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/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/CharUnits.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/RecordLayout.h" 24 #include "clang/AST/RecursiveASTVisitor.h" 25 #include "clang/AST/StmtVisitor.h" 26 #include "clang/AST/TypeLoc.h" 27 #include "clang/AST/TypeOrdering.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/LiteralSupport.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Sema/CXXFieldCollector.h" 33 #include "clang/Sema/DeclSpec.h" 34 #include "clang/Sema/Initialization.h" 35 #include "clang/Sema/Lookup.h" 36 #include "clang/Sema/ParsedTemplate.h" 37 #include "clang/Sema/Scope.h" 38 #include "clang/Sema/ScopeInfo.h" 39 #include "llvm/ADT/STLExtras.h" 40 #include "llvm/ADT/SmallString.h" 41 #include <map> 42 #include <set> 43 44 using namespace clang; 45 46 //===----------------------------------------------------------------------===// 47 // CheckDefaultArgumentVisitor 48 //===----------------------------------------------------------------------===// 49 50 namespace { 51 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 52 /// the default argument of a parameter to determine whether it 53 /// contains any ill-formed subexpressions. For example, this will 54 /// diagnose the use of local variables or parameters within the 55 /// default argument expression. 56 class CheckDefaultArgumentVisitor 57 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 58 Expr *DefaultArg; 59 Sema *S; 60 61 public: 62 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 63 : DefaultArg(defarg), S(s) {} 64 65 bool VisitExpr(Expr *Node); 66 bool VisitDeclRefExpr(DeclRefExpr *DRE); 67 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 68 bool VisitLambdaExpr(LambdaExpr *Lambda); 69 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 70 }; 71 72 /// VisitExpr - Visit all of the children of this expression. 73 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 74 bool IsInvalid = false; 75 for (Stmt::child_range I = Node->children(); I; ++I) 76 IsInvalid |= Visit(*I); 77 return IsInvalid; 78 } 79 80 /// VisitDeclRefExpr - Visit a reference to a declaration, to 81 /// determine whether this declaration can be used in the default 82 /// argument expression. 83 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 84 NamedDecl *Decl = DRE->getDecl(); 85 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 86 // C++ [dcl.fct.default]p9 87 // Default arguments are evaluated each time the function is 88 // called. The order of evaluation of function arguments is 89 // unspecified. Consequently, parameters of a function shall not 90 // be used in default argument expressions, even if they are not 91 // evaluated. Parameters of a function declared before a default 92 // argument expression are in scope and can hide namespace and 93 // class member names. 94 return S->Diag(DRE->getLocStart(), 95 diag::err_param_default_argument_references_param) 96 << Param->getDeclName() << DefaultArg->getSourceRange(); 97 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 98 // C++ [dcl.fct.default]p7 99 // Local variables shall not be used in default argument 100 // expressions. 101 if (VDecl->isLocalVarDecl()) 102 return S->Diag(DRE->getLocStart(), 103 diag::err_param_default_argument_references_local) 104 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 105 } 106 107 return false; 108 } 109 110 /// VisitCXXThisExpr - Visit a C++ "this" expression. 111 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 112 // C++ [dcl.fct.default]p8: 113 // The keyword this shall not be used in a default argument of a 114 // member function. 115 return S->Diag(ThisE->getLocStart(), 116 diag::err_param_default_argument_references_this) 117 << ThisE->getSourceRange(); 118 } 119 120 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 121 bool Invalid = false; 122 for (PseudoObjectExpr::semantics_iterator 123 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 124 Expr *E = *i; 125 126 // Look through bindings. 127 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 128 E = OVE->getSourceExpr(); 129 assert(E && "pseudo-object binding without source expression?"); 130 } 131 132 Invalid |= Visit(E); 133 } 134 return Invalid; 135 } 136 137 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 138 // C++11 [expr.lambda.prim]p13: 139 // A lambda-expression appearing in a default argument shall not 140 // implicitly or explicitly capture any entity. 141 if (Lambda->capture_begin() == Lambda->capture_end()) 142 return false; 143 144 return S->Diag(Lambda->getLocStart(), 145 diag::err_lambda_capture_default_arg); 146 } 147 } 148 149 void 150 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 151 const CXXMethodDecl *Method) { 152 // If we have an MSAny spec already, don't bother. 153 if (!Method || ComputedEST == EST_MSAny) 154 return; 155 156 const FunctionProtoType *Proto 157 = Method->getType()->getAs<FunctionProtoType>(); 158 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 159 if (!Proto) 160 return; 161 162 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 163 164 // If this function can throw any exceptions, make a note of that. 165 if (EST == EST_MSAny || EST == EST_None) { 166 ClearExceptions(); 167 ComputedEST = EST; 168 return; 169 } 170 171 // FIXME: If the call to this decl is using any of its default arguments, we 172 // need to search them for potentially-throwing calls. 173 174 // If this function has a basic noexcept, it doesn't affect the outcome. 175 if (EST == EST_BasicNoexcept) 176 return; 177 178 // If we have a throw-all spec at this point, ignore the function. 179 if (ComputedEST == EST_None) 180 return; 181 182 // If we're still at noexcept(true) and there's a nothrow() callee, 183 // change to that specification. 184 if (EST == EST_DynamicNone) { 185 if (ComputedEST == EST_BasicNoexcept) 186 ComputedEST = EST_DynamicNone; 187 return; 188 } 189 190 // Check out noexcept specs. 191 if (EST == EST_ComputedNoexcept) { 192 FunctionProtoType::NoexceptResult NR = 193 Proto->getNoexceptSpec(Self->Context); 194 assert(NR != FunctionProtoType::NR_NoNoexcept && 195 "Must have noexcept result for EST_ComputedNoexcept."); 196 assert(NR != FunctionProtoType::NR_Dependent && 197 "Should not generate implicit declarations for dependent cases, " 198 "and don't know how to handle them anyway."); 199 200 // noexcept(false) -> no spec on the new function 201 if (NR == FunctionProtoType::NR_Throw) { 202 ClearExceptions(); 203 ComputedEST = EST_None; 204 } 205 // noexcept(true) won't change anything either. 206 return; 207 } 208 209 assert(EST == EST_Dynamic && "EST case not considered earlier."); 210 assert(ComputedEST != EST_None && 211 "Shouldn't collect exceptions when throw-all is guaranteed."); 212 ComputedEST = EST_Dynamic; 213 // Record the exceptions in this function's exception specification. 214 for (const auto &E : Proto->exceptions()) 215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E))) 216 Exceptions.push_back(E); 217 } 218 219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 220 if (!E || ComputedEST == EST_MSAny) 221 return; 222 223 // FIXME: 224 // 225 // C++0x [except.spec]p14: 226 // [An] implicit exception-specification specifies the type-id T if and 227 // only if T is allowed by the exception-specification of a function directly 228 // invoked by f's implicit definition; f shall allow all exceptions if any 229 // function it directly invokes allows all exceptions, and f shall allow no 230 // exceptions if every function it directly invokes allows no exceptions. 231 // 232 // Note in particular that if an implicit exception-specification is generated 233 // for a function containing a throw-expression, that specification can still 234 // be noexcept(true). 235 // 236 // Note also that 'directly invoked' is not defined in the standard, and there 237 // is no indication that we should only consider potentially-evaluated calls. 238 // 239 // Ultimately we should implement the intent of the standard: the exception 240 // specification should be the set of exceptions which can be thrown by the 241 // implicit definition. For now, we assume that any non-nothrow expression can 242 // throw any exception. 243 244 if (Self->canThrow(E)) 245 ComputedEST = EST_None; 246 } 247 248 bool 249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 250 SourceLocation EqualLoc) { 251 if (RequireCompleteType(Param->getLocation(), Param->getType(), 252 diag::err_typecheck_decl_incomplete_type)) { 253 Param->setInvalidDecl(); 254 return true; 255 } 256 257 // C++ [dcl.fct.default]p5 258 // A default argument expression is implicitly converted (clause 259 // 4) to the parameter type. The default argument expression has 260 // the same semantic constraints as the initializer expression in 261 // a declaration of a variable of the parameter type, using the 262 // copy-initialization semantics (8.5). 263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 264 Param); 265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 266 EqualLoc); 267 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 269 if (Result.isInvalid()) 270 return true; 271 Arg = Result.getAs<Expr>(); 272 273 CheckCompletedExpr(Arg, EqualLoc); 274 Arg = MaybeCreateExprWithCleanups(Arg); 275 276 // Okay: add the default argument to the parameter 277 Param->setDefaultArg(Arg); 278 279 // We have already instantiated this parameter; provide each of the 280 // instantiations with the uninstantiated default argument. 281 UnparsedDefaultArgInstantiationsMap::iterator InstPos 282 = UnparsedDefaultArgInstantiations.find(Param); 283 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 286 287 // We're done tracking this parameter's instantiations. 288 UnparsedDefaultArgInstantiations.erase(InstPos); 289 } 290 291 return false; 292 } 293 294 /// ActOnParamDefaultArgument - Check whether the default argument 295 /// provided for a function parameter is well-formed. If so, attach it 296 /// to the parameter declaration. 297 void 298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 299 Expr *DefaultArg) { 300 if (!param || !DefaultArg) 301 return; 302 303 ParmVarDecl *Param = cast<ParmVarDecl>(param); 304 UnparsedDefaultArgLocs.erase(Param); 305 306 // Default arguments are only permitted in C++ 307 if (!getLangOpts().CPlusPlus) { 308 Diag(EqualLoc, diag::err_param_default_argument) 309 << DefaultArg->getSourceRange(); 310 Param->setInvalidDecl(); 311 return; 312 } 313 314 // Check for unexpanded parameter packs. 315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 316 Param->setInvalidDecl(); 317 return; 318 } 319 320 // Check that the default argument is well-formed 321 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 322 if (DefaultArgChecker.Visit(DefaultArg)) { 323 Param->setInvalidDecl(); 324 return; 325 } 326 327 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 328 } 329 330 /// ActOnParamUnparsedDefaultArgument - We've seen a default 331 /// argument for a function parameter, but we can't parse it yet 332 /// because we're inside a class definition. Note that this default 333 /// argument will be parsed later. 334 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 335 SourceLocation EqualLoc, 336 SourceLocation ArgLoc) { 337 if (!param) 338 return; 339 340 ParmVarDecl *Param = cast<ParmVarDecl>(param); 341 Param->setUnparsedDefaultArg(); 342 UnparsedDefaultArgLocs[Param] = ArgLoc; 343 } 344 345 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 346 /// the default argument for the parameter param failed. 347 void Sema::ActOnParamDefaultArgumentError(Decl *param, 348 SourceLocation EqualLoc) { 349 if (!param) 350 return; 351 352 ParmVarDecl *Param = cast<ParmVarDecl>(param); 353 Param->setInvalidDecl(); 354 UnparsedDefaultArgLocs.erase(Param); 355 Param->setDefaultArg(new(Context) 356 OpaqueValueExpr(EqualLoc, Param->getType(), VK_RValue)); 357 } 358 359 /// CheckExtraCXXDefaultArguments - Check for any extra default 360 /// arguments in the declarator, which is not a function declaration 361 /// or definition and therefore is not permitted to have default 362 /// arguments. This routine should be invoked for every declarator 363 /// that is not a function declaration or definition. 364 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 365 // C++ [dcl.fct.default]p3 366 // A default argument expression shall be specified only in the 367 // parameter-declaration-clause of a function declaration or in a 368 // template-parameter (14.1). It shall not be specified for a 369 // parameter pack. If it is specified in a 370 // parameter-declaration-clause, it shall not occur within a 371 // declarator or abstract-declarator of a parameter-declaration. 372 bool MightBeFunction = D.isFunctionDeclarationContext(); 373 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 374 DeclaratorChunk &chunk = D.getTypeObject(i); 375 if (chunk.Kind == DeclaratorChunk::Function) { 376 if (MightBeFunction) { 377 // This is a function declaration. It can have default arguments, but 378 // keep looking in case its return type is a function type with default 379 // arguments. 380 MightBeFunction = false; 381 continue; 382 } 383 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 384 ++argIdx) { 385 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 386 if (Param->hasUnparsedDefaultArg()) { 387 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens; 388 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 389 << SourceRange((*Toks)[1].getLocation(), 390 Toks->back().getLocation()); 391 delete Toks; 392 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr; 393 } else if (Param->getDefaultArg()) { 394 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 395 << Param->getDefaultArg()->getSourceRange(); 396 Param->setDefaultArg(nullptr); 397 } 398 } 399 } else if (chunk.Kind != DeclaratorChunk::Paren) { 400 MightBeFunction = false; 401 } 402 } 403 } 404 405 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 406 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 407 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 408 if (!PVD->hasDefaultArg()) 409 return false; 410 if (!PVD->hasInheritedDefaultArg()) 411 return true; 412 } 413 return false; 414 } 415 416 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 417 /// function, once we already know that they have the same 418 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 419 /// error, false otherwise. 420 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 421 Scope *S) { 422 bool Invalid = false; 423 424 // C++ [dcl.fct.default]p4: 425 // For non-template functions, default arguments can be added in 426 // later declarations of a function in the same 427 // scope. Declarations in different scopes have completely 428 // distinct sets of default arguments. That is, declarations in 429 // inner scopes do not acquire default arguments from 430 // declarations in outer scopes, and vice versa. In a given 431 // function declaration, all parameters subsequent to a 432 // parameter with a default argument shall have default 433 // arguments supplied in this or previous declarations. A 434 // default argument shall not be redefined by a later 435 // declaration (not even to the same value). 436 // 437 // C++ [dcl.fct.default]p6: 438 // Except for member functions of class templates, the default arguments 439 // in a member function definition that appears outside of the class 440 // definition are added to the set of default arguments provided by the 441 // member function declaration in the class definition. 442 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 443 ParmVarDecl *OldParam = Old->getParamDecl(p); 444 ParmVarDecl *NewParam = New->getParamDecl(p); 445 446 bool OldParamHasDfl = OldParam->hasDefaultArg(); 447 bool NewParamHasDfl = NewParam->hasDefaultArg(); 448 449 NamedDecl *ND = Old; 450 451 // The declaration context corresponding to the scope is the semantic 452 // parent, unless this is a local function declaration, in which case 453 // it is that surrounding function. 454 DeclContext *ScopeDC = New->getLexicalDeclContext(); 455 if (!ScopeDC->isFunctionOrMethod()) 456 ScopeDC = New->getDeclContext(); 457 if (S && !isDeclInScope(ND, ScopeDC, S) && 458 !New->getDeclContext()->isRecord()) 459 // Ignore default parameters of old decl if they are not in 460 // the same scope and this is not an out-of-line definition of 461 // a member function. 462 OldParamHasDfl = false; 463 464 if (OldParamHasDfl && NewParamHasDfl) { 465 466 unsigned DiagDefaultParamID = 467 diag::err_param_default_argument_redefinition; 468 469 // MSVC accepts that default parameters be redefined for member functions 470 // of template class. The new default parameter's value is ignored. 471 Invalid = true; 472 if (getLangOpts().MicrosoftExt) { 473 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 474 if (MD && MD->getParent()->getDescribedClassTemplate()) { 475 // Merge the old default argument into the new parameter. 476 NewParam->setHasInheritedDefaultArg(); 477 if (OldParam->hasUninstantiatedDefaultArg()) 478 NewParam->setUninstantiatedDefaultArg( 479 OldParam->getUninstantiatedDefaultArg()); 480 else 481 NewParam->setDefaultArg(OldParam->getInit()); 482 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 483 Invalid = false; 484 } 485 } 486 487 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 488 // hint here. Alternatively, we could walk the type-source information 489 // for NewParam to find the last source location in the type... but it 490 // isn't worth the effort right now. This is the kind of test case that 491 // is hard to get right: 492 // int f(int); 493 // void g(int (*fp)(int) = f); 494 // void g(int (*fp)(int) = &f); 495 Diag(NewParam->getLocation(), DiagDefaultParamID) 496 << NewParam->getDefaultArgRange(); 497 498 // Look for the function declaration where the default argument was 499 // actually written, which may be a declaration prior to Old. 500 for (FunctionDecl *Older = Old->getPreviousDecl(); 501 Older; Older = Older->getPreviousDecl()) { 502 if (!Older->getParamDecl(p)->hasDefaultArg()) 503 break; 504 505 OldParam = Older->getParamDecl(p); 506 } 507 508 Diag(OldParam->getLocation(), diag::note_previous_definition) 509 << OldParam->getDefaultArgRange(); 510 } else if (OldParamHasDfl) { 511 // Merge the old default argument into the new parameter. 512 // It's important to use getInit() here; getDefaultArg() 513 // strips off any top-level ExprWithCleanups. 514 NewParam->setHasInheritedDefaultArg(); 515 if (OldParam->hasUninstantiatedDefaultArg()) 516 NewParam->setUninstantiatedDefaultArg( 517 OldParam->getUninstantiatedDefaultArg()); 518 else 519 NewParam->setDefaultArg(OldParam->getInit()); 520 } else if (NewParamHasDfl) { 521 if (New->getDescribedFunctionTemplate()) { 522 // Paragraph 4, quoted above, only applies to non-template functions. 523 Diag(NewParam->getLocation(), 524 diag::err_param_default_argument_template_redecl) 525 << NewParam->getDefaultArgRange(); 526 Diag(Old->getLocation(), diag::note_template_prev_declaration) 527 << false; 528 } else if (New->getTemplateSpecializationKind() 529 != TSK_ImplicitInstantiation && 530 New->getTemplateSpecializationKind() != TSK_Undeclared) { 531 // C++ [temp.expr.spec]p21: 532 // Default function arguments shall not be specified in a declaration 533 // or a definition for one of the following explicit specializations: 534 // - the explicit specialization of a function template; 535 // - the explicit specialization of a member function template; 536 // - the explicit specialization of a member function of a class 537 // template where the class template specialization to which the 538 // member function specialization belongs is implicitly 539 // instantiated. 540 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 541 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 542 << New->getDeclName() 543 << NewParam->getDefaultArgRange(); 544 } else if (New->getDeclContext()->isDependentContext()) { 545 // C++ [dcl.fct.default]p6 (DR217): 546 // Default arguments for a member function of a class template shall 547 // be specified on the initial declaration of the member function 548 // within the class template. 549 // 550 // Reading the tea leaves a bit in DR217 and its reference to DR205 551 // leads me to the conclusion that one cannot add default function 552 // arguments for an out-of-line definition of a member function of a 553 // dependent type. 554 int WhichKind = 2; 555 if (CXXRecordDecl *Record 556 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 557 if (Record->getDescribedClassTemplate()) 558 WhichKind = 0; 559 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 560 WhichKind = 1; 561 else 562 WhichKind = 2; 563 } 564 565 Diag(NewParam->getLocation(), 566 diag::err_param_default_argument_member_template_redecl) 567 << WhichKind 568 << NewParam->getDefaultArgRange(); 569 } 570 } 571 } 572 573 // DR1344: If a default argument is added outside a class definition and that 574 // default argument makes the function a special member function, the program 575 // is ill-formed. This can only happen for constructors. 576 if (isa<CXXConstructorDecl>(New) && 577 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 578 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 579 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 580 if (NewSM != OldSM) { 581 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 582 assert(NewParam->hasDefaultArg()); 583 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 584 << NewParam->getDefaultArgRange() << NewSM; 585 Diag(Old->getLocation(), diag::note_previous_declaration); 586 } 587 } 588 589 const FunctionDecl *Def; 590 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 591 // template has a constexpr specifier then all its declarations shall 592 // contain the constexpr specifier. 593 if (New->isConstexpr() != Old->isConstexpr()) { 594 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 595 << New << New->isConstexpr(); 596 Diag(Old->getLocation(), diag::note_previous_declaration); 597 Invalid = true; 598 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) { 599 // C++11 [dcl.fcn.spec]p4: 600 // If the definition of a function appears in a translation unit before its 601 // first declaration as inline, the program is ill-formed. 602 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 603 Diag(Def->getLocation(), diag::note_previous_definition); 604 Invalid = true; 605 } 606 607 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 608 // argument expression, that declaration shall be a definition and shall be 609 // the only declaration of the function or function template in the 610 // translation unit. 611 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 612 functionDeclHasDefaultArgument(Old)) { 613 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 614 Diag(Old->getLocation(), diag::note_previous_declaration); 615 Invalid = true; 616 } 617 618 if (CheckEquivalentExceptionSpec(Old, New)) 619 Invalid = true; 620 621 return Invalid; 622 } 623 624 /// \brief Merge the exception specifications of two variable declarations. 625 /// 626 /// This is called when there's a redeclaration of a VarDecl. The function 627 /// checks if the redeclaration might have an exception specification and 628 /// validates compatibility and merges the specs if necessary. 629 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 630 // Shortcut if exceptions are disabled. 631 if (!getLangOpts().CXXExceptions) 632 return; 633 634 assert(Context.hasSameType(New->getType(), Old->getType()) && 635 "Should only be called if types are otherwise the same."); 636 637 QualType NewType = New->getType(); 638 QualType OldType = Old->getType(); 639 640 // We're only interested in pointers and references to functions, as well 641 // as pointers to member functions. 642 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 643 NewType = R->getPointeeType(); 644 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 645 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 646 NewType = P->getPointeeType(); 647 OldType = OldType->getAs<PointerType>()->getPointeeType(); 648 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 649 NewType = M->getPointeeType(); 650 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 651 } 652 653 if (!NewType->isFunctionProtoType()) 654 return; 655 656 // There's lots of special cases for functions. For function pointers, system 657 // libraries are hopefully not as broken so that we don't need these 658 // workarounds. 659 if (CheckEquivalentExceptionSpec( 660 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 661 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 662 New->setInvalidDecl(); 663 } 664 } 665 666 /// CheckCXXDefaultArguments - Verify that the default arguments for a 667 /// function declaration are well-formed according to C++ 668 /// [dcl.fct.default]. 669 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 670 unsigned NumParams = FD->getNumParams(); 671 unsigned p; 672 673 // Find first parameter with a default argument 674 for (p = 0; p < NumParams; ++p) { 675 ParmVarDecl *Param = FD->getParamDecl(p); 676 if (Param->hasDefaultArg()) 677 break; 678 } 679 680 // C++ [dcl.fct.default]p4: 681 // In a given function declaration, all parameters 682 // subsequent to a parameter with a default argument shall 683 // have default arguments supplied in this or previous 684 // declarations. A default argument shall not be redefined 685 // by a later declaration (not even to the same value). 686 unsigned LastMissingDefaultArg = 0; 687 for (; p < NumParams; ++p) { 688 ParmVarDecl *Param = FD->getParamDecl(p); 689 if (!Param->hasDefaultArg()) { 690 if (Param->isInvalidDecl()) 691 /* We already complained about this parameter. */; 692 else if (Param->getIdentifier()) 693 Diag(Param->getLocation(), 694 diag::err_param_default_argument_missing_name) 695 << Param->getIdentifier(); 696 else 697 Diag(Param->getLocation(), 698 diag::err_param_default_argument_missing); 699 700 LastMissingDefaultArg = p; 701 } 702 } 703 704 if (LastMissingDefaultArg > 0) { 705 // Some default arguments were missing. Clear out all of the 706 // default arguments up to (and including) the last missing 707 // default argument, so that we leave the function parameters 708 // in a semantically valid state. 709 for (p = 0; p <= LastMissingDefaultArg; ++p) { 710 ParmVarDecl *Param = FD->getParamDecl(p); 711 if (Param->hasDefaultArg()) { 712 Param->setDefaultArg(nullptr); 713 } 714 } 715 } 716 } 717 718 // CheckConstexprParameterTypes - Check whether a function's parameter types 719 // are all literal types. If so, return true. If not, produce a suitable 720 // diagnostic and return false. 721 static bool CheckConstexprParameterTypes(Sema &SemaRef, 722 const FunctionDecl *FD) { 723 unsigned ArgIndex = 0; 724 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 725 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 726 e = FT->param_type_end(); 727 i != e; ++i, ++ArgIndex) { 728 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 729 SourceLocation ParamLoc = PD->getLocation(); 730 if (!(*i)->isDependentType() && 731 SemaRef.RequireLiteralType(ParamLoc, *i, 732 diag::err_constexpr_non_literal_param, 733 ArgIndex+1, PD->getSourceRange(), 734 isa<CXXConstructorDecl>(FD))) 735 return false; 736 } 737 return true; 738 } 739 740 /// \brief Get diagnostic %select index for tag kind for 741 /// record diagnostic message. 742 /// WARNING: Indexes apply to particular diagnostics only! 743 /// 744 /// \returns diagnostic %select index. 745 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 746 switch (Tag) { 747 case TTK_Struct: return 0; 748 case TTK_Interface: return 1; 749 case TTK_Class: return 2; 750 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 751 } 752 } 753 754 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 755 // the requirements of a constexpr function definition or a constexpr 756 // constructor definition. If so, return true. If not, produce appropriate 757 // diagnostics and return false. 758 // 759 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 760 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 761 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 762 if (MD && MD->isInstance()) { 763 // C++11 [dcl.constexpr]p4: 764 // The definition of a constexpr constructor shall satisfy the following 765 // constraints: 766 // - the class shall not have any virtual base classes; 767 const CXXRecordDecl *RD = MD->getParent(); 768 if (RD->getNumVBases()) { 769 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 770 << isa<CXXConstructorDecl>(NewFD) 771 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 772 for (const auto &I : RD->vbases()) 773 Diag(I.getLocStart(), 774 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 775 return false; 776 } 777 } 778 779 if (!isa<CXXConstructorDecl>(NewFD)) { 780 // C++11 [dcl.constexpr]p3: 781 // The definition of a constexpr function shall satisfy the following 782 // constraints: 783 // - it shall not be virtual; 784 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 785 if (Method && Method->isVirtual()) { 786 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 787 788 // If it's not obvious why this function is virtual, find an overridden 789 // function which uses the 'virtual' keyword. 790 const CXXMethodDecl *WrittenVirtual = Method; 791 while (!WrittenVirtual->isVirtualAsWritten()) 792 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 793 if (WrittenVirtual != Method) 794 Diag(WrittenVirtual->getLocation(), 795 diag::note_overridden_virtual_function); 796 return false; 797 } 798 799 // - its return type shall be a literal type; 800 QualType RT = NewFD->getReturnType(); 801 if (!RT->isDependentType() && 802 RequireLiteralType(NewFD->getLocation(), RT, 803 diag::err_constexpr_non_literal_return)) 804 return false; 805 } 806 807 // - each of its parameter types shall be a literal type; 808 if (!CheckConstexprParameterTypes(*this, NewFD)) 809 return false; 810 811 return true; 812 } 813 814 /// Check the given declaration statement is legal within a constexpr function 815 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 816 /// 817 /// \return true if the body is OK (maybe only as an extension), false if we 818 /// have diagnosed a problem. 819 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 820 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 821 // C++11 [dcl.constexpr]p3 and p4: 822 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 823 // contain only 824 for (const auto *DclIt : DS->decls()) { 825 switch (DclIt->getKind()) { 826 case Decl::StaticAssert: 827 case Decl::Using: 828 case Decl::UsingShadow: 829 case Decl::UsingDirective: 830 case Decl::UnresolvedUsingTypename: 831 case Decl::UnresolvedUsingValue: 832 // - static_assert-declarations 833 // - using-declarations, 834 // - using-directives, 835 continue; 836 837 case Decl::Typedef: 838 case Decl::TypeAlias: { 839 // - typedef declarations and alias-declarations that do not define 840 // classes or enumerations, 841 const auto *TN = cast<TypedefNameDecl>(DclIt); 842 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 843 // Don't allow variably-modified types in constexpr functions. 844 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 845 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 846 << TL.getSourceRange() << TL.getType() 847 << isa<CXXConstructorDecl>(Dcl); 848 return false; 849 } 850 continue; 851 } 852 853 case Decl::Enum: 854 case Decl::CXXRecord: 855 // C++1y allows types to be defined, not just declared. 856 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 857 SemaRef.Diag(DS->getLocStart(), 858 SemaRef.getLangOpts().CPlusPlus1y 859 ? diag::warn_cxx11_compat_constexpr_type_definition 860 : diag::ext_constexpr_type_definition) 861 << isa<CXXConstructorDecl>(Dcl); 862 continue; 863 864 case Decl::EnumConstant: 865 case Decl::IndirectField: 866 case Decl::ParmVar: 867 // These can only appear with other declarations which are banned in 868 // C++11 and permitted in C++1y, so ignore them. 869 continue; 870 871 case Decl::Var: { 872 // C++1y [dcl.constexpr]p3 allows anything except: 873 // a definition of a variable of non-literal type or of static or 874 // thread storage duration or for which no initialization is performed. 875 const auto *VD = cast<VarDecl>(DclIt); 876 if (VD->isThisDeclarationADefinition()) { 877 if (VD->isStaticLocal()) { 878 SemaRef.Diag(VD->getLocation(), 879 diag::err_constexpr_local_var_static) 880 << isa<CXXConstructorDecl>(Dcl) 881 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 882 return false; 883 } 884 if (!VD->getType()->isDependentType() && 885 SemaRef.RequireLiteralType( 886 VD->getLocation(), VD->getType(), 887 diag::err_constexpr_local_var_non_literal_type, 888 isa<CXXConstructorDecl>(Dcl))) 889 return false; 890 if (!VD->getType()->isDependentType() && 891 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 892 SemaRef.Diag(VD->getLocation(), 893 diag::err_constexpr_local_var_no_init) 894 << isa<CXXConstructorDecl>(Dcl); 895 return false; 896 } 897 } 898 SemaRef.Diag(VD->getLocation(), 899 SemaRef.getLangOpts().CPlusPlus1y 900 ? diag::warn_cxx11_compat_constexpr_local_var 901 : diag::ext_constexpr_local_var) 902 << isa<CXXConstructorDecl>(Dcl); 903 continue; 904 } 905 906 case Decl::NamespaceAlias: 907 case Decl::Function: 908 // These are disallowed in C++11 and permitted in C++1y. Allow them 909 // everywhere as an extension. 910 if (!Cxx1yLoc.isValid()) 911 Cxx1yLoc = DS->getLocStart(); 912 continue; 913 914 default: 915 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 916 << isa<CXXConstructorDecl>(Dcl); 917 return false; 918 } 919 } 920 921 return true; 922 } 923 924 /// Check that the given field is initialized within a constexpr constructor. 925 /// 926 /// \param Dcl The constexpr constructor being checked. 927 /// \param Field The field being checked. This may be a member of an anonymous 928 /// struct or union nested within the class being checked. 929 /// \param Inits All declarations, including anonymous struct/union members and 930 /// indirect members, for which any initialization was provided. 931 /// \param Diagnosed Set to true if an error is produced. 932 static void CheckConstexprCtorInitializer(Sema &SemaRef, 933 const FunctionDecl *Dcl, 934 FieldDecl *Field, 935 llvm::SmallSet<Decl*, 16> &Inits, 936 bool &Diagnosed) { 937 if (Field->isInvalidDecl()) 938 return; 939 940 if (Field->isUnnamedBitfield()) 941 return; 942 943 // Anonymous unions with no variant members and empty anonymous structs do not 944 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 945 // indirect fields don't need initializing. 946 if (Field->isAnonymousStructOrUnion() && 947 (Field->getType()->isUnionType() 948 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 949 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 950 return; 951 952 if (!Inits.count(Field)) { 953 if (!Diagnosed) { 954 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 955 Diagnosed = true; 956 } 957 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 958 } else if (Field->isAnonymousStructOrUnion()) { 959 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 960 for (auto *I : RD->fields()) 961 // If an anonymous union contains an anonymous struct of which any member 962 // is initialized, all members must be initialized. 963 if (!RD->isUnion() || Inits.count(I)) 964 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 965 } 966 } 967 968 /// Check the provided statement is allowed in a constexpr function 969 /// definition. 970 static bool 971 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 972 SmallVectorImpl<SourceLocation> &ReturnStmts, 973 SourceLocation &Cxx1yLoc) { 974 // - its function-body shall be [...] a compound-statement that contains only 975 switch (S->getStmtClass()) { 976 case Stmt::NullStmtClass: 977 // - null statements, 978 return true; 979 980 case Stmt::DeclStmtClass: 981 // - static_assert-declarations 982 // - using-declarations, 983 // - using-directives, 984 // - typedef declarations and alias-declarations that do not define 985 // classes or enumerations, 986 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 987 return false; 988 return true; 989 990 case Stmt::ReturnStmtClass: 991 // - and exactly one return statement; 992 if (isa<CXXConstructorDecl>(Dcl)) { 993 // C++1y allows return statements in constexpr constructors. 994 if (!Cxx1yLoc.isValid()) 995 Cxx1yLoc = S->getLocStart(); 996 return true; 997 } 998 999 ReturnStmts.push_back(S->getLocStart()); 1000 return true; 1001 1002 case Stmt::CompoundStmtClass: { 1003 // C++1y allows compound-statements. 1004 if (!Cxx1yLoc.isValid()) 1005 Cxx1yLoc = S->getLocStart(); 1006 1007 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1008 for (auto *BodyIt : CompStmt->body()) { 1009 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1010 Cxx1yLoc)) 1011 return false; 1012 } 1013 return true; 1014 } 1015 1016 case Stmt::AttributedStmtClass: 1017 if (!Cxx1yLoc.isValid()) 1018 Cxx1yLoc = S->getLocStart(); 1019 return true; 1020 1021 case Stmt::IfStmtClass: { 1022 // C++1y allows if-statements. 1023 if (!Cxx1yLoc.isValid()) 1024 Cxx1yLoc = S->getLocStart(); 1025 1026 IfStmt *If = cast<IfStmt>(S); 1027 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1028 Cxx1yLoc)) 1029 return false; 1030 if (If->getElse() && 1031 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1032 Cxx1yLoc)) 1033 return false; 1034 return true; 1035 } 1036 1037 case Stmt::WhileStmtClass: 1038 case Stmt::DoStmtClass: 1039 case Stmt::ForStmtClass: 1040 case Stmt::CXXForRangeStmtClass: 1041 case Stmt::ContinueStmtClass: 1042 // C++1y allows all of these. We don't allow them as extensions in C++11, 1043 // because they don't make sense without variable mutation. 1044 if (!SemaRef.getLangOpts().CPlusPlus1y) 1045 break; 1046 if (!Cxx1yLoc.isValid()) 1047 Cxx1yLoc = S->getLocStart(); 1048 for (Stmt::child_range Children = S->children(); Children; ++Children) 1049 if (*Children && 1050 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1051 Cxx1yLoc)) 1052 return false; 1053 return true; 1054 1055 case Stmt::SwitchStmtClass: 1056 case Stmt::CaseStmtClass: 1057 case Stmt::DefaultStmtClass: 1058 case Stmt::BreakStmtClass: 1059 // C++1y allows switch-statements, and since they don't need variable 1060 // mutation, we can reasonably allow them in C++11 as an extension. 1061 if (!Cxx1yLoc.isValid()) 1062 Cxx1yLoc = S->getLocStart(); 1063 for (Stmt::child_range Children = S->children(); Children; ++Children) 1064 if (*Children && 1065 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1066 Cxx1yLoc)) 1067 return false; 1068 return true; 1069 1070 default: 1071 if (!isa<Expr>(S)) 1072 break; 1073 1074 // C++1y allows expression-statements. 1075 if (!Cxx1yLoc.isValid()) 1076 Cxx1yLoc = S->getLocStart(); 1077 return true; 1078 } 1079 1080 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1081 << isa<CXXConstructorDecl>(Dcl); 1082 return false; 1083 } 1084 1085 /// Check the body for the given constexpr function declaration only contains 1086 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1087 /// 1088 /// \return true if the body is OK, false if we have diagnosed a problem. 1089 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1090 if (isa<CXXTryStmt>(Body)) { 1091 // C++11 [dcl.constexpr]p3: 1092 // The definition of a constexpr function shall satisfy the following 1093 // constraints: [...] 1094 // - its function-body shall be = delete, = default, or a 1095 // compound-statement 1096 // 1097 // C++11 [dcl.constexpr]p4: 1098 // In the definition of a constexpr constructor, [...] 1099 // - its function-body shall not be a function-try-block; 1100 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1101 << isa<CXXConstructorDecl>(Dcl); 1102 return false; 1103 } 1104 1105 SmallVector<SourceLocation, 4> ReturnStmts; 1106 1107 // - its function-body shall be [...] a compound-statement that contains only 1108 // [... list of cases ...] 1109 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1110 SourceLocation Cxx1yLoc; 1111 for (auto *BodyIt : CompBody->body()) { 1112 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1113 return false; 1114 } 1115 1116 if (Cxx1yLoc.isValid()) 1117 Diag(Cxx1yLoc, 1118 getLangOpts().CPlusPlus1y 1119 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1120 : diag::ext_constexpr_body_invalid_stmt) 1121 << isa<CXXConstructorDecl>(Dcl); 1122 1123 if (const CXXConstructorDecl *Constructor 1124 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1125 const CXXRecordDecl *RD = Constructor->getParent(); 1126 // DR1359: 1127 // - every non-variant non-static data member and base class sub-object 1128 // shall be initialized; 1129 // DR1460: 1130 // - if the class is a union having variant members, exactly one of them 1131 // shall be initialized; 1132 if (RD->isUnion()) { 1133 if (Constructor->getNumCtorInitializers() == 0 && 1134 RD->hasVariantMembers()) { 1135 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1136 return false; 1137 } 1138 } else if (!Constructor->isDependentContext() && 1139 !Constructor->isDelegatingConstructor()) { 1140 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1141 1142 // Skip detailed checking if we have enough initializers, and we would 1143 // allow at most one initializer per member. 1144 bool AnyAnonStructUnionMembers = false; 1145 unsigned Fields = 0; 1146 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1147 E = RD->field_end(); I != E; ++I, ++Fields) { 1148 if (I->isAnonymousStructOrUnion()) { 1149 AnyAnonStructUnionMembers = true; 1150 break; 1151 } 1152 } 1153 // DR1460: 1154 // - if the class is a union-like class, but is not a union, for each of 1155 // its anonymous union members having variant members, exactly one of 1156 // them shall be initialized; 1157 if (AnyAnonStructUnionMembers || 1158 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1159 // Check initialization of non-static data members. Base classes are 1160 // always initialized so do not need to be checked. Dependent bases 1161 // might not have initializers in the member initializer list. 1162 llvm::SmallSet<Decl*, 16> Inits; 1163 for (const auto *I: Constructor->inits()) { 1164 if (FieldDecl *FD = I->getMember()) 1165 Inits.insert(FD); 1166 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1167 Inits.insert(ID->chain_begin(), ID->chain_end()); 1168 } 1169 1170 bool Diagnosed = false; 1171 for (auto *I : RD->fields()) 1172 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1173 if (Diagnosed) 1174 return false; 1175 } 1176 } 1177 } else { 1178 if (ReturnStmts.empty()) { 1179 // C++1y doesn't require constexpr functions to contain a 'return' 1180 // statement. We still do, unless the return type might be void, because 1181 // otherwise if there's no return statement, the function cannot 1182 // be used in a core constant expression. 1183 bool OK = getLangOpts().CPlusPlus1y && 1184 (Dcl->getReturnType()->isVoidType() || 1185 Dcl->getReturnType()->isDependentType()); 1186 Diag(Dcl->getLocation(), 1187 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1188 : diag::err_constexpr_body_no_return); 1189 return OK; 1190 } 1191 if (ReturnStmts.size() > 1) { 1192 Diag(ReturnStmts.back(), 1193 getLangOpts().CPlusPlus1y 1194 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1195 : diag::ext_constexpr_body_multiple_return); 1196 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1197 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1198 } 1199 } 1200 1201 // C++11 [dcl.constexpr]p5: 1202 // if no function argument values exist such that the function invocation 1203 // substitution would produce a constant expression, the program is 1204 // ill-formed; no diagnostic required. 1205 // C++11 [dcl.constexpr]p3: 1206 // - every constructor call and implicit conversion used in initializing the 1207 // return value shall be one of those allowed in a constant expression. 1208 // C++11 [dcl.constexpr]p4: 1209 // - every constructor involved in initializing non-static data members and 1210 // base class sub-objects shall be a constexpr constructor. 1211 SmallVector<PartialDiagnosticAt, 8> Diags; 1212 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1213 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1214 << isa<CXXConstructorDecl>(Dcl); 1215 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1216 Diag(Diags[I].first, Diags[I].second); 1217 // Don't return false here: we allow this for compatibility in 1218 // system headers. 1219 } 1220 1221 return true; 1222 } 1223 1224 /// isCurrentClassName - Determine whether the identifier II is the 1225 /// name of the class type currently being defined. In the case of 1226 /// nested classes, this will only return true if II is the name of 1227 /// the innermost class. 1228 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1229 const CXXScopeSpec *SS) { 1230 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1231 1232 CXXRecordDecl *CurDecl; 1233 if (SS && SS->isSet() && !SS->isInvalid()) { 1234 DeclContext *DC = computeDeclContext(*SS, true); 1235 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1236 } else 1237 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1238 1239 if (CurDecl && CurDecl->getIdentifier()) 1240 return &II == CurDecl->getIdentifier(); 1241 return false; 1242 } 1243 1244 /// \brief Determine whether the identifier II is a typo for the name of 1245 /// the class type currently being defined. If so, update it to the identifier 1246 /// that should have been used. 1247 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1248 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1249 1250 if (!getLangOpts().SpellChecking) 1251 return false; 1252 1253 CXXRecordDecl *CurDecl; 1254 if (SS && SS->isSet() && !SS->isInvalid()) { 1255 DeclContext *DC = computeDeclContext(*SS, true); 1256 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1257 } else 1258 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1259 1260 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1261 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1262 < II->getLength()) { 1263 II = CurDecl->getIdentifier(); 1264 return true; 1265 } 1266 1267 return false; 1268 } 1269 1270 /// \brief Determine whether the given class is a base class of the given 1271 /// class, including looking at dependent bases. 1272 static bool findCircularInheritance(const CXXRecordDecl *Class, 1273 const CXXRecordDecl *Current) { 1274 SmallVector<const CXXRecordDecl*, 8> Queue; 1275 1276 Class = Class->getCanonicalDecl(); 1277 while (true) { 1278 for (const auto &I : Current->bases()) { 1279 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 1280 if (!Base) 1281 continue; 1282 1283 Base = Base->getDefinition(); 1284 if (!Base) 1285 continue; 1286 1287 if (Base->getCanonicalDecl() == Class) 1288 return true; 1289 1290 Queue.push_back(Base); 1291 } 1292 1293 if (Queue.empty()) 1294 return false; 1295 1296 Current = Queue.pop_back_val(); 1297 } 1298 1299 return false; 1300 } 1301 1302 /// \brief Perform propagation of DLL attributes from a derived class to a 1303 /// templated base class for MS compatibility. 1304 static void propagateDLLAttrToBaseClassTemplate( 1305 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr, 1306 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 1307 if (getDLLAttr( 1308 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 1309 // If the base class template has a DLL attribute, don't try to change it. 1310 return; 1311 } 1312 1313 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 1314 // If the base class is not already specialized, we can do the propagation. 1315 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 1316 NewAttr->setInherited(true); 1317 BaseTemplateSpec->addAttr(NewAttr); 1318 return; 1319 } 1320 1321 bool DifferentAttribute = false; 1322 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) { 1323 if (!SpecializationAttr->isInherited()) { 1324 // The template has previously been specialized or instantiated with an 1325 // explicit attribute. We should not try to change it. 1326 return; 1327 } 1328 if (SpecializationAttr->getKind() == ClassAttr->getKind()) { 1329 // The specialization already has the right attribute. 1330 return; 1331 } 1332 DifferentAttribute = true; 1333 } 1334 1335 // The template was previously instantiated or explicitly specialized without 1336 // a dll attribute, or the template was previously instantiated with a 1337 // different inherited attribute. It's too late for us to change the 1338 // attribute, so warn that this is unsupported. 1339 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 1340 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute; 1341 S.Diag(ClassAttr->getLocation(), diag::note_attribute); 1342 if (BaseTemplateSpec->isExplicitSpecialization()) { 1343 S.Diag(BaseTemplateSpec->getLocation(), 1344 diag::note_template_class_explicit_specialization_was_here) 1345 << BaseTemplateSpec; 1346 } else { 1347 S.Diag(BaseTemplateSpec->getPointOfInstantiation(), 1348 diag::note_template_class_instantiation_was_here) 1349 << BaseTemplateSpec; 1350 } 1351 } 1352 1353 /// \brief Check the validity of a C++ base class specifier. 1354 /// 1355 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1356 /// and returns NULL otherwise. 1357 CXXBaseSpecifier * 1358 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1359 SourceRange SpecifierRange, 1360 bool Virtual, AccessSpecifier Access, 1361 TypeSourceInfo *TInfo, 1362 SourceLocation EllipsisLoc) { 1363 QualType BaseType = TInfo->getType(); 1364 1365 // C++ [class.union]p1: 1366 // A union shall not have base classes. 1367 if (Class->isUnion()) { 1368 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1369 << SpecifierRange; 1370 return nullptr; 1371 } 1372 1373 if (EllipsisLoc.isValid() && 1374 !TInfo->getType()->containsUnexpandedParameterPack()) { 1375 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1376 << TInfo->getTypeLoc().getSourceRange(); 1377 EllipsisLoc = SourceLocation(); 1378 } 1379 1380 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1381 1382 if (BaseType->isDependentType()) { 1383 // Make sure that we don't have circular inheritance among our dependent 1384 // bases. For non-dependent bases, the check for completeness below handles 1385 // this. 1386 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1387 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1388 ((BaseDecl = BaseDecl->getDefinition()) && 1389 findCircularInheritance(Class, BaseDecl))) { 1390 Diag(BaseLoc, diag::err_circular_inheritance) 1391 << BaseType << Context.getTypeDeclType(Class); 1392 1393 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1394 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1395 << BaseType; 1396 1397 return nullptr; 1398 } 1399 } 1400 1401 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1402 Class->getTagKind() == TTK_Class, 1403 Access, TInfo, EllipsisLoc); 1404 } 1405 1406 // Base specifiers must be record types. 1407 if (!BaseType->isRecordType()) { 1408 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1409 return nullptr; 1410 } 1411 1412 // C++ [class.union]p1: 1413 // A union shall not be used as a base class. 1414 if (BaseType->isUnionType()) { 1415 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1416 return nullptr; 1417 } 1418 1419 // For the MS ABI, propagate DLL attributes to base class templates. 1420 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1421 if (Attr *ClassAttr = getDLLAttr(Class)) { 1422 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 1423 BaseType->getAsCXXRecordDecl())) { 1424 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr, 1425 BaseTemplate, BaseLoc); 1426 } 1427 } 1428 } 1429 1430 // C++ [class.derived]p2: 1431 // The class-name in a base-specifier shall not be an incompletely 1432 // defined class. 1433 if (RequireCompleteType(BaseLoc, BaseType, 1434 diag::err_incomplete_base_class, SpecifierRange)) { 1435 Class->setInvalidDecl(); 1436 return nullptr; 1437 } 1438 1439 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1440 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1441 assert(BaseDecl && "Record type has no declaration"); 1442 BaseDecl = BaseDecl->getDefinition(); 1443 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1444 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1445 assert(CXXBaseDecl && "Base type is not a C++ type"); 1446 1447 // A class which contains a flexible array member is not suitable for use as a 1448 // base class: 1449 // - If the layout determines that a base comes before another base, 1450 // the flexible array member would index into the subsequent base. 1451 // - If the layout determines that base comes before the derived class, 1452 // the flexible array member would index into the derived class. 1453 if (CXXBaseDecl->hasFlexibleArrayMember()) { 1454 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 1455 << CXXBaseDecl->getDeclName(); 1456 return nullptr; 1457 } 1458 1459 // C++ [class]p3: 1460 // If a class is marked final and it appears as a base-type-specifier in 1461 // base-clause, the program is ill-formed. 1462 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1463 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1464 << CXXBaseDecl->getDeclName() 1465 << FA->isSpelledAsSealed(); 1466 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 1467 << CXXBaseDecl->getDeclName() << FA->getRange(); 1468 return nullptr; 1469 } 1470 1471 if (BaseDecl->isInvalidDecl()) 1472 Class->setInvalidDecl(); 1473 1474 // Create the base specifier. 1475 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1476 Class->getTagKind() == TTK_Class, 1477 Access, TInfo, EllipsisLoc); 1478 } 1479 1480 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1481 /// one entry in the base class list of a class specifier, for 1482 /// example: 1483 /// class foo : public bar, virtual private baz { 1484 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1485 BaseResult 1486 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1487 ParsedAttributes &Attributes, 1488 bool Virtual, AccessSpecifier Access, 1489 ParsedType basetype, SourceLocation BaseLoc, 1490 SourceLocation EllipsisLoc) { 1491 if (!classdecl) 1492 return true; 1493 1494 AdjustDeclIfTemplate(classdecl); 1495 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1496 if (!Class) 1497 return true; 1498 1499 // We haven't yet attached the base specifiers. 1500 Class->setIsParsingBaseSpecifiers(); 1501 1502 // We do not support any C++11 attributes on base-specifiers yet. 1503 // Diagnose any attributes we see. 1504 if (!Attributes.empty()) { 1505 for (AttributeList *Attr = Attributes.getList(); Attr; 1506 Attr = Attr->getNext()) { 1507 if (Attr->isInvalid() || 1508 Attr->getKind() == AttributeList::IgnoredAttribute) 1509 continue; 1510 Diag(Attr->getLoc(), 1511 Attr->getKind() == AttributeList::UnknownAttribute 1512 ? diag::warn_unknown_attribute_ignored 1513 : diag::err_base_specifier_attribute) 1514 << Attr->getName(); 1515 } 1516 } 1517 1518 TypeSourceInfo *TInfo = nullptr; 1519 GetTypeFromParser(basetype, &TInfo); 1520 1521 if (EllipsisLoc.isInvalid() && 1522 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1523 UPPC_BaseType)) 1524 return true; 1525 1526 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1527 Virtual, Access, TInfo, 1528 EllipsisLoc)) 1529 return BaseSpec; 1530 else 1531 Class->setInvalidDecl(); 1532 1533 return true; 1534 } 1535 1536 /// \brief Performs the actual work of attaching the given base class 1537 /// specifiers to a C++ class. 1538 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1539 unsigned NumBases) { 1540 if (NumBases == 0) 1541 return false; 1542 1543 // Used to keep track of which base types we have already seen, so 1544 // that we can properly diagnose redundant direct base types. Note 1545 // that the key is always the unqualified canonical type of the base 1546 // class. 1547 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1548 1549 // Copy non-redundant base specifiers into permanent storage. 1550 unsigned NumGoodBases = 0; 1551 bool Invalid = false; 1552 for (unsigned idx = 0; idx < NumBases; ++idx) { 1553 QualType NewBaseType 1554 = Context.getCanonicalType(Bases[idx]->getType()); 1555 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1556 1557 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1558 if (KnownBase) { 1559 // C++ [class.mi]p3: 1560 // A class shall not be specified as a direct base class of a 1561 // derived class more than once. 1562 Diag(Bases[idx]->getLocStart(), 1563 diag::err_duplicate_base_class) 1564 << KnownBase->getType() 1565 << Bases[idx]->getSourceRange(); 1566 1567 // Delete the duplicate base class specifier; we're going to 1568 // overwrite its pointer later. 1569 Context.Deallocate(Bases[idx]); 1570 1571 Invalid = true; 1572 } else { 1573 // Okay, add this new base class. 1574 KnownBase = Bases[idx]; 1575 Bases[NumGoodBases++] = Bases[idx]; 1576 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1577 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1578 if (Class->isInterface() && 1579 (!RD->isInterface() || 1580 KnownBase->getAccessSpecifier() != AS_public)) { 1581 // The Microsoft extension __interface does not permit bases that 1582 // are not themselves public interfaces. 1583 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1584 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1585 << RD->getSourceRange(); 1586 Invalid = true; 1587 } 1588 if (RD->hasAttr<WeakAttr>()) 1589 Class->addAttr(WeakAttr::CreateImplicit(Context)); 1590 } 1591 } 1592 } 1593 1594 // Attach the remaining base class specifiers to the derived class. 1595 Class->setBases(Bases, NumGoodBases); 1596 1597 // Delete the remaining (good) base class specifiers, since their 1598 // data has been copied into the CXXRecordDecl. 1599 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1600 Context.Deallocate(Bases[idx]); 1601 1602 return Invalid; 1603 } 1604 1605 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1606 /// class, after checking whether there are any duplicate base 1607 /// classes. 1608 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1609 unsigned NumBases) { 1610 if (!ClassDecl || !Bases || !NumBases) 1611 return; 1612 1613 AdjustDeclIfTemplate(ClassDecl); 1614 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1615 } 1616 1617 /// \brief Determine whether the type \p Derived is a C++ class that is 1618 /// derived from the type \p Base. 1619 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1620 if (!getLangOpts().CPlusPlus) 1621 return false; 1622 1623 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1624 if (!DerivedRD) 1625 return false; 1626 1627 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1628 if (!BaseRD) 1629 return false; 1630 1631 // If either the base or the derived type is invalid, don't try to 1632 // check whether one is derived from the other. 1633 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1634 return false; 1635 1636 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1637 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1638 } 1639 1640 /// \brief Determine whether the type \p Derived is a C++ class that is 1641 /// derived from the type \p Base. 1642 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1643 if (!getLangOpts().CPlusPlus) 1644 return false; 1645 1646 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1647 if (!DerivedRD) 1648 return false; 1649 1650 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1651 if (!BaseRD) 1652 return false; 1653 1654 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1655 } 1656 1657 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1658 CXXCastPath &BasePathArray) { 1659 assert(BasePathArray.empty() && "Base path array must be empty!"); 1660 assert(Paths.isRecordingPaths() && "Must record paths!"); 1661 1662 const CXXBasePath &Path = Paths.front(); 1663 1664 // We first go backward and check if we have a virtual base. 1665 // FIXME: It would be better if CXXBasePath had the base specifier for 1666 // the nearest virtual base. 1667 unsigned Start = 0; 1668 for (unsigned I = Path.size(); I != 0; --I) { 1669 if (Path[I - 1].Base->isVirtual()) { 1670 Start = I - 1; 1671 break; 1672 } 1673 } 1674 1675 // Now add all bases. 1676 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1677 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1678 } 1679 1680 /// \brief Determine whether the given base path includes a virtual 1681 /// base class. 1682 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1683 for (CXXCastPath::const_iterator B = BasePath.begin(), 1684 BEnd = BasePath.end(); 1685 B != BEnd; ++B) 1686 if ((*B)->isVirtual()) 1687 return true; 1688 1689 return false; 1690 } 1691 1692 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1693 /// conversion (where Derived and Base are class types) is 1694 /// well-formed, meaning that the conversion is unambiguous (and 1695 /// that all of the base classes are accessible). Returns true 1696 /// and emits a diagnostic if the code is ill-formed, returns false 1697 /// otherwise. Loc is the location where this routine should point to 1698 /// if there is an error, and Range is the source range to highlight 1699 /// if there is an error. 1700 bool 1701 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1702 unsigned InaccessibleBaseID, 1703 unsigned AmbigiousBaseConvID, 1704 SourceLocation Loc, SourceRange Range, 1705 DeclarationName Name, 1706 CXXCastPath *BasePath) { 1707 // First, determine whether the path from Derived to Base is 1708 // ambiguous. This is slightly more expensive than checking whether 1709 // the Derived to Base conversion exists, because here we need to 1710 // explore multiple paths to determine if there is an ambiguity. 1711 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1712 /*DetectVirtual=*/false); 1713 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1714 assert(DerivationOkay && 1715 "Can only be used with a derived-to-base conversion"); 1716 (void)DerivationOkay; 1717 1718 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1719 if (InaccessibleBaseID) { 1720 // Check that the base class can be accessed. 1721 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1722 InaccessibleBaseID)) { 1723 case AR_inaccessible: 1724 return true; 1725 case AR_accessible: 1726 case AR_dependent: 1727 case AR_delayed: 1728 break; 1729 } 1730 } 1731 1732 // Build a base path if necessary. 1733 if (BasePath) 1734 BuildBasePathArray(Paths, *BasePath); 1735 return false; 1736 } 1737 1738 if (AmbigiousBaseConvID) { 1739 // We know that the derived-to-base conversion is ambiguous, and 1740 // we're going to produce a diagnostic. Perform the derived-to-base 1741 // search just one more time to compute all of the possible paths so 1742 // that we can print them out. This is more expensive than any of 1743 // the previous derived-to-base checks we've done, but at this point 1744 // performance isn't as much of an issue. 1745 Paths.clear(); 1746 Paths.setRecordingPaths(true); 1747 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1748 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1749 (void)StillOkay; 1750 1751 // Build up a textual representation of the ambiguous paths, e.g., 1752 // D -> B -> A, that will be used to illustrate the ambiguous 1753 // conversions in the diagnostic. We only print one of the paths 1754 // to each base class subobject. 1755 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1756 1757 Diag(Loc, AmbigiousBaseConvID) 1758 << Derived << Base << PathDisplayStr << Range << Name; 1759 } 1760 return true; 1761 } 1762 1763 bool 1764 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1765 SourceLocation Loc, SourceRange Range, 1766 CXXCastPath *BasePath, 1767 bool IgnoreAccess) { 1768 return CheckDerivedToBaseConversion(Derived, Base, 1769 IgnoreAccess ? 0 1770 : diag::err_upcast_to_inaccessible_base, 1771 diag::err_ambiguous_derived_to_base_conv, 1772 Loc, Range, DeclarationName(), 1773 BasePath); 1774 } 1775 1776 1777 /// @brief Builds a string representing ambiguous paths from a 1778 /// specific derived class to different subobjects of the same base 1779 /// class. 1780 /// 1781 /// This function builds a string that can be used in error messages 1782 /// to show the different paths that one can take through the 1783 /// inheritance hierarchy to go from the derived class to different 1784 /// subobjects of a base class. The result looks something like this: 1785 /// @code 1786 /// struct D -> struct B -> struct A 1787 /// struct D -> struct C -> struct A 1788 /// @endcode 1789 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1790 std::string PathDisplayStr; 1791 std::set<unsigned> DisplayedPaths; 1792 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1793 Path != Paths.end(); ++Path) { 1794 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1795 // We haven't displayed a path to this particular base 1796 // class subobject yet. 1797 PathDisplayStr += "\n "; 1798 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1799 for (CXXBasePath::const_iterator Element = Path->begin(); 1800 Element != Path->end(); ++Element) 1801 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1802 } 1803 } 1804 1805 return PathDisplayStr; 1806 } 1807 1808 //===----------------------------------------------------------------------===// 1809 // C++ class member Handling 1810 //===----------------------------------------------------------------------===// 1811 1812 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1813 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1814 SourceLocation ASLoc, 1815 SourceLocation ColonLoc, 1816 AttributeList *Attrs) { 1817 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1818 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1819 ASLoc, ColonLoc); 1820 CurContext->addHiddenDecl(ASDecl); 1821 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1822 } 1823 1824 /// CheckOverrideControl - Check C++11 override control semantics. 1825 void Sema::CheckOverrideControl(NamedDecl *D) { 1826 if (D->isInvalidDecl()) 1827 return; 1828 1829 // We only care about "override" and "final" declarations. 1830 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1831 return; 1832 1833 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1834 1835 // We can't check dependent instance methods. 1836 if (MD && MD->isInstance() && 1837 (MD->getParent()->hasAnyDependentBases() || 1838 MD->getType()->isDependentType())) 1839 return; 1840 1841 if (MD && !MD->isVirtual()) { 1842 // If we have a non-virtual method, check if if hides a virtual method. 1843 // (In that case, it's most likely the method has the wrong type.) 1844 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1845 FindHiddenVirtualMethods(MD, OverloadedMethods); 1846 1847 if (!OverloadedMethods.empty()) { 1848 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1849 Diag(OA->getLocation(), 1850 diag::override_keyword_hides_virtual_member_function) 1851 << "override" << (OverloadedMethods.size() > 1); 1852 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1853 Diag(FA->getLocation(), 1854 diag::override_keyword_hides_virtual_member_function) 1855 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1856 << (OverloadedMethods.size() > 1); 1857 } 1858 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1859 MD->setInvalidDecl(); 1860 return; 1861 } 1862 // Fall through into the general case diagnostic. 1863 // FIXME: We might want to attempt typo correction here. 1864 } 1865 1866 if (!MD || !MD->isVirtual()) { 1867 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1868 Diag(OA->getLocation(), 1869 diag::override_keyword_only_allowed_on_virtual_member_functions) 1870 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1871 D->dropAttr<OverrideAttr>(); 1872 } 1873 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1874 Diag(FA->getLocation(), 1875 diag::override_keyword_only_allowed_on_virtual_member_functions) 1876 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1877 << FixItHint::CreateRemoval(FA->getLocation()); 1878 D->dropAttr<FinalAttr>(); 1879 } 1880 return; 1881 } 1882 1883 // C++11 [class.virtual]p5: 1884 // If a virtual function is marked with the virt-specifier override and 1885 // does not override a member function of a base class, the program is 1886 // ill-formed. 1887 bool HasOverriddenMethods = 1888 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1889 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1890 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1891 << MD->getDeclName(); 1892 } 1893 1894 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1895 /// function overrides a virtual member function marked 'final', according to 1896 /// C++11 [class.virtual]p4. 1897 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1898 const CXXMethodDecl *Old) { 1899 FinalAttr *FA = Old->getAttr<FinalAttr>(); 1900 if (!FA) 1901 return false; 1902 1903 Diag(New->getLocation(), diag::err_final_function_overridden) 1904 << New->getDeclName() 1905 << FA->isSpelledAsSealed(); 1906 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1907 return true; 1908 } 1909 1910 static bool InitializationHasSideEffects(const FieldDecl &FD) { 1911 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1912 // FIXME: Destruction of ObjC lifetime types has side-effects. 1913 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1914 return !RD->isCompleteDefinition() || 1915 !RD->hasTrivialDefaultConstructor() || 1916 !RD->hasTrivialDestructor(); 1917 return false; 1918 } 1919 1920 static AttributeList *getMSPropertyAttr(AttributeList *list) { 1921 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 1922 if (it->isDeclspecPropertyAttribute()) 1923 return it; 1924 return nullptr; 1925 } 1926 1927 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1928 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1929 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 1930 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1931 /// present (but parsing it has been deferred). 1932 NamedDecl * 1933 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1934 MultiTemplateParamsArg TemplateParameterLists, 1935 Expr *BW, const VirtSpecifiers &VS, 1936 InClassInitStyle InitStyle) { 1937 const DeclSpec &DS = D.getDeclSpec(); 1938 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1939 DeclarationName Name = NameInfo.getName(); 1940 SourceLocation Loc = NameInfo.getLoc(); 1941 1942 // For anonymous bitfields, the location should point to the type. 1943 if (Loc.isInvalid()) 1944 Loc = D.getLocStart(); 1945 1946 Expr *BitWidth = static_cast<Expr*>(BW); 1947 1948 assert(isa<CXXRecordDecl>(CurContext)); 1949 assert(!DS.isFriendSpecified()); 1950 1951 bool isFunc = D.isDeclarationOfFunction(); 1952 1953 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1954 // The Microsoft extension __interface only permits public member functions 1955 // and prohibits constructors, destructors, operators, non-public member 1956 // functions, static methods and data members. 1957 unsigned InvalidDecl; 1958 bool ShowDeclName = true; 1959 if (!isFunc) 1960 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1961 else if (AS != AS_public) 1962 InvalidDecl = 2; 1963 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1964 InvalidDecl = 3; 1965 else switch (Name.getNameKind()) { 1966 case DeclarationName::CXXConstructorName: 1967 InvalidDecl = 4; 1968 ShowDeclName = false; 1969 break; 1970 1971 case DeclarationName::CXXDestructorName: 1972 InvalidDecl = 5; 1973 ShowDeclName = false; 1974 break; 1975 1976 case DeclarationName::CXXOperatorName: 1977 case DeclarationName::CXXConversionFunctionName: 1978 InvalidDecl = 6; 1979 break; 1980 1981 default: 1982 InvalidDecl = 0; 1983 break; 1984 } 1985 1986 if (InvalidDecl) { 1987 if (ShowDeclName) 1988 Diag(Loc, diag::err_invalid_member_in_interface) 1989 << (InvalidDecl-1) << Name; 1990 else 1991 Diag(Loc, diag::err_invalid_member_in_interface) 1992 << (InvalidDecl-1) << ""; 1993 return nullptr; 1994 } 1995 } 1996 1997 // C++ 9.2p6: A member shall not be declared to have automatic storage 1998 // duration (auto, register) or with the extern storage-class-specifier. 1999 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2000 // data members and cannot be applied to names declared const or static, 2001 // and cannot be applied to reference members. 2002 switch (DS.getStorageClassSpec()) { 2003 case DeclSpec::SCS_unspecified: 2004 case DeclSpec::SCS_typedef: 2005 case DeclSpec::SCS_static: 2006 break; 2007 case DeclSpec::SCS_mutable: 2008 if (isFunc) { 2009 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2010 2011 // FIXME: It would be nicer if the keyword was ignored only for this 2012 // declarator. Otherwise we could get follow-up errors. 2013 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2014 } 2015 break; 2016 default: 2017 Diag(DS.getStorageClassSpecLoc(), 2018 diag::err_storageclass_invalid_for_member); 2019 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2020 break; 2021 } 2022 2023 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2024 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2025 !isFunc); 2026 2027 if (DS.isConstexprSpecified() && isInstField) { 2028 SemaDiagnosticBuilder B = 2029 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2030 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2031 if (InitStyle == ICIS_NoInit) { 2032 B << 0 << 0; 2033 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2034 B << FixItHint::CreateRemoval(ConstexprLoc); 2035 else { 2036 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2037 D.getMutableDeclSpec().ClearConstexprSpec(); 2038 const char *PrevSpec; 2039 unsigned DiagID; 2040 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2041 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2042 (void)Failed; 2043 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2044 } 2045 } else { 2046 B << 1; 2047 const char *PrevSpec; 2048 unsigned DiagID; 2049 if (D.getMutableDeclSpec().SetStorageClassSpec( 2050 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2051 Context.getPrintingPolicy())) { 2052 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2053 "This is the only DeclSpec that should fail to be applied"); 2054 B << 1; 2055 } else { 2056 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2057 isInstField = false; 2058 } 2059 } 2060 } 2061 2062 NamedDecl *Member; 2063 if (isInstField) { 2064 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2065 2066 // Data members must have identifiers for names. 2067 if (!Name.isIdentifier()) { 2068 Diag(Loc, diag::err_bad_variable_name) 2069 << Name; 2070 return nullptr; 2071 } 2072 2073 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2074 2075 // Member field could not be with "template" keyword. 2076 // So TemplateParameterLists should be empty in this case. 2077 if (TemplateParameterLists.size()) { 2078 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2079 if (TemplateParams->size()) { 2080 // There is no such thing as a member field template. 2081 Diag(D.getIdentifierLoc(), diag::err_template_member) 2082 << II 2083 << SourceRange(TemplateParams->getTemplateLoc(), 2084 TemplateParams->getRAngleLoc()); 2085 } else { 2086 // There is an extraneous 'template<>' for this member. 2087 Diag(TemplateParams->getTemplateLoc(), 2088 diag::err_template_member_noparams) 2089 << II 2090 << SourceRange(TemplateParams->getTemplateLoc(), 2091 TemplateParams->getRAngleLoc()); 2092 } 2093 return nullptr; 2094 } 2095 2096 if (SS.isSet() && !SS.isInvalid()) { 2097 // The user provided a superfluous scope specifier inside a class 2098 // definition: 2099 // 2100 // class X { 2101 // int X::member; 2102 // }; 2103 if (DeclContext *DC = computeDeclContext(SS, false)) 2104 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2105 else 2106 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2107 << Name << SS.getRange(); 2108 2109 SS.clear(); 2110 } 2111 2112 AttributeList *MSPropertyAttr = 2113 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2114 if (MSPropertyAttr) { 2115 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2116 BitWidth, InitStyle, AS, MSPropertyAttr); 2117 if (!Member) 2118 return nullptr; 2119 isInstField = false; 2120 } else { 2121 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2122 BitWidth, InitStyle, AS); 2123 assert(Member && "HandleField never returns null"); 2124 } 2125 } else { 2126 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 2127 2128 Member = HandleDeclarator(S, D, TemplateParameterLists); 2129 if (!Member) 2130 return nullptr; 2131 2132 // Non-instance-fields can't have a bitfield. 2133 if (BitWidth) { 2134 if (Member->isInvalidDecl()) { 2135 // don't emit another diagnostic. 2136 } else if (isa<VarDecl>(Member)) { 2137 // C++ 9.6p3: A bit-field shall not be a static member. 2138 // "static member 'A' cannot be a bit-field" 2139 Diag(Loc, diag::err_static_not_bitfield) 2140 << Name << BitWidth->getSourceRange(); 2141 } else if (isa<TypedefDecl>(Member)) { 2142 // "typedef member 'x' cannot be a bit-field" 2143 Diag(Loc, diag::err_typedef_not_bitfield) 2144 << Name << BitWidth->getSourceRange(); 2145 } else { 2146 // A function typedef ("typedef int f(); f a;"). 2147 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2148 Diag(Loc, diag::err_not_integral_type_bitfield) 2149 << Name << cast<ValueDecl>(Member)->getType() 2150 << BitWidth->getSourceRange(); 2151 } 2152 2153 BitWidth = nullptr; 2154 Member->setInvalidDecl(); 2155 } 2156 2157 Member->setAccess(AS); 2158 2159 // If we have declared a member function template or static data member 2160 // template, set the access of the templated declaration as well. 2161 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2162 FunTmpl->getTemplatedDecl()->setAccess(AS); 2163 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2164 VarTmpl->getTemplatedDecl()->setAccess(AS); 2165 } 2166 2167 if (VS.isOverrideSpecified()) 2168 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 2169 if (VS.isFinalSpecified()) 2170 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2171 VS.isFinalSpelledSealed())); 2172 2173 if (VS.getLastLocation().isValid()) { 2174 // Update the end location of a method that has a virt-specifiers. 2175 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2176 MD->setRangeEnd(VS.getLastLocation()); 2177 } 2178 2179 CheckOverrideControl(Member); 2180 2181 assert((Name || isInstField) && "No identifier for non-field ?"); 2182 2183 if (isInstField) { 2184 FieldDecl *FD = cast<FieldDecl>(Member); 2185 FieldCollector->Add(FD); 2186 2187 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 2188 // Remember all explicit private FieldDecls that have a name, no side 2189 // effects and are not part of a dependent type declaration. 2190 if (!FD->isImplicit() && FD->getDeclName() && 2191 FD->getAccess() == AS_private && 2192 !FD->hasAttr<UnusedAttr>() && 2193 !FD->getParent()->isDependentContext() && 2194 !InitializationHasSideEffects(*FD)) 2195 UnusedPrivateFields.insert(FD); 2196 } 2197 } 2198 2199 return Member; 2200 } 2201 2202 namespace { 2203 class UninitializedFieldVisitor 2204 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2205 Sema &S; 2206 // List of Decls to generate a warning on. Also remove Decls that become 2207 // initialized. 2208 llvm::SmallPtrSet<ValueDecl*, 4> &Decls; 2209 // If non-null, add a note to the warning pointing back to the constructor. 2210 const CXXConstructorDecl *Constructor; 2211 public: 2212 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2213 UninitializedFieldVisitor(Sema &S, 2214 llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2215 const CXXConstructorDecl *Constructor) 2216 : Inherited(S.Context), S(S), Decls(Decls), 2217 Constructor(Constructor) { } 2218 2219 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) { 2220 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2221 return; 2222 2223 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2224 // or union. 2225 MemberExpr *FieldME = ME; 2226 2227 Expr *Base = ME; 2228 while (isa<MemberExpr>(Base)) { 2229 ME = cast<MemberExpr>(Base); 2230 2231 if (isa<VarDecl>(ME->getMemberDecl())) 2232 return; 2233 2234 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2235 if (!FD->isAnonymousStructOrUnion()) 2236 FieldME = ME; 2237 2238 Base = ME->getBase(); 2239 } 2240 2241 if (!isa<CXXThisExpr>(Base)) 2242 return; 2243 2244 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2245 2246 if (!Decls.count(FoundVD)) 2247 return; 2248 2249 const bool IsReference = FoundVD->getType()->isReferenceType(); 2250 2251 // Prevent double warnings on use of unbounded references. 2252 if (IsReference != CheckReferenceOnly) 2253 return; 2254 2255 unsigned diag = IsReference 2256 ? diag::warn_reference_field_is_uninit 2257 : diag::warn_field_is_uninit; 2258 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 2259 if (Constructor) 2260 S.Diag(Constructor->getLocation(), 2261 diag::note_uninit_in_this_constructor) 2262 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 2263 2264 } 2265 2266 void HandleValue(Expr *E) { 2267 E = E->IgnoreParens(); 2268 2269 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2270 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2271 return; 2272 } 2273 2274 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2275 HandleValue(CO->getTrueExpr()); 2276 HandleValue(CO->getFalseExpr()); 2277 return; 2278 } 2279 2280 if (BinaryConditionalOperator *BCO = 2281 dyn_cast<BinaryConditionalOperator>(E)) { 2282 HandleValue(BCO->getCommon()); 2283 HandleValue(BCO->getFalseExpr()); 2284 return; 2285 } 2286 2287 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2288 switch (BO->getOpcode()) { 2289 default: 2290 return; 2291 case(BO_PtrMemD): 2292 case(BO_PtrMemI): 2293 HandleValue(BO->getLHS()); 2294 return; 2295 case(BO_Comma): 2296 HandleValue(BO->getRHS()); 2297 return; 2298 } 2299 } 2300 } 2301 2302 void VisitMemberExpr(MemberExpr *ME) { 2303 // All uses of unbounded reference fields will warn. 2304 HandleMemberExpr(ME, true /*CheckReferenceOnly*/); 2305 2306 Inherited::VisitMemberExpr(ME); 2307 } 2308 2309 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2310 if (E->getCastKind() == CK_LValueToRValue) 2311 HandleValue(E->getSubExpr()); 2312 2313 Inherited::VisitImplicitCastExpr(E); 2314 } 2315 2316 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2317 if (E->getConstructor()->isCopyConstructor()) { 2318 Expr *ArgExpr = E->getArg(0); 2319 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) { 2320 if (ICE->getCastKind() == CK_NoOp) { 2321 ArgExpr = ICE->getSubExpr(); 2322 } 2323 } 2324 2325 if (MemberExpr *ME = dyn_cast<MemberExpr>(ArgExpr)) { 2326 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2327 } 2328 } 2329 Inherited::VisitCXXConstructExpr(E); 2330 } 2331 2332 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2333 Expr *Callee = E->getCallee(); 2334 if (isa<MemberExpr>(Callee)) 2335 HandleValue(Callee); 2336 2337 Inherited::VisitCXXMemberCallExpr(E); 2338 } 2339 2340 void VisitBinaryOperator(BinaryOperator *E) { 2341 // If a field assignment is detected, remove the field from the 2342 // uninitiailized field set. 2343 if (E->getOpcode() == BO_Assign) 2344 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2345 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2346 if (!FD->getType()->isReferenceType()) 2347 Decls.erase(FD); 2348 2349 Inherited::VisitBinaryOperator(E); 2350 } 2351 }; 2352 static void CheckInitExprContainsUninitializedFields( 2353 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2354 const CXXConstructorDecl *Constructor) { 2355 if (Decls.size() == 0) 2356 return; 2357 2358 if (!E) 2359 return; 2360 2361 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) { 2362 E = Default->getExpr(); 2363 if (!E) 2364 return; 2365 // In class initializers will point to the constructor. 2366 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E); 2367 } else { 2368 UninitializedFieldVisitor(S, Decls, nullptr).Visit(E); 2369 } 2370 } 2371 2372 // Diagnose value-uses of fields to initialize themselves, e.g. 2373 // foo(foo) 2374 // where foo is not also a parameter to the constructor. 2375 // Also diagnose across field uninitialized use such as 2376 // x(y), y(x) 2377 // TODO: implement -Wuninitialized and fold this into that framework. 2378 static void DiagnoseUninitializedFields( 2379 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 2380 2381 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 2382 Constructor->getLocation())) { 2383 return; 2384 } 2385 2386 if (Constructor->isInvalidDecl()) 2387 return; 2388 2389 const CXXRecordDecl *RD = Constructor->getParent(); 2390 2391 // Holds fields that are uninitialized. 2392 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 2393 2394 // At the beginning, all fields are uninitialized. 2395 for (auto *I : RD->decls()) { 2396 if (auto *FD = dyn_cast<FieldDecl>(I)) { 2397 UninitializedFields.insert(FD); 2398 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 2399 UninitializedFields.insert(IFD->getAnonField()); 2400 } 2401 } 2402 2403 for (const auto *FieldInit : Constructor->inits()) { 2404 Expr *InitExpr = FieldInit->getInit(); 2405 2406 CheckInitExprContainsUninitializedFields( 2407 SemaRef, InitExpr, UninitializedFields, Constructor); 2408 2409 if (FieldDecl *Field = FieldInit->getAnyMember()) 2410 UninitializedFields.erase(Field); 2411 } 2412 } 2413 } // namespace 2414 2415 /// \brief Enter a new C++ default initializer scope. After calling this, the 2416 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 2417 /// parsing or instantiating the initializer failed. 2418 void Sema::ActOnStartCXXInClassMemberInitializer() { 2419 // Create a synthetic function scope to represent the call to the constructor 2420 // that notionally surrounds a use of this initializer. 2421 PushFunctionScope(); 2422 } 2423 2424 /// \brief This is invoked after parsing an in-class initializer for a 2425 /// non-static C++ class member, and after instantiating an in-class initializer 2426 /// in a class template. Such actions are deferred until the class is complete. 2427 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 2428 SourceLocation InitLoc, 2429 Expr *InitExpr) { 2430 // Pop the notional constructor scope we created earlier. 2431 PopFunctionScopeInfo(nullptr, D); 2432 2433 FieldDecl *FD = cast<FieldDecl>(D); 2434 assert(FD->getInClassInitStyle() != ICIS_NoInit && 2435 "must set init style when field is created"); 2436 2437 if (!InitExpr) { 2438 FD->setInvalidDecl(); 2439 FD->removeInClassInitializer(); 2440 return; 2441 } 2442 2443 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2444 FD->setInvalidDecl(); 2445 FD->removeInClassInitializer(); 2446 return; 2447 } 2448 2449 ExprResult Init = InitExpr; 2450 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2451 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2452 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2453 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2454 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2455 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2456 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2457 if (Init.isInvalid()) { 2458 FD->setInvalidDecl(); 2459 return; 2460 } 2461 } 2462 2463 // C++11 [class.base.init]p7: 2464 // The initialization of each base and member constitutes a 2465 // full-expression. 2466 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 2467 if (Init.isInvalid()) { 2468 FD->setInvalidDecl(); 2469 return; 2470 } 2471 2472 InitExpr = Init.get(); 2473 2474 FD->setInClassInitializer(InitExpr); 2475 } 2476 2477 /// \brief Find the direct and/or virtual base specifiers that 2478 /// correspond to the given base type, for use in base initialization 2479 /// within a constructor. 2480 static bool FindBaseInitializer(Sema &SemaRef, 2481 CXXRecordDecl *ClassDecl, 2482 QualType BaseType, 2483 const CXXBaseSpecifier *&DirectBaseSpec, 2484 const CXXBaseSpecifier *&VirtualBaseSpec) { 2485 // First, check for a direct base class. 2486 DirectBaseSpec = nullptr; 2487 for (const auto &Base : ClassDecl->bases()) { 2488 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 2489 // We found a direct base of this type. That's what we're 2490 // initializing. 2491 DirectBaseSpec = &Base; 2492 break; 2493 } 2494 } 2495 2496 // Check for a virtual base class. 2497 // FIXME: We might be able to short-circuit this if we know in advance that 2498 // there are no virtual bases. 2499 VirtualBaseSpec = nullptr; 2500 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2501 // We haven't found a base yet; search the class hierarchy for a 2502 // virtual base class. 2503 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2504 /*DetectVirtual=*/false); 2505 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2506 BaseType, Paths)) { 2507 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2508 Path != Paths.end(); ++Path) { 2509 if (Path->back().Base->isVirtual()) { 2510 VirtualBaseSpec = Path->back().Base; 2511 break; 2512 } 2513 } 2514 } 2515 } 2516 2517 return DirectBaseSpec || VirtualBaseSpec; 2518 } 2519 2520 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2521 MemInitResult 2522 Sema::ActOnMemInitializer(Decl *ConstructorD, 2523 Scope *S, 2524 CXXScopeSpec &SS, 2525 IdentifierInfo *MemberOrBase, 2526 ParsedType TemplateTypeTy, 2527 const DeclSpec &DS, 2528 SourceLocation IdLoc, 2529 Expr *InitList, 2530 SourceLocation EllipsisLoc) { 2531 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2532 DS, IdLoc, InitList, 2533 EllipsisLoc); 2534 } 2535 2536 /// \brief Handle a C++ member initializer using parentheses syntax. 2537 MemInitResult 2538 Sema::ActOnMemInitializer(Decl *ConstructorD, 2539 Scope *S, 2540 CXXScopeSpec &SS, 2541 IdentifierInfo *MemberOrBase, 2542 ParsedType TemplateTypeTy, 2543 const DeclSpec &DS, 2544 SourceLocation IdLoc, 2545 SourceLocation LParenLoc, 2546 ArrayRef<Expr *> Args, 2547 SourceLocation RParenLoc, 2548 SourceLocation EllipsisLoc) { 2549 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2550 Args, RParenLoc); 2551 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2552 DS, IdLoc, List, EllipsisLoc); 2553 } 2554 2555 namespace { 2556 2557 // Callback to only accept typo corrections that can be a valid C++ member 2558 // intializer: either a non-static field member or a base class. 2559 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2560 public: 2561 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2562 : ClassDecl(ClassDecl) {} 2563 2564 bool ValidateCandidate(const TypoCorrection &candidate) override { 2565 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2566 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2567 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2568 return isa<TypeDecl>(ND); 2569 } 2570 return false; 2571 } 2572 2573 private: 2574 CXXRecordDecl *ClassDecl; 2575 }; 2576 2577 } 2578 2579 /// \brief Handle a C++ member initializer. 2580 MemInitResult 2581 Sema::BuildMemInitializer(Decl *ConstructorD, 2582 Scope *S, 2583 CXXScopeSpec &SS, 2584 IdentifierInfo *MemberOrBase, 2585 ParsedType TemplateTypeTy, 2586 const DeclSpec &DS, 2587 SourceLocation IdLoc, 2588 Expr *Init, 2589 SourceLocation EllipsisLoc) { 2590 if (!ConstructorD) 2591 return true; 2592 2593 AdjustDeclIfTemplate(ConstructorD); 2594 2595 CXXConstructorDecl *Constructor 2596 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2597 if (!Constructor) { 2598 // The user wrote a constructor initializer on a function that is 2599 // not a C++ constructor. Ignore the error for now, because we may 2600 // have more member initializers coming; we'll diagnose it just 2601 // once in ActOnMemInitializers. 2602 return true; 2603 } 2604 2605 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2606 2607 // C++ [class.base.init]p2: 2608 // Names in a mem-initializer-id are looked up in the scope of the 2609 // constructor's class and, if not found in that scope, are looked 2610 // up in the scope containing the constructor's definition. 2611 // [Note: if the constructor's class contains a member with the 2612 // same name as a direct or virtual base class of the class, a 2613 // mem-initializer-id naming the member or base class and composed 2614 // of a single identifier refers to the class member. A 2615 // mem-initializer-id for the hidden base class may be specified 2616 // using a qualified name. ] 2617 if (!SS.getScopeRep() && !TemplateTypeTy) { 2618 // Look for a member, first. 2619 DeclContext::lookup_result Result 2620 = ClassDecl->lookup(MemberOrBase); 2621 if (!Result.empty()) { 2622 ValueDecl *Member; 2623 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2624 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2625 if (EllipsisLoc.isValid()) 2626 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2627 << MemberOrBase 2628 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2629 2630 return BuildMemberInitializer(Member, Init, IdLoc); 2631 } 2632 } 2633 } 2634 // It didn't name a member, so see if it names a class. 2635 QualType BaseType; 2636 TypeSourceInfo *TInfo = nullptr; 2637 2638 if (TemplateTypeTy) { 2639 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2640 } else if (DS.getTypeSpecType() == TST_decltype) { 2641 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2642 } else { 2643 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2644 LookupParsedName(R, S, &SS); 2645 2646 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2647 if (!TyD) { 2648 if (R.isAmbiguous()) return true; 2649 2650 // We don't want access-control diagnostics here. 2651 R.suppressDiagnostics(); 2652 2653 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2654 bool NotUnknownSpecialization = false; 2655 DeclContext *DC = computeDeclContext(SS, false); 2656 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2657 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2658 2659 if (!NotUnknownSpecialization) { 2660 // When the scope specifier can refer to a member of an unknown 2661 // specialization, we take it as a type name. 2662 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2663 SS.getWithLocInContext(Context), 2664 *MemberOrBase, IdLoc); 2665 if (BaseType.isNull()) 2666 return true; 2667 2668 R.clear(); 2669 R.setLookupName(MemberOrBase); 2670 } 2671 } 2672 2673 // If no results were found, try to correct typos. 2674 TypoCorrection Corr; 2675 MemInitializerValidatorCCC Validator(ClassDecl); 2676 if (R.empty() && BaseType.isNull() && 2677 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2678 Validator, CTK_ErrorRecovery, ClassDecl))) { 2679 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2680 // We have found a non-static data member with a similar 2681 // name to what was typed; complain and initialize that 2682 // member. 2683 diagnoseTypo(Corr, 2684 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2685 << MemberOrBase << true); 2686 return BuildMemberInitializer(Member, Init, IdLoc); 2687 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2688 const CXXBaseSpecifier *DirectBaseSpec; 2689 const CXXBaseSpecifier *VirtualBaseSpec; 2690 if (FindBaseInitializer(*this, ClassDecl, 2691 Context.getTypeDeclType(Type), 2692 DirectBaseSpec, VirtualBaseSpec)) { 2693 // We have found a direct or virtual base class with a 2694 // similar name to what was typed; complain and initialize 2695 // that base class. 2696 diagnoseTypo(Corr, 2697 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2698 << MemberOrBase << false, 2699 PDiag() /*Suppress note, we provide our own.*/); 2700 2701 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2702 : VirtualBaseSpec; 2703 Diag(BaseSpec->getLocStart(), 2704 diag::note_base_class_specified_here) 2705 << BaseSpec->getType() 2706 << BaseSpec->getSourceRange(); 2707 2708 TyD = Type; 2709 } 2710 } 2711 } 2712 2713 if (!TyD && BaseType.isNull()) { 2714 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2715 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2716 return true; 2717 } 2718 } 2719 2720 if (BaseType.isNull()) { 2721 BaseType = Context.getTypeDeclType(TyD); 2722 if (SS.isSet()) 2723 // FIXME: preserve source range information 2724 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 2725 BaseType); 2726 } 2727 } 2728 2729 if (!TInfo) 2730 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2731 2732 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2733 } 2734 2735 /// Checks a member initializer expression for cases where reference (or 2736 /// pointer) members are bound to by-value parameters (or their addresses). 2737 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2738 Expr *Init, 2739 SourceLocation IdLoc) { 2740 QualType MemberTy = Member->getType(); 2741 2742 // We only handle pointers and references currently. 2743 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2744 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2745 return; 2746 2747 const bool IsPointer = MemberTy->isPointerType(); 2748 if (IsPointer) { 2749 if (const UnaryOperator *Op 2750 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2751 // The only case we're worried about with pointers requires taking the 2752 // address. 2753 if (Op->getOpcode() != UO_AddrOf) 2754 return; 2755 2756 Init = Op->getSubExpr(); 2757 } else { 2758 // We only handle address-of expression initializers for pointers. 2759 return; 2760 } 2761 } 2762 2763 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2764 // We only warn when referring to a non-reference parameter declaration. 2765 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2766 if (!Parameter || Parameter->getType()->isReferenceType()) 2767 return; 2768 2769 S.Diag(Init->getExprLoc(), 2770 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2771 : diag::warn_bind_ref_member_to_parameter) 2772 << Member << Parameter << Init->getSourceRange(); 2773 } else { 2774 // Other initializers are fine. 2775 return; 2776 } 2777 2778 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2779 << (unsigned)IsPointer; 2780 } 2781 2782 MemInitResult 2783 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2784 SourceLocation IdLoc) { 2785 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2786 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2787 assert((DirectMember || IndirectMember) && 2788 "Member must be a FieldDecl or IndirectFieldDecl"); 2789 2790 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2791 return true; 2792 2793 if (Member->isInvalidDecl()) 2794 return true; 2795 2796 MultiExprArg Args; 2797 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2798 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2799 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2800 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 2801 } else { 2802 // Template instantiation doesn't reconstruct ParenListExprs for us. 2803 Args = Init; 2804 } 2805 2806 SourceRange InitRange = Init->getSourceRange(); 2807 2808 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2809 // Can't check initialization for a member of dependent type or when 2810 // any of the arguments are type-dependent expressions. 2811 DiscardCleanupsInEvaluationContext(); 2812 } else { 2813 bool InitList = false; 2814 if (isa<InitListExpr>(Init)) { 2815 InitList = true; 2816 Args = Init; 2817 } 2818 2819 // Initialize the member. 2820 InitializedEntity MemberEntity = 2821 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 2822 : InitializedEntity::InitializeMember(IndirectMember, 2823 nullptr); 2824 InitializationKind Kind = 2825 InitList ? InitializationKind::CreateDirectList(IdLoc) 2826 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2827 InitRange.getEnd()); 2828 2829 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 2830 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 2831 nullptr); 2832 if (MemberInit.isInvalid()) 2833 return true; 2834 2835 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 2836 2837 // C++11 [class.base.init]p7: 2838 // The initialization of each base and member constitutes a 2839 // full-expression. 2840 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 2841 if (MemberInit.isInvalid()) 2842 return true; 2843 2844 Init = MemberInit.get(); 2845 } 2846 2847 if (DirectMember) { 2848 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2849 InitRange.getBegin(), Init, 2850 InitRange.getEnd()); 2851 } else { 2852 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2853 InitRange.getBegin(), Init, 2854 InitRange.getEnd()); 2855 } 2856 } 2857 2858 MemInitResult 2859 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2860 CXXRecordDecl *ClassDecl) { 2861 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2862 if (!LangOpts.CPlusPlus11) 2863 return Diag(NameLoc, diag::err_delegating_ctor) 2864 << TInfo->getTypeLoc().getLocalSourceRange(); 2865 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2866 2867 bool InitList = true; 2868 MultiExprArg Args = Init; 2869 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2870 InitList = false; 2871 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2872 } 2873 2874 SourceRange InitRange = Init->getSourceRange(); 2875 // Initialize the object. 2876 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2877 QualType(ClassDecl->getTypeForDecl(), 0)); 2878 InitializationKind Kind = 2879 InitList ? InitializationKind::CreateDirectList(NameLoc) 2880 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2881 InitRange.getEnd()); 2882 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 2883 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2884 Args, nullptr); 2885 if (DelegationInit.isInvalid()) 2886 return true; 2887 2888 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2889 "Delegating constructor with no target?"); 2890 2891 // C++11 [class.base.init]p7: 2892 // The initialization of each base and member constitutes a 2893 // full-expression. 2894 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 2895 InitRange.getBegin()); 2896 if (DelegationInit.isInvalid()) 2897 return true; 2898 2899 // If we are in a dependent context, template instantiation will 2900 // perform this type-checking again. Just save the arguments that we 2901 // received in a ParenListExpr. 2902 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2903 // of the information that we have about the base 2904 // initializer. However, deconstructing the ASTs is a dicey process, 2905 // and this approach is far more likely to get the corner cases right. 2906 if (CurContext->isDependentContext()) 2907 DelegationInit = Init; 2908 2909 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2910 DelegationInit.getAs<Expr>(), 2911 InitRange.getEnd()); 2912 } 2913 2914 MemInitResult 2915 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2916 Expr *Init, CXXRecordDecl *ClassDecl, 2917 SourceLocation EllipsisLoc) { 2918 SourceLocation BaseLoc 2919 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2920 2921 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2922 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2923 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2924 2925 // C++ [class.base.init]p2: 2926 // [...] Unless the mem-initializer-id names a nonstatic data 2927 // member of the constructor's class or a direct or virtual base 2928 // of that class, the mem-initializer is ill-formed. A 2929 // mem-initializer-list can initialize a base class using any 2930 // name that denotes that base class type. 2931 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2932 2933 SourceRange InitRange = Init->getSourceRange(); 2934 if (EllipsisLoc.isValid()) { 2935 // This is a pack expansion. 2936 if (!BaseType->containsUnexpandedParameterPack()) { 2937 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2938 << SourceRange(BaseLoc, InitRange.getEnd()); 2939 2940 EllipsisLoc = SourceLocation(); 2941 } 2942 } else { 2943 // Check for any unexpanded parameter packs. 2944 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2945 return true; 2946 2947 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2948 return true; 2949 } 2950 2951 // Check for direct and virtual base classes. 2952 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 2953 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 2954 if (!Dependent) { 2955 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2956 BaseType)) 2957 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2958 2959 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2960 VirtualBaseSpec); 2961 2962 // C++ [base.class.init]p2: 2963 // Unless the mem-initializer-id names a nonstatic data member of the 2964 // constructor's class or a direct or virtual base of that class, the 2965 // mem-initializer is ill-formed. 2966 if (!DirectBaseSpec && !VirtualBaseSpec) { 2967 // If the class has any dependent bases, then it's possible that 2968 // one of those types will resolve to the same type as 2969 // BaseType. Therefore, just treat this as a dependent base 2970 // class initialization. FIXME: Should we try to check the 2971 // initialization anyway? It seems odd. 2972 if (ClassDecl->hasAnyDependentBases()) 2973 Dependent = true; 2974 else 2975 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2976 << BaseType << Context.getTypeDeclType(ClassDecl) 2977 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2978 } 2979 } 2980 2981 if (Dependent) { 2982 DiscardCleanupsInEvaluationContext(); 2983 2984 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2985 /*IsVirtual=*/false, 2986 InitRange.getBegin(), Init, 2987 InitRange.getEnd(), EllipsisLoc); 2988 } 2989 2990 // C++ [base.class.init]p2: 2991 // If a mem-initializer-id is ambiguous because it designates both 2992 // a direct non-virtual base class and an inherited virtual base 2993 // class, the mem-initializer is ill-formed. 2994 if (DirectBaseSpec && VirtualBaseSpec) 2995 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2996 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2997 2998 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 2999 if (!BaseSpec) 3000 BaseSpec = VirtualBaseSpec; 3001 3002 // Initialize the base. 3003 bool InitList = true; 3004 MultiExprArg Args = Init; 3005 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3006 InitList = false; 3007 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3008 } 3009 3010 InitializedEntity BaseEntity = 3011 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 3012 InitializationKind Kind = 3013 InitList ? InitializationKind::CreateDirectList(BaseLoc) 3014 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 3015 InitRange.getEnd()); 3016 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 3017 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 3018 if (BaseInit.isInvalid()) 3019 return true; 3020 3021 // C++11 [class.base.init]p7: 3022 // The initialization of each base and member constitutes a 3023 // full-expression. 3024 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 3025 if (BaseInit.isInvalid()) 3026 return true; 3027 3028 // If we are in a dependent context, template instantiation will 3029 // perform this type-checking again. Just save the arguments that we 3030 // received in a ParenListExpr. 3031 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3032 // of the information that we have about the base 3033 // initializer. However, deconstructing the ASTs is a dicey process, 3034 // and this approach is far more likely to get the corner cases right. 3035 if (CurContext->isDependentContext()) 3036 BaseInit = Init; 3037 3038 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3039 BaseSpec->isVirtual(), 3040 InitRange.getBegin(), 3041 BaseInit.getAs<Expr>(), 3042 InitRange.getEnd(), EllipsisLoc); 3043 } 3044 3045 // Create a static_cast\<T&&>(expr). 3046 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 3047 if (T.isNull()) T = E->getType(); 3048 QualType TargetType = SemaRef.BuildReferenceType( 3049 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 3050 SourceLocation ExprLoc = E->getLocStart(); 3051 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 3052 TargetType, ExprLoc); 3053 3054 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 3055 SourceRange(ExprLoc, ExprLoc), 3056 E->getSourceRange()).get(); 3057 } 3058 3059 /// ImplicitInitializerKind - How an implicit base or member initializer should 3060 /// initialize its base or member. 3061 enum ImplicitInitializerKind { 3062 IIK_Default, 3063 IIK_Copy, 3064 IIK_Move, 3065 IIK_Inherit 3066 }; 3067 3068 static bool 3069 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3070 ImplicitInitializerKind ImplicitInitKind, 3071 CXXBaseSpecifier *BaseSpec, 3072 bool IsInheritedVirtualBase, 3073 CXXCtorInitializer *&CXXBaseInit) { 3074 InitializedEntity InitEntity 3075 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 3076 IsInheritedVirtualBase); 3077 3078 ExprResult BaseInit; 3079 3080 switch (ImplicitInitKind) { 3081 case IIK_Inherit: { 3082 const CXXRecordDecl *Inherited = 3083 Constructor->getInheritedConstructor()->getParent(); 3084 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 3085 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 3086 // C++11 [class.inhctor]p8: 3087 // Each expression in the expression-list is of the form 3088 // static_cast<T&&>(p), where p is the name of the corresponding 3089 // constructor parameter and T is the declared type of p. 3090 SmallVector<Expr*, 16> Args; 3091 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 3092 ParmVarDecl *PD = Constructor->getParamDecl(I); 3093 ExprResult ArgExpr = 3094 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 3095 VK_LValue, SourceLocation()); 3096 if (ArgExpr.isInvalid()) 3097 return true; 3098 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType())); 3099 } 3100 3101 InitializationKind InitKind = InitializationKind::CreateDirect( 3102 Constructor->getLocation(), SourceLocation(), SourceLocation()); 3103 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 3104 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 3105 break; 3106 } 3107 } 3108 // Fall through. 3109 case IIK_Default: { 3110 InitializationKind InitKind 3111 = InitializationKind::CreateDefault(Constructor->getLocation()); 3112 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3113 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3114 break; 3115 } 3116 3117 case IIK_Move: 3118 case IIK_Copy: { 3119 bool Moving = ImplicitInitKind == IIK_Move; 3120 ParmVarDecl *Param = Constructor->getParamDecl(0); 3121 QualType ParamType = Param->getType().getNonReferenceType(); 3122 3123 Expr *CopyCtorArg = 3124 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3125 SourceLocation(), Param, false, 3126 Constructor->getLocation(), ParamType, 3127 VK_LValue, nullptr); 3128 3129 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 3130 3131 // Cast to the base class to avoid ambiguities. 3132 QualType ArgTy = 3133 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3134 ParamType.getQualifiers()); 3135 3136 if (Moving) { 3137 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3138 } 3139 3140 CXXCastPath BasePath; 3141 BasePath.push_back(BaseSpec); 3142 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3143 CK_UncheckedDerivedToBase, 3144 Moving ? VK_XValue : VK_LValue, 3145 &BasePath).get(); 3146 3147 InitializationKind InitKind 3148 = InitializationKind::CreateDirect(Constructor->getLocation(), 3149 SourceLocation(), SourceLocation()); 3150 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3151 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3152 break; 3153 } 3154 } 3155 3156 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3157 if (BaseInit.isInvalid()) 3158 return true; 3159 3160 CXXBaseInit = 3161 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3162 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3163 SourceLocation()), 3164 BaseSpec->isVirtual(), 3165 SourceLocation(), 3166 BaseInit.getAs<Expr>(), 3167 SourceLocation(), 3168 SourceLocation()); 3169 3170 return false; 3171 } 3172 3173 static bool RefersToRValueRef(Expr *MemRef) { 3174 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3175 return Referenced->getType()->isRValueReferenceType(); 3176 } 3177 3178 static bool 3179 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3180 ImplicitInitializerKind ImplicitInitKind, 3181 FieldDecl *Field, IndirectFieldDecl *Indirect, 3182 CXXCtorInitializer *&CXXMemberInit) { 3183 if (Field->isInvalidDecl()) 3184 return true; 3185 3186 SourceLocation Loc = Constructor->getLocation(); 3187 3188 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3189 bool Moving = ImplicitInitKind == IIK_Move; 3190 ParmVarDecl *Param = Constructor->getParamDecl(0); 3191 QualType ParamType = Param->getType().getNonReferenceType(); 3192 3193 // Suppress copying zero-width bitfields. 3194 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3195 return false; 3196 3197 Expr *MemberExprBase = 3198 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3199 SourceLocation(), Param, false, 3200 Loc, ParamType, VK_LValue, nullptr); 3201 3202 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3203 3204 if (Moving) { 3205 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3206 } 3207 3208 // Build a reference to this field within the parameter. 3209 CXXScopeSpec SS; 3210 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3211 Sema::LookupMemberName); 3212 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3213 : cast<ValueDecl>(Field), AS_public); 3214 MemberLookup.resolveKind(); 3215 ExprResult CtorArg 3216 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3217 ParamType, Loc, 3218 /*IsArrow=*/false, 3219 SS, 3220 /*TemplateKWLoc=*/SourceLocation(), 3221 /*FirstQualifierInScope=*/nullptr, 3222 MemberLookup, 3223 /*TemplateArgs=*/nullptr); 3224 if (CtorArg.isInvalid()) 3225 return true; 3226 3227 // C++11 [class.copy]p15: 3228 // - if a member m has rvalue reference type T&&, it is direct-initialized 3229 // with static_cast<T&&>(x.m); 3230 if (RefersToRValueRef(CtorArg.get())) { 3231 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3232 } 3233 3234 // When the field we are copying is an array, create index variables for 3235 // each dimension of the array. We use these index variables to subscript 3236 // the source array, and other clients (e.g., CodeGen) will perform the 3237 // necessary iteration with these index variables. 3238 SmallVector<VarDecl *, 4> IndexVariables; 3239 QualType BaseType = Field->getType(); 3240 QualType SizeType = SemaRef.Context.getSizeType(); 3241 bool InitializingArray = false; 3242 while (const ConstantArrayType *Array 3243 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3244 InitializingArray = true; 3245 // Create the iteration variable for this array index. 3246 IdentifierInfo *IterationVarName = nullptr; 3247 { 3248 SmallString<8> Str; 3249 llvm::raw_svector_ostream OS(Str); 3250 OS << "__i" << IndexVariables.size(); 3251 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3252 } 3253 VarDecl *IterationVar 3254 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3255 IterationVarName, SizeType, 3256 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3257 SC_None); 3258 IndexVariables.push_back(IterationVar); 3259 3260 // Create a reference to the iteration variable. 3261 ExprResult IterationVarRef 3262 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3263 assert(!IterationVarRef.isInvalid() && 3264 "Reference to invented variable cannot fail!"); 3265 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get()); 3266 assert(!IterationVarRef.isInvalid() && 3267 "Conversion of invented variable cannot fail!"); 3268 3269 // Subscript the array with this iteration variable. 3270 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc, 3271 IterationVarRef.get(), 3272 Loc); 3273 if (CtorArg.isInvalid()) 3274 return true; 3275 3276 BaseType = Array->getElementType(); 3277 } 3278 3279 // The array subscript expression is an lvalue, which is wrong for moving. 3280 if (Moving && InitializingArray) 3281 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3282 3283 // Construct the entity that we will be initializing. For an array, this 3284 // will be first element in the array, which may require several levels 3285 // of array-subscript entities. 3286 SmallVector<InitializedEntity, 4> Entities; 3287 Entities.reserve(1 + IndexVariables.size()); 3288 if (Indirect) 3289 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3290 else 3291 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3292 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3293 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3294 0, 3295 Entities.back())); 3296 3297 // Direct-initialize to use the copy constructor. 3298 InitializationKind InitKind = 3299 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3300 3301 Expr *CtorArgE = CtorArg.getAs<Expr>(); 3302 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE); 3303 3304 ExprResult MemberInit 3305 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3306 MultiExprArg(&CtorArgE, 1)); 3307 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3308 if (MemberInit.isInvalid()) 3309 return true; 3310 3311 if (Indirect) { 3312 assert(IndexVariables.size() == 0 && 3313 "Indirect field improperly initialized"); 3314 CXXMemberInit 3315 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3316 Loc, Loc, 3317 MemberInit.getAs<Expr>(), 3318 Loc); 3319 } else 3320 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3321 Loc, MemberInit.getAs<Expr>(), 3322 Loc, 3323 IndexVariables.data(), 3324 IndexVariables.size()); 3325 return false; 3326 } 3327 3328 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3329 "Unhandled implicit init kind!"); 3330 3331 QualType FieldBaseElementType = 3332 SemaRef.Context.getBaseElementType(Field->getType()); 3333 3334 if (FieldBaseElementType->isRecordType()) { 3335 InitializedEntity InitEntity 3336 = Indirect? InitializedEntity::InitializeMember(Indirect) 3337 : InitializedEntity::InitializeMember(Field); 3338 InitializationKind InitKind = 3339 InitializationKind::CreateDefault(Loc); 3340 3341 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3342 ExprResult MemberInit = 3343 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3344 3345 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3346 if (MemberInit.isInvalid()) 3347 return true; 3348 3349 if (Indirect) 3350 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3351 Indirect, Loc, 3352 Loc, 3353 MemberInit.get(), 3354 Loc); 3355 else 3356 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3357 Field, Loc, Loc, 3358 MemberInit.get(), 3359 Loc); 3360 return false; 3361 } 3362 3363 if (!Field->getParent()->isUnion()) { 3364 if (FieldBaseElementType->isReferenceType()) { 3365 SemaRef.Diag(Constructor->getLocation(), 3366 diag::err_uninitialized_member_in_ctor) 3367 << (int)Constructor->isImplicit() 3368 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3369 << 0 << Field->getDeclName(); 3370 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3371 return true; 3372 } 3373 3374 if (FieldBaseElementType.isConstQualified()) { 3375 SemaRef.Diag(Constructor->getLocation(), 3376 diag::err_uninitialized_member_in_ctor) 3377 << (int)Constructor->isImplicit() 3378 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3379 << 1 << Field->getDeclName(); 3380 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3381 return true; 3382 } 3383 } 3384 3385 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3386 FieldBaseElementType->isObjCRetainableType() && 3387 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3388 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3389 // ARC: 3390 // Default-initialize Objective-C pointers to NULL. 3391 CXXMemberInit 3392 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3393 Loc, Loc, 3394 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3395 Loc); 3396 return false; 3397 } 3398 3399 // Nothing to initialize. 3400 CXXMemberInit = nullptr; 3401 return false; 3402 } 3403 3404 namespace { 3405 struct BaseAndFieldInfo { 3406 Sema &S; 3407 CXXConstructorDecl *Ctor; 3408 bool AnyErrorsInInits; 3409 ImplicitInitializerKind IIK; 3410 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3411 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3412 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 3413 3414 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3415 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3416 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3417 if (Generated && Ctor->isCopyConstructor()) 3418 IIK = IIK_Copy; 3419 else if (Generated && Ctor->isMoveConstructor()) 3420 IIK = IIK_Move; 3421 else if (Ctor->getInheritedConstructor()) 3422 IIK = IIK_Inherit; 3423 else 3424 IIK = IIK_Default; 3425 } 3426 3427 bool isImplicitCopyOrMove() const { 3428 switch (IIK) { 3429 case IIK_Copy: 3430 case IIK_Move: 3431 return true; 3432 3433 case IIK_Default: 3434 case IIK_Inherit: 3435 return false; 3436 } 3437 3438 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3439 } 3440 3441 bool addFieldInitializer(CXXCtorInitializer *Init) { 3442 AllToInit.push_back(Init); 3443 3444 // Check whether this initializer makes the field "used". 3445 if (Init->getInit()->HasSideEffects(S.Context)) 3446 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3447 3448 return false; 3449 } 3450 3451 bool isInactiveUnionMember(FieldDecl *Field) { 3452 RecordDecl *Record = Field->getParent(); 3453 if (!Record->isUnion()) 3454 return false; 3455 3456 if (FieldDecl *Active = 3457 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 3458 return Active != Field->getCanonicalDecl(); 3459 3460 // In an implicit copy or move constructor, ignore any in-class initializer. 3461 if (isImplicitCopyOrMove()) 3462 return true; 3463 3464 // If there's no explicit initialization, the field is active only if it 3465 // has an in-class initializer... 3466 if (Field->hasInClassInitializer()) 3467 return false; 3468 // ... or it's an anonymous struct or union whose class has an in-class 3469 // initializer. 3470 if (!Field->isAnonymousStructOrUnion()) 3471 return true; 3472 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 3473 return !FieldRD->hasInClassInitializer(); 3474 } 3475 3476 /// \brief Determine whether the given field is, or is within, a union member 3477 /// that is inactive (because there was an initializer given for a different 3478 /// member of the union, or because the union was not initialized at all). 3479 bool isWithinInactiveUnionMember(FieldDecl *Field, 3480 IndirectFieldDecl *Indirect) { 3481 if (!Indirect) 3482 return isInactiveUnionMember(Field); 3483 3484 for (auto *C : Indirect->chain()) { 3485 FieldDecl *Field = dyn_cast<FieldDecl>(C); 3486 if (Field && isInactiveUnionMember(Field)) 3487 return true; 3488 } 3489 return false; 3490 } 3491 }; 3492 } 3493 3494 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3495 /// array type. 3496 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3497 if (T->isIncompleteArrayType()) 3498 return true; 3499 3500 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3501 if (!ArrayT->getSize()) 3502 return true; 3503 3504 T = ArrayT->getElementType(); 3505 } 3506 3507 return false; 3508 } 3509 3510 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3511 FieldDecl *Field, 3512 IndirectFieldDecl *Indirect = nullptr) { 3513 if (Field->isInvalidDecl()) 3514 return false; 3515 3516 // Overwhelmingly common case: we have a direct initializer for this field. 3517 if (CXXCtorInitializer *Init = 3518 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 3519 return Info.addFieldInitializer(Init); 3520 3521 // C++11 [class.base.init]p8: 3522 // if the entity is a non-static data member that has a 3523 // brace-or-equal-initializer and either 3524 // -- the constructor's class is a union and no other variant member of that 3525 // union is designated by a mem-initializer-id or 3526 // -- the constructor's class is not a union, and, if the entity is a member 3527 // of an anonymous union, no other member of that union is designated by 3528 // a mem-initializer-id, 3529 // the entity is initialized as specified in [dcl.init]. 3530 // 3531 // We also apply the same rules to handle anonymous structs within anonymous 3532 // unions. 3533 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 3534 return false; 3535 3536 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3537 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, 3538 Info.Ctor->getLocation(), Field); 3539 CXXCtorInitializer *Init; 3540 if (Indirect) 3541 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3542 SourceLocation(), 3543 SourceLocation(), DIE, 3544 SourceLocation()); 3545 else 3546 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3547 SourceLocation(), 3548 SourceLocation(), DIE, 3549 SourceLocation()); 3550 return Info.addFieldInitializer(Init); 3551 } 3552 3553 // Don't initialize incomplete or zero-length arrays. 3554 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3555 return false; 3556 3557 // Don't try to build an implicit initializer if there were semantic 3558 // errors in any of the initializers (and therefore we might be 3559 // missing some that the user actually wrote). 3560 if (Info.AnyErrorsInInits) 3561 return false; 3562 3563 CXXCtorInitializer *Init = nullptr; 3564 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3565 Indirect, Init)) 3566 return true; 3567 3568 if (!Init) 3569 return false; 3570 3571 return Info.addFieldInitializer(Init); 3572 } 3573 3574 bool 3575 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3576 CXXCtorInitializer *Initializer) { 3577 assert(Initializer->isDelegatingInitializer()); 3578 Constructor->setNumCtorInitializers(1); 3579 CXXCtorInitializer **initializer = 3580 new (Context) CXXCtorInitializer*[1]; 3581 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3582 Constructor->setCtorInitializers(initializer); 3583 3584 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3585 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3586 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3587 } 3588 3589 DelegatingCtorDecls.push_back(Constructor); 3590 3591 return false; 3592 } 3593 3594 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3595 ArrayRef<CXXCtorInitializer *> Initializers) { 3596 if (Constructor->isDependentContext()) { 3597 // Just store the initializers as written, they will be checked during 3598 // instantiation. 3599 if (!Initializers.empty()) { 3600 Constructor->setNumCtorInitializers(Initializers.size()); 3601 CXXCtorInitializer **baseOrMemberInitializers = 3602 new (Context) CXXCtorInitializer*[Initializers.size()]; 3603 memcpy(baseOrMemberInitializers, Initializers.data(), 3604 Initializers.size() * sizeof(CXXCtorInitializer*)); 3605 Constructor->setCtorInitializers(baseOrMemberInitializers); 3606 } 3607 3608 // Let template instantiation know whether we had errors. 3609 if (AnyErrors) 3610 Constructor->setInvalidDecl(); 3611 3612 return false; 3613 } 3614 3615 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3616 3617 // We need to build the initializer AST according to order of construction 3618 // and not what user specified in the Initializers list. 3619 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3620 if (!ClassDecl) 3621 return true; 3622 3623 bool HadError = false; 3624 3625 for (unsigned i = 0; i < Initializers.size(); i++) { 3626 CXXCtorInitializer *Member = Initializers[i]; 3627 3628 if (Member->isBaseInitializer()) 3629 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3630 else { 3631 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 3632 3633 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 3634 for (auto *C : F->chain()) { 3635 FieldDecl *FD = dyn_cast<FieldDecl>(C); 3636 if (FD && FD->getParent()->isUnion()) 3637 Info.ActiveUnionMember.insert(std::make_pair( 3638 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3639 } 3640 } else if (FieldDecl *FD = Member->getMember()) { 3641 if (FD->getParent()->isUnion()) 3642 Info.ActiveUnionMember.insert(std::make_pair( 3643 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3644 } 3645 } 3646 } 3647 3648 // Keep track of the direct virtual bases. 3649 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3650 for (auto &I : ClassDecl->bases()) { 3651 if (I.isVirtual()) 3652 DirectVBases.insert(&I); 3653 } 3654 3655 // Push virtual bases before others. 3656 for (auto &VBase : ClassDecl->vbases()) { 3657 if (CXXCtorInitializer *Value 3658 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 3659 // [class.base.init]p7, per DR257: 3660 // A mem-initializer where the mem-initializer-id names a virtual base 3661 // class is ignored during execution of a constructor of any class that 3662 // is not the most derived class. 3663 if (ClassDecl->isAbstract()) { 3664 // FIXME: Provide a fixit to remove the base specifier. This requires 3665 // tracking the location of the associated comma for a base specifier. 3666 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3667 << VBase.getType() << ClassDecl; 3668 DiagnoseAbstractType(ClassDecl); 3669 } 3670 3671 Info.AllToInit.push_back(Value); 3672 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3673 // [class.base.init]p8, per DR257: 3674 // If a given [...] base class is not named by a mem-initializer-id 3675 // [...] and the entity is not a virtual base class of an abstract 3676 // class, then [...] the entity is default-initialized. 3677 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 3678 CXXCtorInitializer *CXXBaseInit; 3679 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3680 &VBase, IsInheritedVirtualBase, 3681 CXXBaseInit)) { 3682 HadError = true; 3683 continue; 3684 } 3685 3686 Info.AllToInit.push_back(CXXBaseInit); 3687 } 3688 } 3689 3690 // Non-virtual bases. 3691 for (auto &Base : ClassDecl->bases()) { 3692 // Virtuals are in the virtual base list and already constructed. 3693 if (Base.isVirtual()) 3694 continue; 3695 3696 if (CXXCtorInitializer *Value 3697 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 3698 Info.AllToInit.push_back(Value); 3699 } else if (!AnyErrors) { 3700 CXXCtorInitializer *CXXBaseInit; 3701 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3702 &Base, /*IsInheritedVirtualBase=*/false, 3703 CXXBaseInit)) { 3704 HadError = true; 3705 continue; 3706 } 3707 3708 Info.AllToInit.push_back(CXXBaseInit); 3709 } 3710 } 3711 3712 // Fields. 3713 for (auto *Mem : ClassDecl->decls()) { 3714 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 3715 // C++ [class.bit]p2: 3716 // A declaration for a bit-field that omits the identifier declares an 3717 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3718 // initialized. 3719 if (F->isUnnamedBitfield()) 3720 continue; 3721 3722 // If we're not generating the implicit copy/move constructor, then we'll 3723 // handle anonymous struct/union fields based on their individual 3724 // indirect fields. 3725 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3726 continue; 3727 3728 if (CollectFieldInitializer(*this, Info, F)) 3729 HadError = true; 3730 continue; 3731 } 3732 3733 // Beyond this point, we only consider default initialization. 3734 if (Info.isImplicitCopyOrMove()) 3735 continue; 3736 3737 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 3738 if (F->getType()->isIncompleteArrayType()) { 3739 assert(ClassDecl->hasFlexibleArrayMember() && 3740 "Incomplete array type is not valid"); 3741 continue; 3742 } 3743 3744 // Initialize each field of an anonymous struct individually. 3745 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3746 HadError = true; 3747 3748 continue; 3749 } 3750 } 3751 3752 unsigned NumInitializers = Info.AllToInit.size(); 3753 if (NumInitializers > 0) { 3754 Constructor->setNumCtorInitializers(NumInitializers); 3755 CXXCtorInitializer **baseOrMemberInitializers = 3756 new (Context) CXXCtorInitializer*[NumInitializers]; 3757 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3758 NumInitializers * sizeof(CXXCtorInitializer*)); 3759 Constructor->setCtorInitializers(baseOrMemberInitializers); 3760 3761 // Constructors implicitly reference the base and member 3762 // destructors. 3763 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3764 Constructor->getParent()); 3765 } 3766 3767 return HadError; 3768 } 3769 3770 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3771 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3772 const RecordDecl *RD = RT->getDecl(); 3773 if (RD->isAnonymousStructOrUnion()) { 3774 for (auto *Field : RD->fields()) 3775 PopulateKeysForFields(Field, IdealInits); 3776 return; 3777 } 3778 } 3779 IdealInits.push_back(Field->getCanonicalDecl()); 3780 } 3781 3782 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3783 return Context.getCanonicalType(BaseType).getTypePtr(); 3784 } 3785 3786 static const void *GetKeyForMember(ASTContext &Context, 3787 CXXCtorInitializer *Member) { 3788 if (!Member->isAnyMemberInitializer()) 3789 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3790 3791 return Member->getAnyMember()->getCanonicalDecl(); 3792 } 3793 3794 static void DiagnoseBaseOrMemInitializerOrder( 3795 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3796 ArrayRef<CXXCtorInitializer *> Inits) { 3797 if (Constructor->getDeclContext()->isDependentContext()) 3798 return; 3799 3800 // Don't check initializers order unless the warning is enabled at the 3801 // location of at least one initializer. 3802 bool ShouldCheckOrder = false; 3803 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3804 CXXCtorInitializer *Init = Inits[InitIndex]; 3805 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 3806 Init->getSourceLocation())) { 3807 ShouldCheckOrder = true; 3808 break; 3809 } 3810 } 3811 if (!ShouldCheckOrder) 3812 return; 3813 3814 // Build the list of bases and members in the order that they'll 3815 // actually be initialized. The explicit initializers should be in 3816 // this same order but may be missing things. 3817 SmallVector<const void*, 32> IdealInitKeys; 3818 3819 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3820 3821 // 1. Virtual bases. 3822 for (const auto &VBase : ClassDecl->vbases()) 3823 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 3824 3825 // 2. Non-virtual bases. 3826 for (const auto &Base : ClassDecl->bases()) { 3827 if (Base.isVirtual()) 3828 continue; 3829 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 3830 } 3831 3832 // 3. Direct fields. 3833 for (auto *Field : ClassDecl->fields()) { 3834 if (Field->isUnnamedBitfield()) 3835 continue; 3836 3837 PopulateKeysForFields(Field, IdealInitKeys); 3838 } 3839 3840 unsigned NumIdealInits = IdealInitKeys.size(); 3841 unsigned IdealIndex = 0; 3842 3843 CXXCtorInitializer *PrevInit = nullptr; 3844 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3845 CXXCtorInitializer *Init = Inits[InitIndex]; 3846 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3847 3848 // Scan forward to try to find this initializer in the idealized 3849 // initializers list. 3850 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3851 if (InitKey == IdealInitKeys[IdealIndex]) 3852 break; 3853 3854 // If we didn't find this initializer, it must be because we 3855 // scanned past it on a previous iteration. That can only 3856 // happen if we're out of order; emit a warning. 3857 if (IdealIndex == NumIdealInits && PrevInit) { 3858 Sema::SemaDiagnosticBuilder D = 3859 SemaRef.Diag(PrevInit->getSourceLocation(), 3860 diag::warn_initializer_out_of_order); 3861 3862 if (PrevInit->isAnyMemberInitializer()) 3863 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3864 else 3865 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3866 3867 if (Init->isAnyMemberInitializer()) 3868 D << 0 << Init->getAnyMember()->getDeclName(); 3869 else 3870 D << 1 << Init->getTypeSourceInfo()->getType(); 3871 3872 // Move back to the initializer's location in the ideal list. 3873 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3874 if (InitKey == IdealInitKeys[IdealIndex]) 3875 break; 3876 3877 assert(IdealIndex != NumIdealInits && 3878 "initializer not found in initializer list"); 3879 } 3880 3881 PrevInit = Init; 3882 } 3883 } 3884 3885 namespace { 3886 bool CheckRedundantInit(Sema &S, 3887 CXXCtorInitializer *Init, 3888 CXXCtorInitializer *&PrevInit) { 3889 if (!PrevInit) { 3890 PrevInit = Init; 3891 return false; 3892 } 3893 3894 if (FieldDecl *Field = Init->getAnyMember()) 3895 S.Diag(Init->getSourceLocation(), 3896 diag::err_multiple_mem_initialization) 3897 << Field->getDeclName() 3898 << Init->getSourceRange(); 3899 else { 3900 const Type *BaseClass = Init->getBaseClass(); 3901 assert(BaseClass && "neither field nor base"); 3902 S.Diag(Init->getSourceLocation(), 3903 diag::err_multiple_base_initialization) 3904 << QualType(BaseClass, 0) 3905 << Init->getSourceRange(); 3906 } 3907 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3908 << 0 << PrevInit->getSourceRange(); 3909 3910 return true; 3911 } 3912 3913 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3914 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3915 3916 bool CheckRedundantUnionInit(Sema &S, 3917 CXXCtorInitializer *Init, 3918 RedundantUnionMap &Unions) { 3919 FieldDecl *Field = Init->getAnyMember(); 3920 RecordDecl *Parent = Field->getParent(); 3921 NamedDecl *Child = Field; 3922 3923 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3924 if (Parent->isUnion()) { 3925 UnionEntry &En = Unions[Parent]; 3926 if (En.first && En.first != Child) { 3927 S.Diag(Init->getSourceLocation(), 3928 diag::err_multiple_mem_union_initialization) 3929 << Field->getDeclName() 3930 << Init->getSourceRange(); 3931 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3932 << 0 << En.second->getSourceRange(); 3933 return true; 3934 } 3935 if (!En.first) { 3936 En.first = Child; 3937 En.second = Init; 3938 } 3939 if (!Parent->isAnonymousStructOrUnion()) 3940 return false; 3941 } 3942 3943 Child = Parent; 3944 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3945 } 3946 3947 return false; 3948 } 3949 } 3950 3951 /// ActOnMemInitializers - Handle the member initializers for a constructor. 3952 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3953 SourceLocation ColonLoc, 3954 ArrayRef<CXXCtorInitializer*> MemInits, 3955 bool AnyErrors) { 3956 if (!ConstructorDecl) 3957 return; 3958 3959 AdjustDeclIfTemplate(ConstructorDecl); 3960 3961 CXXConstructorDecl *Constructor 3962 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3963 3964 if (!Constructor) { 3965 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3966 return; 3967 } 3968 3969 // Mapping for the duplicate initializers check. 3970 // For member initializers, this is keyed with a FieldDecl*. 3971 // For base initializers, this is keyed with a Type*. 3972 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 3973 3974 // Mapping for the inconsistent anonymous-union initializers check. 3975 RedundantUnionMap MemberUnions; 3976 3977 bool HadError = false; 3978 for (unsigned i = 0; i < MemInits.size(); i++) { 3979 CXXCtorInitializer *Init = MemInits[i]; 3980 3981 // Set the source order index. 3982 Init->setSourceOrder(i); 3983 3984 if (Init->isAnyMemberInitializer()) { 3985 const void *Key = GetKeyForMember(Context, Init); 3986 if (CheckRedundantInit(*this, Init, Members[Key]) || 3987 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3988 HadError = true; 3989 } else if (Init->isBaseInitializer()) { 3990 const void *Key = GetKeyForMember(Context, Init); 3991 if (CheckRedundantInit(*this, Init, Members[Key])) 3992 HadError = true; 3993 } else { 3994 assert(Init->isDelegatingInitializer()); 3995 // This must be the only initializer 3996 if (MemInits.size() != 1) { 3997 Diag(Init->getSourceLocation(), 3998 diag::err_delegating_initializer_alone) 3999 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 4000 // We will treat this as being the only initializer. 4001 } 4002 SetDelegatingInitializer(Constructor, MemInits[i]); 4003 // Return immediately as the initializer is set. 4004 return; 4005 } 4006 } 4007 4008 if (HadError) 4009 return; 4010 4011 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 4012 4013 SetCtorInitializers(Constructor, AnyErrors, MemInits); 4014 4015 DiagnoseUninitializedFields(*this, Constructor); 4016 } 4017 4018 void 4019 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 4020 CXXRecordDecl *ClassDecl) { 4021 // Ignore dependent contexts. Also ignore unions, since their members never 4022 // have destructors implicitly called. 4023 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 4024 return; 4025 4026 // FIXME: all the access-control diagnostics are positioned on the 4027 // field/base declaration. That's probably good; that said, the 4028 // user might reasonably want to know why the destructor is being 4029 // emitted, and we currently don't say. 4030 4031 // Non-static data members. 4032 for (auto *Field : ClassDecl->fields()) { 4033 if (Field->isInvalidDecl()) 4034 continue; 4035 4036 // Don't destroy incomplete or zero-length arrays. 4037 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 4038 continue; 4039 4040 QualType FieldType = Context.getBaseElementType(Field->getType()); 4041 4042 const RecordType* RT = FieldType->getAs<RecordType>(); 4043 if (!RT) 4044 continue; 4045 4046 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4047 if (FieldClassDecl->isInvalidDecl()) 4048 continue; 4049 if (FieldClassDecl->hasIrrelevantDestructor()) 4050 continue; 4051 // The destructor for an implicit anonymous union member is never invoked. 4052 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 4053 continue; 4054 4055 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 4056 assert(Dtor && "No dtor found for FieldClassDecl!"); 4057 CheckDestructorAccess(Field->getLocation(), Dtor, 4058 PDiag(diag::err_access_dtor_field) 4059 << Field->getDeclName() 4060 << FieldType); 4061 4062 MarkFunctionReferenced(Location, Dtor); 4063 DiagnoseUseOfDecl(Dtor, Location); 4064 } 4065 4066 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 4067 4068 // Bases. 4069 for (const auto &Base : ClassDecl->bases()) { 4070 // Bases are always records in a well-formed non-dependent class. 4071 const RecordType *RT = Base.getType()->getAs<RecordType>(); 4072 4073 // Remember direct virtual bases. 4074 if (Base.isVirtual()) 4075 DirectVirtualBases.insert(RT); 4076 4077 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4078 // If our base class is invalid, we probably can't get its dtor anyway. 4079 if (BaseClassDecl->isInvalidDecl()) 4080 continue; 4081 if (BaseClassDecl->hasIrrelevantDestructor()) 4082 continue; 4083 4084 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4085 assert(Dtor && "No dtor found for BaseClassDecl!"); 4086 4087 // FIXME: caret should be on the start of the class name 4088 CheckDestructorAccess(Base.getLocStart(), Dtor, 4089 PDiag(diag::err_access_dtor_base) 4090 << Base.getType() 4091 << Base.getSourceRange(), 4092 Context.getTypeDeclType(ClassDecl)); 4093 4094 MarkFunctionReferenced(Location, Dtor); 4095 DiagnoseUseOfDecl(Dtor, Location); 4096 } 4097 4098 // Virtual bases. 4099 for (const auto &VBase : ClassDecl->vbases()) { 4100 // Bases are always records in a well-formed non-dependent class. 4101 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 4102 4103 // Ignore direct virtual bases. 4104 if (DirectVirtualBases.count(RT)) 4105 continue; 4106 4107 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4108 // If our base class is invalid, we probably can't get its dtor anyway. 4109 if (BaseClassDecl->isInvalidDecl()) 4110 continue; 4111 if (BaseClassDecl->hasIrrelevantDestructor()) 4112 continue; 4113 4114 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4115 assert(Dtor && "No dtor found for BaseClassDecl!"); 4116 if (CheckDestructorAccess( 4117 ClassDecl->getLocation(), Dtor, 4118 PDiag(diag::err_access_dtor_vbase) 4119 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 4120 Context.getTypeDeclType(ClassDecl)) == 4121 AR_accessible) { 4122 CheckDerivedToBaseConversion( 4123 Context.getTypeDeclType(ClassDecl), VBase.getType(), 4124 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4125 SourceRange(), DeclarationName(), nullptr); 4126 } 4127 4128 MarkFunctionReferenced(Location, Dtor); 4129 DiagnoseUseOfDecl(Dtor, Location); 4130 } 4131 } 4132 4133 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4134 if (!CDtorDecl) 4135 return; 4136 4137 if (CXXConstructorDecl *Constructor 4138 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 4139 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4140 DiagnoseUninitializedFields(*this, Constructor); 4141 } 4142 } 4143 4144 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4145 unsigned DiagID, AbstractDiagSelID SelID) { 4146 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4147 unsigned DiagID; 4148 AbstractDiagSelID SelID; 4149 4150 public: 4151 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4152 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4153 4154 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 4155 if (Suppressed) return; 4156 if (SelID == -1) 4157 S.Diag(Loc, DiagID) << T; 4158 else 4159 S.Diag(Loc, DiagID) << SelID << T; 4160 } 4161 } Diagnoser(DiagID, SelID); 4162 4163 return RequireNonAbstractType(Loc, T, Diagnoser); 4164 } 4165 4166 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4167 TypeDiagnoser &Diagnoser) { 4168 if (!getLangOpts().CPlusPlus) 4169 return false; 4170 4171 if (const ArrayType *AT = Context.getAsArrayType(T)) 4172 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4173 4174 if (const PointerType *PT = T->getAs<PointerType>()) { 4175 // Find the innermost pointer type. 4176 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4177 PT = T; 4178 4179 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4180 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4181 } 4182 4183 const RecordType *RT = T->getAs<RecordType>(); 4184 if (!RT) 4185 return false; 4186 4187 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4188 4189 // We can't answer whether something is abstract until it has a 4190 // definition. If it's currently being defined, we'll walk back 4191 // over all the declarations when we have a full definition. 4192 const CXXRecordDecl *Def = RD->getDefinition(); 4193 if (!Def || Def->isBeingDefined()) 4194 return false; 4195 4196 if (!RD->isAbstract()) 4197 return false; 4198 4199 Diagnoser.diagnose(*this, Loc, T); 4200 DiagnoseAbstractType(RD); 4201 4202 return true; 4203 } 4204 4205 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4206 // Check if we've already emitted the list of pure virtual functions 4207 // for this class. 4208 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4209 return; 4210 4211 // If the diagnostic is suppressed, don't emit the notes. We're only 4212 // going to emit them once, so try to attach them to a diagnostic we're 4213 // actually going to show. 4214 if (Diags.isLastDiagnosticIgnored()) 4215 return; 4216 4217 CXXFinalOverriderMap FinalOverriders; 4218 RD->getFinalOverriders(FinalOverriders); 4219 4220 // Keep a set of seen pure methods so we won't diagnose the same method 4221 // more than once. 4222 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4223 4224 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4225 MEnd = FinalOverriders.end(); 4226 M != MEnd; 4227 ++M) { 4228 for (OverridingMethods::iterator SO = M->second.begin(), 4229 SOEnd = M->second.end(); 4230 SO != SOEnd; ++SO) { 4231 // C++ [class.abstract]p4: 4232 // A class is abstract if it contains or inherits at least one 4233 // pure virtual function for which the final overrider is pure 4234 // virtual. 4235 4236 // 4237 if (SO->second.size() != 1) 4238 continue; 4239 4240 if (!SO->second.front().Method->isPure()) 4241 continue; 4242 4243 if (!SeenPureMethods.insert(SO->second.front().Method)) 4244 continue; 4245 4246 Diag(SO->second.front().Method->getLocation(), 4247 diag::note_pure_virtual_function) 4248 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4249 } 4250 } 4251 4252 if (!PureVirtualClassDiagSet) 4253 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4254 PureVirtualClassDiagSet->insert(RD); 4255 } 4256 4257 namespace { 4258 struct AbstractUsageInfo { 4259 Sema &S; 4260 CXXRecordDecl *Record; 4261 CanQualType AbstractType; 4262 bool Invalid; 4263 4264 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4265 : S(S), Record(Record), 4266 AbstractType(S.Context.getCanonicalType( 4267 S.Context.getTypeDeclType(Record))), 4268 Invalid(false) {} 4269 4270 void DiagnoseAbstractType() { 4271 if (Invalid) return; 4272 S.DiagnoseAbstractType(Record); 4273 Invalid = true; 4274 } 4275 4276 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4277 }; 4278 4279 struct CheckAbstractUsage { 4280 AbstractUsageInfo &Info; 4281 const NamedDecl *Ctx; 4282 4283 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4284 : Info(Info), Ctx(Ctx) {} 4285 4286 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4287 switch (TL.getTypeLocClass()) { 4288 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4289 #define TYPELOC(CLASS, PARENT) \ 4290 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4291 #include "clang/AST/TypeLocNodes.def" 4292 } 4293 } 4294 4295 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4296 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 4297 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 4298 if (!TL.getParam(I)) 4299 continue; 4300 4301 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 4302 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4303 } 4304 } 4305 4306 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4307 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4308 } 4309 4310 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4311 // Visit the type parameters from a permissive context. 4312 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4313 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4314 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4315 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4316 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4317 // TODO: other template argument types? 4318 } 4319 } 4320 4321 // Visit pointee types from a permissive context. 4322 #define CheckPolymorphic(Type) \ 4323 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4324 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4325 } 4326 CheckPolymorphic(PointerTypeLoc) 4327 CheckPolymorphic(ReferenceTypeLoc) 4328 CheckPolymorphic(MemberPointerTypeLoc) 4329 CheckPolymorphic(BlockPointerTypeLoc) 4330 CheckPolymorphic(AtomicTypeLoc) 4331 4332 /// Handle all the types we haven't given a more specific 4333 /// implementation for above. 4334 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4335 // Every other kind of type that we haven't called out already 4336 // that has an inner type is either (1) sugar or (2) contains that 4337 // inner type in some way as a subobject. 4338 if (TypeLoc Next = TL.getNextTypeLoc()) 4339 return Visit(Next, Sel); 4340 4341 // If there's no inner type and we're in a permissive context, 4342 // don't diagnose. 4343 if (Sel == Sema::AbstractNone) return; 4344 4345 // Check whether the type matches the abstract type. 4346 QualType T = TL.getType(); 4347 if (T->isArrayType()) { 4348 Sel = Sema::AbstractArrayType; 4349 T = Info.S.Context.getBaseElementType(T); 4350 } 4351 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4352 if (CT != Info.AbstractType) return; 4353 4354 // It matched; do some magic. 4355 if (Sel == Sema::AbstractArrayType) { 4356 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4357 << T << TL.getSourceRange(); 4358 } else { 4359 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4360 << Sel << T << TL.getSourceRange(); 4361 } 4362 Info.DiagnoseAbstractType(); 4363 } 4364 }; 4365 4366 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4367 Sema::AbstractDiagSelID Sel) { 4368 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4369 } 4370 4371 } 4372 4373 /// Check for invalid uses of an abstract type in a method declaration. 4374 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4375 CXXMethodDecl *MD) { 4376 // No need to do the check on definitions, which require that 4377 // the return/param types be complete. 4378 if (MD->doesThisDeclarationHaveABody()) 4379 return; 4380 4381 // For safety's sake, just ignore it if we don't have type source 4382 // information. This should never happen for non-implicit methods, 4383 // but... 4384 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4385 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4386 } 4387 4388 /// Check for invalid uses of an abstract type within a class definition. 4389 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4390 CXXRecordDecl *RD) { 4391 for (auto *D : RD->decls()) { 4392 if (D->isImplicit()) continue; 4393 4394 // Methods and method templates. 4395 if (isa<CXXMethodDecl>(D)) { 4396 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4397 } else if (isa<FunctionTemplateDecl>(D)) { 4398 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4399 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4400 4401 // Fields and static variables. 4402 } else if (isa<FieldDecl>(D)) { 4403 FieldDecl *FD = cast<FieldDecl>(D); 4404 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4405 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4406 } else if (isa<VarDecl>(D)) { 4407 VarDecl *VD = cast<VarDecl>(D); 4408 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4409 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4410 4411 // Nested classes and class templates. 4412 } else if (isa<CXXRecordDecl>(D)) { 4413 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4414 } else if (isa<ClassTemplateDecl>(D)) { 4415 CheckAbstractClassUsage(Info, 4416 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4417 } 4418 } 4419 } 4420 4421 /// \brief Check class-level dllimport/dllexport attribute. 4422 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) { 4423 Attr *ClassAttr = getDLLAttr(Class); 4424 if (!ClassAttr) 4425 return; 4426 4427 bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 4428 4429 // Force declaration of implicit members so they can inherit the attribute. 4430 S.ForceDeclarationOfImplicitMembers(Class); 4431 4432 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 4433 // seem to be true in practice? 4434 4435 for (Decl *Member : Class->decls()) { 4436 VarDecl *VD = dyn_cast<VarDecl>(Member); 4437 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 4438 4439 // Only methods and static fields inherit the attributes. 4440 if (!VD && !MD) 4441 continue; 4442 4443 // Don't process deleted methods. 4444 if (MD && MD->isDeleted()) 4445 continue; 4446 4447 if (MD && MD->isMoveAssignmentOperator() && !ClassExported && 4448 MD->isInlined()) { 4449 // Current MSVC versions don't export the move assignment operators, so 4450 // don't attempt to import them if we have a definition. 4451 continue; 4452 } 4453 4454 if (InheritableAttr *MemberAttr = getDLLAttr(Member)) { 4455 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && 4456 !MemberAttr->isInherited() && !ClassAttr->isInherited()) { 4457 S.Diag(MemberAttr->getLocation(), 4458 diag::err_attribute_dll_member_of_dll_class) 4459 << MemberAttr << ClassAttr; 4460 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 4461 Member->setInvalidDecl(); 4462 continue; 4463 } 4464 } else { 4465 auto *NewAttr = 4466 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 4467 NewAttr->setInherited(true); 4468 Member->addAttr(NewAttr); 4469 } 4470 4471 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) { 4472 if (ClassExported) { 4473 if (MD->isUserProvided()) { 4474 // Instantiate non-default methods. 4475 S.MarkFunctionReferenced(Class->getLocation(), MD); 4476 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 4477 MD->isCopyAssignmentOperator() || 4478 MD->isMoveAssignmentOperator()) { 4479 // Instantiate non-trivial or explicitly defaulted methods, and the 4480 // copy assignment / move assignment operators. 4481 S.MarkFunctionReferenced(Class->getLocation(), MD); 4482 // Resolve its exception specification; CodeGen needs it. 4483 auto *FPT = MD->getType()->getAs<FunctionProtoType>(); 4484 S.ResolveExceptionSpec(Class->getLocation(), FPT); 4485 S.ActOnFinishInlineMethodDef(MD); 4486 } 4487 } 4488 } 4489 } 4490 } 4491 4492 /// \brief Perform semantic checks on a class definition that has been 4493 /// completing, introducing implicitly-declared members, checking for 4494 /// abstract types, etc. 4495 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4496 if (!Record) 4497 return; 4498 4499 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4500 AbstractUsageInfo Info(*this, Record); 4501 CheckAbstractClassUsage(Info, Record); 4502 } 4503 4504 // If this is not an aggregate type and has no user-declared constructor, 4505 // complain about any non-static data members of reference or const scalar 4506 // type, since they will never get initializers. 4507 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4508 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4509 !Record->isLambda()) { 4510 bool Complained = false; 4511 for (const auto *F : Record->fields()) { 4512 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4513 continue; 4514 4515 if (F->getType()->isReferenceType() || 4516 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4517 if (!Complained) { 4518 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4519 << Record->getTagKind() << Record; 4520 Complained = true; 4521 } 4522 4523 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4524 << F->getType()->isReferenceType() 4525 << F->getDeclName(); 4526 } 4527 } 4528 } 4529 4530 if (Record->isDynamicClass() && !Record->isDependentType()) 4531 DynamicClasses.push_back(Record); 4532 4533 if (Record->getIdentifier()) { 4534 // C++ [class.mem]p13: 4535 // If T is the name of a class, then each of the following shall have a 4536 // name different from T: 4537 // - every member of every anonymous union that is a member of class T. 4538 // 4539 // C++ [class.mem]p14: 4540 // In addition, if class T has a user-declared constructor (12.1), every 4541 // non-static data member of class T shall have a name different from T. 4542 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4543 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4544 ++I) { 4545 NamedDecl *D = *I; 4546 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4547 isa<IndirectFieldDecl>(D)) { 4548 Diag(D->getLocation(), diag::err_member_name_of_class) 4549 << D->getDeclName(); 4550 break; 4551 } 4552 } 4553 } 4554 4555 // Warn if the class has virtual methods but non-virtual public destructor. 4556 if (Record->isPolymorphic() && !Record->isDependentType()) { 4557 CXXDestructorDecl *dtor = Record->getDestructor(); 4558 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 4559 !Record->hasAttr<FinalAttr>()) 4560 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4561 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4562 } 4563 4564 if (Record->isAbstract()) { 4565 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4566 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4567 << FA->isSpelledAsSealed(); 4568 DiagnoseAbstractType(Record); 4569 } 4570 } 4571 4572 if (!Record->isDependentType()) { 4573 for (auto *M : Record->methods()) { 4574 // See if a method overloads virtual methods in a base 4575 // class without overriding any. 4576 if (!M->isStatic()) 4577 DiagnoseHiddenVirtualMethods(M); 4578 4579 // Check whether the explicitly-defaulted special members are valid. 4580 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4581 CheckExplicitlyDefaultedSpecialMember(M); 4582 4583 // For an explicitly defaulted or deleted special member, we defer 4584 // determining triviality until the class is complete. That time is now! 4585 if (!M->isImplicit() && !M->isUserProvided()) { 4586 CXXSpecialMember CSM = getSpecialMember(M); 4587 if (CSM != CXXInvalid) { 4588 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 4589 4590 // Inform the class that we've finished declaring this member. 4591 Record->finishedDefaultedOrDeletedMember(M); 4592 } 4593 } 4594 } 4595 } 4596 4597 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4598 // function that is not a constructor declares that member function to be 4599 // const. [...] The class of which that function is a member shall be 4600 // a literal type. 4601 // 4602 // If the class has virtual bases, any constexpr members will already have 4603 // been diagnosed by the checks performed on the member declaration, so 4604 // suppress this (less useful) diagnostic. 4605 // 4606 // We delay this until we know whether an explicitly-defaulted (or deleted) 4607 // destructor for the class is trivial. 4608 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4609 !Record->isLiteral() && !Record->getNumVBases()) { 4610 for (const auto *M : Record->methods()) { 4611 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) { 4612 switch (Record->getTemplateSpecializationKind()) { 4613 case TSK_ImplicitInstantiation: 4614 case TSK_ExplicitInstantiationDeclaration: 4615 case TSK_ExplicitInstantiationDefinition: 4616 // If a template instantiates to a non-literal type, but its members 4617 // instantiate to constexpr functions, the template is technically 4618 // ill-formed, but we allow it for sanity. 4619 continue; 4620 4621 case TSK_Undeclared: 4622 case TSK_ExplicitSpecialization: 4623 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4624 diag::err_constexpr_method_non_literal); 4625 break; 4626 } 4627 4628 // Only produce one error per class. 4629 break; 4630 } 4631 } 4632 } 4633 4634 // ms_struct is a request to use the same ABI rules as MSVC. Check 4635 // whether this class uses any C++ features that are implemented 4636 // completely differently in MSVC, and if so, emit a diagnostic. 4637 // That diagnostic defaults to an error, but we allow projects to 4638 // map it down to a warning (or ignore it). It's a fairly common 4639 // practice among users of the ms_struct pragma to mass-annotate 4640 // headers, sweeping up a bunch of types that the project doesn't 4641 // really rely on MSVC-compatible layout for. We must therefore 4642 // support "ms_struct except for C++ stuff" as a secondary ABI. 4643 if (Record->isMsStruct(Context) && 4644 (Record->isPolymorphic() || Record->getNumBases())) { 4645 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 4646 } 4647 4648 // Declare inheriting constructors. We do this eagerly here because: 4649 // - The standard requires an eager diagnostic for conflicting inheriting 4650 // constructors from different classes. 4651 // - The lazy declaration of the other implicit constructors is so as to not 4652 // waste space and performance on classes that are not meant to be 4653 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4654 // have inheriting constructors. 4655 DeclareInheritingConstructors(Record); 4656 4657 checkDLLAttribute(*this, Record); 4658 } 4659 4660 /// Look up the special member function that would be called by a special 4661 /// member function for a subobject of class type. 4662 /// 4663 /// \param Class The class type of the subobject. 4664 /// \param CSM The kind of special member function. 4665 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 4666 /// \param ConstRHS True if this is a copy operation with a const object 4667 /// on its RHS, that is, if the argument to the outer special member 4668 /// function is 'const' and this is not a field marked 'mutable'. 4669 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 4670 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 4671 unsigned FieldQuals, bool ConstRHS) { 4672 unsigned LHSQuals = 0; 4673 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 4674 LHSQuals = FieldQuals; 4675 4676 unsigned RHSQuals = FieldQuals; 4677 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4678 RHSQuals = 0; 4679 else if (ConstRHS) 4680 RHSQuals |= Qualifiers::Const; 4681 4682 return S.LookupSpecialMember(Class, CSM, 4683 RHSQuals & Qualifiers::Const, 4684 RHSQuals & Qualifiers::Volatile, 4685 false, 4686 LHSQuals & Qualifiers::Const, 4687 LHSQuals & Qualifiers::Volatile); 4688 } 4689 4690 /// Is the special member function which would be selected to perform the 4691 /// specified operation on the specified class type a constexpr constructor? 4692 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4693 Sema::CXXSpecialMember CSM, 4694 unsigned Quals, bool ConstRHS) { 4695 Sema::SpecialMemberOverloadResult *SMOR = 4696 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 4697 if (!SMOR || !SMOR->getMethod()) 4698 // A constructor we wouldn't select can't be "involved in initializing" 4699 // anything. 4700 return true; 4701 return SMOR->getMethod()->isConstexpr(); 4702 } 4703 4704 /// Determine whether the specified special member function would be constexpr 4705 /// if it were implicitly defined. 4706 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4707 Sema::CXXSpecialMember CSM, 4708 bool ConstArg) { 4709 if (!S.getLangOpts().CPlusPlus11) 4710 return false; 4711 4712 // C++11 [dcl.constexpr]p4: 4713 // In the definition of a constexpr constructor [...] 4714 bool Ctor = true; 4715 switch (CSM) { 4716 case Sema::CXXDefaultConstructor: 4717 // Since default constructor lookup is essentially trivial (and cannot 4718 // involve, for instance, template instantiation), we compute whether a 4719 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4720 // 4721 // This is important for performance; we need to know whether the default 4722 // constructor is constexpr to determine whether the type is a literal type. 4723 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4724 4725 case Sema::CXXCopyConstructor: 4726 case Sema::CXXMoveConstructor: 4727 // For copy or move constructors, we need to perform overload resolution. 4728 break; 4729 4730 case Sema::CXXCopyAssignment: 4731 case Sema::CXXMoveAssignment: 4732 if (!S.getLangOpts().CPlusPlus1y) 4733 return false; 4734 // In C++1y, we need to perform overload resolution. 4735 Ctor = false; 4736 break; 4737 4738 case Sema::CXXDestructor: 4739 case Sema::CXXInvalid: 4740 return false; 4741 } 4742 4743 // -- if the class is a non-empty union, or for each non-empty anonymous 4744 // union member of a non-union class, exactly one non-static data member 4745 // shall be initialized; [DR1359] 4746 // 4747 // If we squint, this is guaranteed, since exactly one non-static data member 4748 // will be initialized (if the constructor isn't deleted), we just don't know 4749 // which one. 4750 if (Ctor && ClassDecl->isUnion()) 4751 return true; 4752 4753 // -- the class shall not have any virtual base classes; 4754 if (Ctor && ClassDecl->getNumVBases()) 4755 return false; 4756 4757 // C++1y [class.copy]p26: 4758 // -- [the class] is a literal type, and 4759 if (!Ctor && !ClassDecl->isLiteral()) 4760 return false; 4761 4762 // -- every constructor involved in initializing [...] base class 4763 // sub-objects shall be a constexpr constructor; 4764 // -- the assignment operator selected to copy/move each direct base 4765 // class is a constexpr function, and 4766 for (const auto &B : ClassDecl->bases()) { 4767 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 4768 if (!BaseType) continue; 4769 4770 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4771 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg)) 4772 return false; 4773 } 4774 4775 // -- every constructor involved in initializing non-static data members 4776 // [...] shall be a constexpr constructor; 4777 // -- every non-static data member and base class sub-object shall be 4778 // initialized 4779 // -- for each non-static data member of X that is of class type (or array 4780 // thereof), the assignment operator selected to copy/move that member is 4781 // a constexpr function 4782 for (const auto *F : ClassDecl->fields()) { 4783 if (F->isInvalidDecl()) 4784 continue; 4785 QualType BaseType = S.Context.getBaseElementType(F->getType()); 4786 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 4787 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4788 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 4789 BaseType.getCVRQualifiers(), 4790 ConstArg && !F->isMutable())) 4791 return false; 4792 } 4793 } 4794 4795 // All OK, it's constexpr! 4796 return true; 4797 } 4798 4799 static Sema::ImplicitExceptionSpecification 4800 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4801 switch (S.getSpecialMember(MD)) { 4802 case Sema::CXXDefaultConstructor: 4803 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4804 case Sema::CXXCopyConstructor: 4805 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4806 case Sema::CXXCopyAssignment: 4807 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4808 case Sema::CXXMoveConstructor: 4809 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4810 case Sema::CXXMoveAssignment: 4811 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4812 case Sema::CXXDestructor: 4813 return S.ComputeDefaultedDtorExceptionSpec(MD); 4814 case Sema::CXXInvalid: 4815 break; 4816 } 4817 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 4818 "only special members have implicit exception specs"); 4819 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 4820 } 4821 4822 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 4823 CXXMethodDecl *MD) { 4824 FunctionProtoType::ExtProtoInfo EPI; 4825 4826 // Build an exception specification pointing back at this member. 4827 EPI.ExceptionSpec.Type = EST_Unevaluated; 4828 EPI.ExceptionSpec.SourceDecl = MD; 4829 4830 // Set the calling convention to the default for C++ instance methods. 4831 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 4832 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 4833 /*IsCXXMethod=*/true)); 4834 return EPI; 4835 } 4836 4837 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4838 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4839 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4840 return; 4841 4842 // Evaluate the exception specification. 4843 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec(); 4844 4845 // Update the type of the special member to use it. 4846 UpdateExceptionSpec(MD, ESI); 4847 4848 // A user-provided destructor can be defined outside the class. When that 4849 // happens, be sure to update the exception specification on both 4850 // declarations. 4851 const FunctionProtoType *CanonicalFPT = 4852 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4853 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4854 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 4855 } 4856 4857 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4858 CXXRecordDecl *RD = MD->getParent(); 4859 CXXSpecialMember CSM = getSpecialMember(MD); 4860 4861 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4862 "not an explicitly-defaulted special member"); 4863 4864 // Whether this was the first-declared instance of the constructor. 4865 // This affects whether we implicitly add an exception spec and constexpr. 4866 bool First = MD == MD->getCanonicalDecl(); 4867 4868 bool HadError = false; 4869 4870 // C++11 [dcl.fct.def.default]p1: 4871 // A function that is explicitly defaulted shall 4872 // -- be a special member function (checked elsewhere), 4873 // -- have the same type (except for ref-qualifiers, and except that a 4874 // copy operation can take a non-const reference) as an implicit 4875 // declaration, and 4876 // -- not have default arguments. 4877 unsigned ExpectedParams = 1; 4878 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4879 ExpectedParams = 0; 4880 if (MD->getNumParams() != ExpectedParams) { 4881 // This also checks for default arguments: a copy or move constructor with a 4882 // default argument is classified as a default constructor, and assignment 4883 // operations and destructors can't have default arguments. 4884 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4885 << CSM << MD->getSourceRange(); 4886 HadError = true; 4887 } else if (MD->isVariadic()) { 4888 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4889 << CSM << MD->getSourceRange(); 4890 HadError = true; 4891 } 4892 4893 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4894 4895 bool CanHaveConstParam = false; 4896 if (CSM == CXXCopyConstructor) 4897 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4898 else if (CSM == CXXCopyAssignment) 4899 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4900 4901 QualType ReturnType = Context.VoidTy; 4902 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4903 // Check for return type matching. 4904 ReturnType = Type->getReturnType(); 4905 QualType ExpectedReturnType = 4906 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4907 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4908 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4909 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4910 HadError = true; 4911 } 4912 4913 // A defaulted special member cannot have cv-qualifiers. 4914 if (Type->getTypeQuals()) { 4915 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4916 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y; 4917 HadError = true; 4918 } 4919 } 4920 4921 // Check for parameter type matching. 4922 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 4923 bool HasConstParam = false; 4924 if (ExpectedParams && ArgType->isReferenceType()) { 4925 // Argument must be reference to possibly-const T. 4926 QualType ReferentType = ArgType->getPointeeType(); 4927 HasConstParam = ReferentType.isConstQualified(); 4928 4929 if (ReferentType.isVolatileQualified()) { 4930 Diag(MD->getLocation(), 4931 diag::err_defaulted_special_member_volatile_param) << CSM; 4932 HadError = true; 4933 } 4934 4935 if (HasConstParam && !CanHaveConstParam) { 4936 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4937 Diag(MD->getLocation(), 4938 diag::err_defaulted_special_member_copy_const_param) 4939 << (CSM == CXXCopyAssignment); 4940 // FIXME: Explain why this special member can't be const. 4941 } else { 4942 Diag(MD->getLocation(), 4943 diag::err_defaulted_special_member_move_const_param) 4944 << (CSM == CXXMoveAssignment); 4945 } 4946 HadError = true; 4947 } 4948 } else if (ExpectedParams) { 4949 // A copy assignment operator can take its argument by value, but a 4950 // defaulted one cannot. 4951 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4952 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4953 HadError = true; 4954 } 4955 4956 // C++11 [dcl.fct.def.default]p2: 4957 // An explicitly-defaulted function may be declared constexpr only if it 4958 // would have been implicitly declared as constexpr, 4959 // Do not apply this rule to members of class templates, since core issue 1358 4960 // makes such functions always instantiate to constexpr functions. For 4961 // functions which cannot be constexpr (for non-constructors in C++11 and for 4962 // destructors in C++1y), this is checked elsewhere. 4963 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4964 HasConstParam); 4965 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD) 4966 : isa<CXXConstructorDecl>(MD)) && 4967 MD->isConstexpr() && !Constexpr && 4968 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4969 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4970 // FIXME: Explain why the special member can't be constexpr. 4971 HadError = true; 4972 } 4973 4974 // and may have an explicit exception-specification only if it is compatible 4975 // with the exception-specification on the implicit declaration. 4976 if (Type->hasExceptionSpec()) { 4977 // Delay the check if this is the first declaration of the special member, 4978 // since we may not have parsed some necessary in-class initializers yet. 4979 if (First) { 4980 // If the exception specification needs to be instantiated, do so now, 4981 // before we clobber it with an EST_Unevaluated specification below. 4982 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 4983 InstantiateExceptionSpec(MD->getLocStart(), MD); 4984 Type = MD->getType()->getAs<FunctionProtoType>(); 4985 } 4986 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 4987 } else 4988 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 4989 } 4990 4991 // If a function is explicitly defaulted on its first declaration, 4992 if (First) { 4993 // -- it is implicitly considered to be constexpr if the implicit 4994 // definition would be, 4995 MD->setConstexpr(Constexpr); 4996 4997 // -- it is implicitly considered to have the same exception-specification 4998 // as if it had been implicitly declared, 4999 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 5000 EPI.ExceptionSpec.Type = EST_Unevaluated; 5001 EPI.ExceptionSpec.SourceDecl = MD; 5002 MD->setType(Context.getFunctionType(ReturnType, 5003 ArrayRef<QualType>(&ArgType, 5004 ExpectedParams), 5005 EPI)); 5006 } 5007 5008 if (ShouldDeleteSpecialMember(MD, CSM)) { 5009 if (First) { 5010 SetDeclDeleted(MD, MD->getLocation()); 5011 } else { 5012 // C++11 [dcl.fct.def.default]p4: 5013 // [For a] user-provided explicitly-defaulted function [...] if such a 5014 // function is implicitly defined as deleted, the program is ill-formed. 5015 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 5016 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true); 5017 HadError = true; 5018 } 5019 } 5020 5021 if (HadError) 5022 MD->setInvalidDecl(); 5023 } 5024 5025 /// Check whether the exception specification provided for an 5026 /// explicitly-defaulted special member matches the exception specification 5027 /// that would have been generated for an implicit special member, per 5028 /// C++11 [dcl.fct.def.default]p2. 5029 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 5030 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 5031 // Compute the implicit exception specification. 5032 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5033 /*IsCXXMethod=*/true); 5034 FunctionProtoType::ExtProtoInfo EPI(CC); 5035 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD) 5036 .getExceptionSpec(); 5037 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 5038 Context.getFunctionType(Context.VoidTy, None, EPI)); 5039 5040 // Ensure that it matches. 5041 CheckEquivalentExceptionSpec( 5042 PDiag(diag::err_incorrect_defaulted_exception_spec) 5043 << getSpecialMember(MD), PDiag(), 5044 ImplicitType, SourceLocation(), 5045 SpecifiedType, MD->getLocation()); 5046 } 5047 5048 void Sema::CheckDelayedMemberExceptionSpecs() { 5049 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>, 5050 2> Checks; 5051 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs; 5052 5053 std::swap(Checks, DelayedDestructorExceptionSpecChecks); 5054 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 5055 5056 // Perform any deferred checking of exception specifications for virtual 5057 // destructors. 5058 for (unsigned i = 0, e = Checks.size(); i != e; ++i) { 5059 const CXXDestructorDecl *Dtor = Checks[i].first; 5060 assert(!Dtor->getParent()->isDependentType() && 5061 "Should not ever add destructors of templates into the list."); 5062 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second); 5063 } 5064 5065 // Check that any explicitly-defaulted methods have exception specifications 5066 // compatible with their implicit exception specifications. 5067 for (unsigned I = 0, N = Specs.size(); I != N; ++I) 5068 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first, 5069 Specs[I].second); 5070 } 5071 5072 namespace { 5073 struct SpecialMemberDeletionInfo { 5074 Sema &S; 5075 CXXMethodDecl *MD; 5076 Sema::CXXSpecialMember CSM; 5077 bool Diagnose; 5078 5079 // Properties of the special member, computed for convenience. 5080 bool IsConstructor, IsAssignment, IsMove, ConstArg; 5081 SourceLocation Loc; 5082 5083 bool AllFieldsAreConst; 5084 5085 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 5086 Sema::CXXSpecialMember CSM, bool Diagnose) 5087 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 5088 IsConstructor(false), IsAssignment(false), IsMove(false), 5089 ConstArg(false), Loc(MD->getLocation()), 5090 AllFieldsAreConst(true) { 5091 switch (CSM) { 5092 case Sema::CXXDefaultConstructor: 5093 case Sema::CXXCopyConstructor: 5094 IsConstructor = true; 5095 break; 5096 case Sema::CXXMoveConstructor: 5097 IsConstructor = true; 5098 IsMove = true; 5099 break; 5100 case Sema::CXXCopyAssignment: 5101 IsAssignment = true; 5102 break; 5103 case Sema::CXXMoveAssignment: 5104 IsAssignment = true; 5105 IsMove = true; 5106 break; 5107 case Sema::CXXDestructor: 5108 break; 5109 case Sema::CXXInvalid: 5110 llvm_unreachable("invalid special member kind"); 5111 } 5112 5113 if (MD->getNumParams()) { 5114 if (const ReferenceType *RT = 5115 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 5116 ConstArg = RT->getPointeeType().isConstQualified(); 5117 } 5118 } 5119 5120 bool inUnion() const { return MD->getParent()->isUnion(); } 5121 5122 /// Look up the corresponding special member in the given class. 5123 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 5124 unsigned Quals, bool IsMutable) { 5125 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 5126 ConstArg && !IsMutable); 5127 } 5128 5129 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 5130 5131 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 5132 bool shouldDeleteForField(FieldDecl *FD); 5133 bool shouldDeleteForAllConstMembers(); 5134 5135 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 5136 unsigned Quals); 5137 bool shouldDeleteForSubobjectCall(Subobject Subobj, 5138 Sema::SpecialMemberOverloadResult *SMOR, 5139 bool IsDtorCallInCtor); 5140 5141 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 5142 }; 5143 } 5144 5145 /// Is the given special member inaccessible when used on the given 5146 /// sub-object. 5147 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 5148 CXXMethodDecl *target) { 5149 /// If we're operating on a base class, the object type is the 5150 /// type of this special member. 5151 QualType objectTy; 5152 AccessSpecifier access = target->getAccess(); 5153 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 5154 objectTy = S.Context.getTypeDeclType(MD->getParent()); 5155 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 5156 5157 // If we're operating on a field, the object type is the type of the field. 5158 } else { 5159 objectTy = S.Context.getTypeDeclType(target->getParent()); 5160 } 5161 5162 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 5163 } 5164 5165 /// Check whether we should delete a special member due to the implicit 5166 /// definition containing a call to a special member of a subobject. 5167 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5168 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5169 bool IsDtorCallInCtor) { 5170 CXXMethodDecl *Decl = SMOR->getMethod(); 5171 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5172 5173 int DiagKind = -1; 5174 5175 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5176 DiagKind = !Decl ? 0 : 1; 5177 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5178 DiagKind = 2; 5179 else if (!isAccessible(Subobj, Decl)) 5180 DiagKind = 3; 5181 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5182 !Decl->isTrivial()) { 5183 // A member of a union must have a trivial corresponding special member. 5184 // As a weird special case, a destructor call from a union's constructor 5185 // must be accessible and non-deleted, but need not be trivial. Such a 5186 // destructor is never actually called, but is semantically checked as 5187 // if it were. 5188 DiagKind = 4; 5189 } 5190 5191 if (DiagKind == -1) 5192 return false; 5193 5194 if (Diagnose) { 5195 if (Field) { 5196 S.Diag(Field->getLocation(), 5197 diag::note_deleted_special_member_class_subobject) 5198 << CSM << MD->getParent() << /*IsField*/true 5199 << Field << DiagKind << IsDtorCallInCtor; 5200 } else { 5201 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5202 S.Diag(Base->getLocStart(), 5203 diag::note_deleted_special_member_class_subobject) 5204 << CSM << MD->getParent() << /*IsField*/false 5205 << Base->getType() << DiagKind << IsDtorCallInCtor; 5206 } 5207 5208 if (DiagKind == 1) 5209 S.NoteDeletedFunction(Decl); 5210 // FIXME: Explain inaccessibility if DiagKind == 3. 5211 } 5212 5213 return true; 5214 } 5215 5216 /// Check whether we should delete a special member function due to having a 5217 /// direct or virtual base class or non-static data member of class type M. 5218 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5219 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5220 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5221 bool IsMutable = Field && Field->isMutable(); 5222 5223 // C++11 [class.ctor]p5: 5224 // -- any direct or virtual base class, or non-static data member with no 5225 // brace-or-equal-initializer, has class type M (or array thereof) and 5226 // either M has no default constructor or overload resolution as applied 5227 // to M's default constructor results in an ambiguity or in a function 5228 // that is deleted or inaccessible 5229 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5230 // -- a direct or virtual base class B that cannot be copied/moved because 5231 // overload resolution, as applied to B's corresponding special member, 5232 // results in an ambiguity or a function that is deleted or inaccessible 5233 // from the defaulted special member 5234 // C++11 [class.dtor]p5: 5235 // -- any direct or virtual base class [...] has a type with a destructor 5236 // that is deleted or inaccessible 5237 if (!(CSM == Sema::CXXDefaultConstructor && 5238 Field && Field->hasInClassInitializer()) && 5239 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 5240 false)) 5241 return true; 5242 5243 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5244 // -- any direct or virtual base class or non-static data member has a 5245 // type with a destructor that is deleted or inaccessible 5246 if (IsConstructor) { 5247 Sema::SpecialMemberOverloadResult *SMOR = 5248 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5249 false, false, false, false, false); 5250 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5251 return true; 5252 } 5253 5254 return false; 5255 } 5256 5257 /// Check whether we should delete a special member function due to the class 5258 /// having a particular direct or virtual base class. 5259 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5260 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5261 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5262 } 5263 5264 /// Check whether we should delete a special member function due to the class 5265 /// having a particular non-static data member. 5266 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5267 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5268 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5269 5270 if (CSM == Sema::CXXDefaultConstructor) { 5271 // For a default constructor, all references must be initialized in-class 5272 // and, if a union, it must have a non-const member. 5273 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5274 if (Diagnose) 5275 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5276 << MD->getParent() << FD << FieldType << /*Reference*/0; 5277 return true; 5278 } 5279 // C++11 [class.ctor]p5: any non-variant non-static data member of 5280 // const-qualified type (or array thereof) with no 5281 // brace-or-equal-initializer does not have a user-provided default 5282 // constructor. 5283 if (!inUnion() && FieldType.isConstQualified() && 5284 !FD->hasInClassInitializer() && 5285 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5286 if (Diagnose) 5287 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5288 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5289 return true; 5290 } 5291 5292 if (inUnion() && !FieldType.isConstQualified()) 5293 AllFieldsAreConst = false; 5294 } else if (CSM == Sema::CXXCopyConstructor) { 5295 // For a copy constructor, data members must not be of rvalue reference 5296 // type. 5297 if (FieldType->isRValueReferenceType()) { 5298 if (Diagnose) 5299 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5300 << MD->getParent() << FD << FieldType; 5301 return true; 5302 } 5303 } else if (IsAssignment) { 5304 // For an assignment operator, data members must not be of reference type. 5305 if (FieldType->isReferenceType()) { 5306 if (Diagnose) 5307 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5308 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5309 return true; 5310 } 5311 if (!FieldRecord && FieldType.isConstQualified()) { 5312 // C++11 [class.copy]p23: 5313 // -- a non-static data member of const non-class type (or array thereof) 5314 if (Diagnose) 5315 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5316 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5317 return true; 5318 } 5319 } 5320 5321 if (FieldRecord) { 5322 // Some additional restrictions exist on the variant members. 5323 if (!inUnion() && FieldRecord->isUnion() && 5324 FieldRecord->isAnonymousStructOrUnion()) { 5325 bool AllVariantFieldsAreConst = true; 5326 5327 // FIXME: Handle anonymous unions declared within anonymous unions. 5328 for (auto *UI : FieldRecord->fields()) { 5329 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5330 5331 if (!UnionFieldType.isConstQualified()) 5332 AllVariantFieldsAreConst = false; 5333 5334 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5335 if (UnionFieldRecord && 5336 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 5337 UnionFieldType.getCVRQualifiers())) 5338 return true; 5339 } 5340 5341 // At least one member in each anonymous union must be non-const 5342 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5343 !FieldRecord->field_empty()) { 5344 if (Diagnose) 5345 S.Diag(FieldRecord->getLocation(), 5346 diag::note_deleted_default_ctor_all_const) 5347 << MD->getParent() << /*anonymous union*/1; 5348 return true; 5349 } 5350 5351 // Don't check the implicit member of the anonymous union type. 5352 // This is technically non-conformant, but sanity demands it. 5353 return false; 5354 } 5355 5356 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5357 FieldType.getCVRQualifiers())) 5358 return true; 5359 } 5360 5361 return false; 5362 } 5363 5364 /// C++11 [class.ctor] p5: 5365 /// A defaulted default constructor for a class X is defined as deleted if 5366 /// X is a union and all of its variant members are of const-qualified type. 5367 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5368 // This is a silly definition, because it gives an empty union a deleted 5369 // default constructor. Don't do that. 5370 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5371 !MD->getParent()->field_empty()) { 5372 if (Diagnose) 5373 S.Diag(MD->getParent()->getLocation(), 5374 diag::note_deleted_default_ctor_all_const) 5375 << MD->getParent() << /*not anonymous union*/0; 5376 return true; 5377 } 5378 return false; 5379 } 5380 5381 /// Determine whether a defaulted special member function should be defined as 5382 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5383 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5384 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5385 bool Diagnose) { 5386 if (MD->isInvalidDecl()) 5387 return false; 5388 CXXRecordDecl *RD = MD->getParent(); 5389 assert(!RD->isDependentType() && "do deletion after instantiation"); 5390 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5391 return false; 5392 5393 // C++11 [expr.lambda.prim]p19: 5394 // The closure type associated with a lambda-expression has a 5395 // deleted (8.4.3) default constructor and a deleted copy 5396 // assignment operator. 5397 if (RD->isLambda() && 5398 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5399 if (Diagnose) 5400 Diag(RD->getLocation(), diag::note_lambda_decl); 5401 return true; 5402 } 5403 5404 // For an anonymous struct or union, the copy and assignment special members 5405 // will never be used, so skip the check. For an anonymous union declared at 5406 // namespace scope, the constructor and destructor are used. 5407 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5408 RD->isAnonymousStructOrUnion()) 5409 return false; 5410 5411 // C++11 [class.copy]p7, p18: 5412 // If the class definition declares a move constructor or move assignment 5413 // operator, an implicitly declared copy constructor or copy assignment 5414 // operator is defined as deleted. 5415 if (MD->isImplicit() && 5416 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5417 CXXMethodDecl *UserDeclaredMove = nullptr; 5418 5419 // In Microsoft mode, a user-declared move only causes the deletion of the 5420 // corresponding copy operation, not both copy operations. 5421 if (RD->hasUserDeclaredMoveConstructor() && 5422 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 5423 if (!Diagnose) return true; 5424 5425 // Find any user-declared move constructor. 5426 for (auto *I : RD->ctors()) { 5427 if (I->isMoveConstructor()) { 5428 UserDeclaredMove = I; 5429 break; 5430 } 5431 } 5432 assert(UserDeclaredMove); 5433 } else if (RD->hasUserDeclaredMoveAssignment() && 5434 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 5435 if (!Diagnose) return true; 5436 5437 // Find any user-declared move assignment operator. 5438 for (auto *I : RD->methods()) { 5439 if (I->isMoveAssignmentOperator()) { 5440 UserDeclaredMove = I; 5441 break; 5442 } 5443 } 5444 assert(UserDeclaredMove); 5445 } 5446 5447 if (UserDeclaredMove) { 5448 Diag(UserDeclaredMove->getLocation(), 5449 diag::note_deleted_copy_user_declared_move) 5450 << (CSM == CXXCopyAssignment) << RD 5451 << UserDeclaredMove->isMoveAssignmentOperator(); 5452 return true; 5453 } 5454 } 5455 5456 // Do access control from the special member function 5457 ContextRAII MethodContext(*this, MD); 5458 5459 // C++11 [class.dtor]p5: 5460 // -- for a virtual destructor, lookup of the non-array deallocation function 5461 // results in an ambiguity or in a function that is deleted or inaccessible 5462 if (CSM == CXXDestructor && MD->isVirtual()) { 5463 FunctionDecl *OperatorDelete = nullptr; 5464 DeclarationName Name = 5465 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5466 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5467 OperatorDelete, false)) { 5468 if (Diagnose) 5469 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5470 return true; 5471 } 5472 } 5473 5474 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5475 5476 for (auto &BI : RD->bases()) 5477 if (!BI.isVirtual() && 5478 SMI.shouldDeleteForBase(&BI)) 5479 return true; 5480 5481 // Per DR1611, do not consider virtual bases of constructors of abstract 5482 // classes, since we are not going to construct them. 5483 if (!RD->isAbstract() || !SMI.IsConstructor) { 5484 for (auto &BI : RD->vbases()) 5485 if (SMI.shouldDeleteForBase(&BI)) 5486 return true; 5487 } 5488 5489 for (auto *FI : RD->fields()) 5490 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5491 SMI.shouldDeleteForField(FI)) 5492 return true; 5493 5494 if (SMI.shouldDeleteForAllConstMembers()) 5495 return true; 5496 5497 return false; 5498 } 5499 5500 /// Perform lookup for a special member of the specified kind, and determine 5501 /// whether it is trivial. If the triviality can be determined without the 5502 /// lookup, skip it. This is intended for use when determining whether a 5503 /// special member of a containing object is trivial, and thus does not ever 5504 /// perform overload resolution for default constructors. 5505 /// 5506 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5507 /// member that was most likely to be intended to be trivial, if any. 5508 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5509 Sema::CXXSpecialMember CSM, unsigned Quals, 5510 bool ConstRHS, CXXMethodDecl **Selected) { 5511 if (Selected) 5512 *Selected = nullptr; 5513 5514 switch (CSM) { 5515 case Sema::CXXInvalid: 5516 llvm_unreachable("not a special member"); 5517 5518 case Sema::CXXDefaultConstructor: 5519 // C++11 [class.ctor]p5: 5520 // A default constructor is trivial if: 5521 // - all the [direct subobjects] have trivial default constructors 5522 // 5523 // Note, no overload resolution is performed in this case. 5524 if (RD->hasTrivialDefaultConstructor()) 5525 return true; 5526 5527 if (Selected) { 5528 // If there's a default constructor which could have been trivial, dig it 5529 // out. Otherwise, if there's any user-provided default constructor, point 5530 // to that as an example of why there's not a trivial one. 5531 CXXConstructorDecl *DefCtor = nullptr; 5532 if (RD->needsImplicitDefaultConstructor()) 5533 S.DeclareImplicitDefaultConstructor(RD); 5534 for (auto *CI : RD->ctors()) { 5535 if (!CI->isDefaultConstructor()) 5536 continue; 5537 DefCtor = CI; 5538 if (!DefCtor->isUserProvided()) 5539 break; 5540 } 5541 5542 *Selected = DefCtor; 5543 } 5544 5545 return false; 5546 5547 case Sema::CXXDestructor: 5548 // C++11 [class.dtor]p5: 5549 // A destructor is trivial if: 5550 // - all the direct [subobjects] have trivial destructors 5551 if (RD->hasTrivialDestructor()) 5552 return true; 5553 5554 if (Selected) { 5555 if (RD->needsImplicitDestructor()) 5556 S.DeclareImplicitDestructor(RD); 5557 *Selected = RD->getDestructor(); 5558 } 5559 5560 return false; 5561 5562 case Sema::CXXCopyConstructor: 5563 // C++11 [class.copy]p12: 5564 // A copy constructor is trivial if: 5565 // - the constructor selected to copy each direct [subobject] is trivial 5566 if (RD->hasTrivialCopyConstructor()) { 5567 if (Quals == Qualifiers::Const) 5568 // We must either select the trivial copy constructor or reach an 5569 // ambiguity; no need to actually perform overload resolution. 5570 return true; 5571 } else if (!Selected) { 5572 return false; 5573 } 5574 // In C++98, we are not supposed to perform overload resolution here, but we 5575 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5576 // cases like B as having a non-trivial copy constructor: 5577 // struct A { template<typename T> A(T&); }; 5578 // struct B { mutable A a; }; 5579 goto NeedOverloadResolution; 5580 5581 case Sema::CXXCopyAssignment: 5582 // C++11 [class.copy]p25: 5583 // A copy assignment operator is trivial if: 5584 // - the assignment operator selected to copy each direct [subobject] is 5585 // trivial 5586 if (RD->hasTrivialCopyAssignment()) { 5587 if (Quals == Qualifiers::Const) 5588 return true; 5589 } else if (!Selected) { 5590 return false; 5591 } 5592 // In C++98, we are not supposed to perform overload resolution here, but we 5593 // treat that as a language defect. 5594 goto NeedOverloadResolution; 5595 5596 case Sema::CXXMoveConstructor: 5597 case Sema::CXXMoveAssignment: 5598 NeedOverloadResolution: 5599 Sema::SpecialMemberOverloadResult *SMOR = 5600 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 5601 5602 // The standard doesn't describe how to behave if the lookup is ambiguous. 5603 // We treat it as not making the member non-trivial, just like the standard 5604 // mandates for the default constructor. This should rarely matter, because 5605 // the member will also be deleted. 5606 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5607 return true; 5608 5609 if (!SMOR->getMethod()) { 5610 assert(SMOR->getKind() == 5611 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5612 return false; 5613 } 5614 5615 // We deliberately don't check if we found a deleted special member. We're 5616 // not supposed to! 5617 if (Selected) 5618 *Selected = SMOR->getMethod(); 5619 return SMOR->getMethod()->isTrivial(); 5620 } 5621 5622 llvm_unreachable("unknown special method kind"); 5623 } 5624 5625 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5626 for (auto *CI : RD->ctors()) 5627 if (!CI->isImplicit()) 5628 return CI; 5629 5630 // Look for constructor templates. 5631 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5632 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5633 if (CXXConstructorDecl *CD = 5634 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5635 return CD; 5636 } 5637 5638 return nullptr; 5639 } 5640 5641 /// The kind of subobject we are checking for triviality. The values of this 5642 /// enumeration are used in diagnostics. 5643 enum TrivialSubobjectKind { 5644 /// The subobject is a base class. 5645 TSK_BaseClass, 5646 /// The subobject is a non-static data member. 5647 TSK_Field, 5648 /// The object is actually the complete object. 5649 TSK_CompleteObject 5650 }; 5651 5652 /// Check whether the special member selected for a given type would be trivial. 5653 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5654 QualType SubType, bool ConstRHS, 5655 Sema::CXXSpecialMember CSM, 5656 TrivialSubobjectKind Kind, 5657 bool Diagnose) { 5658 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5659 if (!SubRD) 5660 return true; 5661 5662 CXXMethodDecl *Selected; 5663 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5664 ConstRHS, Diagnose ? &Selected : nullptr)) 5665 return true; 5666 5667 if (Diagnose) { 5668 if (ConstRHS) 5669 SubType.addConst(); 5670 5671 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5672 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5673 << Kind << SubType.getUnqualifiedType(); 5674 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5675 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5676 } else if (!Selected) 5677 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5678 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5679 else if (Selected->isUserProvided()) { 5680 if (Kind == TSK_CompleteObject) 5681 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5682 << Kind << SubType.getUnqualifiedType() << CSM; 5683 else { 5684 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5685 << Kind << SubType.getUnqualifiedType() << CSM; 5686 S.Diag(Selected->getLocation(), diag::note_declared_at); 5687 } 5688 } else { 5689 if (Kind != TSK_CompleteObject) 5690 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5691 << Kind << SubType.getUnqualifiedType() << CSM; 5692 5693 // Explain why the defaulted or deleted special member isn't trivial. 5694 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5695 } 5696 } 5697 5698 return false; 5699 } 5700 5701 /// Check whether the members of a class type allow a special member to be 5702 /// trivial. 5703 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5704 Sema::CXXSpecialMember CSM, 5705 bool ConstArg, bool Diagnose) { 5706 for (const auto *FI : RD->fields()) { 5707 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5708 continue; 5709 5710 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5711 5712 // Pretend anonymous struct or union members are members of this class. 5713 if (FI->isAnonymousStructOrUnion()) { 5714 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5715 CSM, ConstArg, Diagnose)) 5716 return false; 5717 continue; 5718 } 5719 5720 // C++11 [class.ctor]p5: 5721 // A default constructor is trivial if [...] 5722 // -- no non-static data member of its class has a 5723 // brace-or-equal-initializer 5724 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5725 if (Diagnose) 5726 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 5727 return false; 5728 } 5729 5730 // Objective C ARC 4.3.5: 5731 // [...] nontrivally ownership-qualified types are [...] not trivially 5732 // default constructible, copy constructible, move constructible, copy 5733 // assignable, move assignable, or destructible [...] 5734 if (S.getLangOpts().ObjCAutoRefCount && 5735 FieldType.hasNonTrivialObjCLifetime()) { 5736 if (Diagnose) 5737 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5738 << RD << FieldType.getObjCLifetime(); 5739 return false; 5740 } 5741 5742 bool ConstRHS = ConstArg && !FI->isMutable(); 5743 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 5744 CSM, TSK_Field, Diagnose)) 5745 return false; 5746 } 5747 5748 return true; 5749 } 5750 5751 /// Diagnose why the specified class does not have a trivial special member of 5752 /// the given kind. 5753 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5754 QualType Ty = Context.getRecordType(RD); 5755 5756 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 5757 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 5758 TSK_CompleteObject, /*Diagnose*/true); 5759 } 5760 5761 /// Determine whether a defaulted or deleted special member function is trivial, 5762 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5763 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5764 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5765 bool Diagnose) { 5766 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5767 5768 CXXRecordDecl *RD = MD->getParent(); 5769 5770 bool ConstArg = false; 5771 5772 // C++11 [class.copy]p12, p25: [DR1593] 5773 // A [special member] is trivial if [...] its parameter-type-list is 5774 // equivalent to the parameter-type-list of an implicit declaration [...] 5775 switch (CSM) { 5776 case CXXDefaultConstructor: 5777 case CXXDestructor: 5778 // Trivial default constructors and destructors cannot have parameters. 5779 break; 5780 5781 case CXXCopyConstructor: 5782 case CXXCopyAssignment: { 5783 // Trivial copy operations always have const, non-volatile parameter types. 5784 ConstArg = true; 5785 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5786 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5787 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5788 if (Diagnose) 5789 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5790 << Param0->getSourceRange() << Param0->getType() 5791 << Context.getLValueReferenceType( 5792 Context.getRecordType(RD).withConst()); 5793 return false; 5794 } 5795 break; 5796 } 5797 5798 case CXXMoveConstructor: 5799 case CXXMoveAssignment: { 5800 // Trivial move operations always have non-cv-qualified parameters. 5801 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5802 const RValueReferenceType *RT = 5803 Param0->getType()->getAs<RValueReferenceType>(); 5804 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5805 if (Diagnose) 5806 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5807 << Param0->getSourceRange() << Param0->getType() 5808 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5809 return false; 5810 } 5811 break; 5812 } 5813 5814 case CXXInvalid: 5815 llvm_unreachable("not a special member"); 5816 } 5817 5818 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5819 if (Diagnose) 5820 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5821 diag::note_nontrivial_default_arg) 5822 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5823 return false; 5824 } 5825 if (MD->isVariadic()) { 5826 if (Diagnose) 5827 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5828 return false; 5829 } 5830 5831 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5832 // A copy/move [constructor or assignment operator] is trivial if 5833 // -- the [member] selected to copy/move each direct base class subobject 5834 // is trivial 5835 // 5836 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5837 // A [default constructor or destructor] is trivial if 5838 // -- all the direct base classes have trivial [default constructors or 5839 // destructors] 5840 for (const auto &BI : RD->bases()) 5841 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 5842 ConstArg, CSM, TSK_BaseClass, Diagnose)) 5843 return false; 5844 5845 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5846 // A copy/move [constructor or assignment operator] for a class X is 5847 // trivial if 5848 // -- for each non-static data member of X that is of class type (or array 5849 // thereof), the constructor selected to copy/move that member is 5850 // trivial 5851 // 5852 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5853 // A [default constructor or destructor] is trivial if 5854 // -- for all of the non-static data members of its class that are of class 5855 // type (or array thereof), each such class has a trivial [default 5856 // constructor or destructor] 5857 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5858 return false; 5859 5860 // C++11 [class.dtor]p5: 5861 // A destructor is trivial if [...] 5862 // -- the destructor is not virtual 5863 if (CSM == CXXDestructor && MD->isVirtual()) { 5864 if (Diagnose) 5865 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5866 return false; 5867 } 5868 5869 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5870 // A [special member] for class X is trivial if [...] 5871 // -- class X has no virtual functions and no virtual base classes 5872 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5873 if (!Diagnose) 5874 return false; 5875 5876 if (RD->getNumVBases()) { 5877 // Check for virtual bases. We already know that the corresponding 5878 // member in all bases is trivial, so vbases must all be direct. 5879 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5880 assert(BS.isVirtual()); 5881 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5882 return false; 5883 } 5884 5885 // Must have a virtual method. 5886 for (const auto *MI : RD->methods()) { 5887 if (MI->isVirtual()) { 5888 SourceLocation MLoc = MI->getLocStart(); 5889 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5890 return false; 5891 } 5892 } 5893 5894 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5895 } 5896 5897 // Looks like it's trivial! 5898 return true; 5899 } 5900 5901 /// \brief Data used with FindHiddenVirtualMethod 5902 namespace { 5903 struct FindHiddenVirtualMethodData { 5904 Sema *S; 5905 CXXMethodDecl *Method; 5906 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5907 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5908 }; 5909 } 5910 5911 /// \brief Check whether any most overriden method from MD in Methods 5912 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 5913 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5914 if (MD->size_overridden_methods() == 0) 5915 return Methods.count(MD->getCanonicalDecl()); 5916 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5917 E = MD->end_overridden_methods(); 5918 I != E; ++I) 5919 if (CheckMostOverridenMethods(*I, Methods)) 5920 return true; 5921 return false; 5922 } 5923 5924 /// \brief Member lookup function that determines whether a given C++ 5925 /// method overloads virtual methods in a base class without overriding any, 5926 /// to be used with CXXRecordDecl::lookupInBases(). 5927 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 5928 CXXBasePath &Path, 5929 void *UserData) { 5930 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5931 5932 FindHiddenVirtualMethodData &Data 5933 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 5934 5935 DeclarationName Name = Data.Method->getDeclName(); 5936 assert(Name.getNameKind() == DeclarationName::Identifier); 5937 5938 bool foundSameNameMethod = false; 5939 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 5940 for (Path.Decls = BaseRecord->lookup(Name); 5941 !Path.Decls.empty(); 5942 Path.Decls = Path.Decls.slice(1)) { 5943 NamedDecl *D = Path.Decls.front(); 5944 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5945 MD = MD->getCanonicalDecl(); 5946 foundSameNameMethod = true; 5947 // Interested only in hidden virtual methods. 5948 if (!MD->isVirtual()) 5949 continue; 5950 // If the method we are checking overrides a method from its base 5951 // don't warn about the other overloaded methods. Clang deviates from GCC 5952 // by only diagnosing overloads of inherited virtual functions that do not 5953 // override any other virtual functions in the base. GCC's 5954 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 5955 // function from a base class. These cases may be better served by a 5956 // warning (not specific to virtual functions) on call sites when the call 5957 // would select a different function from the base class, were it visible. 5958 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 5959 if (!Data.S->IsOverload(Data.Method, MD, false)) 5960 return true; 5961 // Collect the overload only if its hidden. 5962 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 5963 overloadedMethods.push_back(MD); 5964 } 5965 } 5966 5967 if (foundSameNameMethod) 5968 Data.OverloadedMethods.append(overloadedMethods.begin(), 5969 overloadedMethods.end()); 5970 return foundSameNameMethod; 5971 } 5972 5973 /// \brief Add the most overriden methods from MD to Methods 5974 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 5975 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5976 if (MD->size_overridden_methods() == 0) 5977 Methods.insert(MD->getCanonicalDecl()); 5978 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5979 E = MD->end_overridden_methods(); 5980 I != E; ++I) 5981 AddMostOverridenMethods(*I, Methods); 5982 } 5983 5984 /// \brief Check if a method overloads virtual methods in a base class without 5985 /// overriding any. 5986 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 5987 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 5988 if (!MD->getDeclName().isIdentifier()) 5989 return; 5990 5991 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5992 /*bool RecordPaths=*/false, 5993 /*bool DetectVirtual=*/false); 5994 FindHiddenVirtualMethodData Data; 5995 Data.Method = MD; 5996 Data.S = this; 5997 5998 // Keep the base methods that were overriden or introduced in the subclass 5999 // by 'using' in a set. A base method not in this set is hidden. 6000 CXXRecordDecl *DC = MD->getParent(); 6001 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 6002 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 6003 NamedDecl *ND = *I; 6004 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 6005 ND = shad->getTargetDecl(); 6006 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6007 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 6008 } 6009 6010 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths)) 6011 OverloadedMethods = Data.OverloadedMethods; 6012 } 6013 6014 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 6015 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6016 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 6017 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 6018 PartialDiagnostic PD = PDiag( 6019 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 6020 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 6021 Diag(overloadedMD->getLocation(), PD); 6022 } 6023 } 6024 6025 /// \brief Diagnose methods which overload virtual methods in a base class 6026 /// without overriding any. 6027 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 6028 if (MD->isInvalidDecl()) 6029 return; 6030 6031 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 6032 return; 6033 6034 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6035 FindHiddenVirtualMethods(MD, OverloadedMethods); 6036 if (!OverloadedMethods.empty()) { 6037 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 6038 << MD << (OverloadedMethods.size() > 1); 6039 6040 NoteHiddenVirtualMethods(MD, OverloadedMethods); 6041 } 6042 } 6043 6044 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 6045 Decl *TagDecl, 6046 SourceLocation LBrac, 6047 SourceLocation RBrac, 6048 AttributeList *AttrList) { 6049 if (!TagDecl) 6050 return; 6051 6052 AdjustDeclIfTemplate(TagDecl); 6053 6054 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 6055 if (l->getKind() != AttributeList::AT_Visibility) 6056 continue; 6057 l->setInvalid(); 6058 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 6059 l->getName(); 6060 } 6061 6062 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 6063 // strict aliasing violation! 6064 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 6065 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 6066 6067 CheckCompletedCXXClass( 6068 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 6069 } 6070 6071 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 6072 /// special functions, such as the default constructor, copy 6073 /// constructor, or destructor, to the given C++ class (C++ 6074 /// [special]p1). This routine can only be executed just before the 6075 /// definition of the class is complete. 6076 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 6077 if (!ClassDecl->hasUserDeclaredConstructor()) 6078 ++ASTContext::NumImplicitDefaultConstructors; 6079 6080 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 6081 ++ASTContext::NumImplicitCopyConstructors; 6082 6083 // If the properties or semantics of the copy constructor couldn't be 6084 // determined while the class was being declared, force a declaration 6085 // of it now. 6086 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 6087 DeclareImplicitCopyConstructor(ClassDecl); 6088 } 6089 6090 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 6091 ++ASTContext::NumImplicitMoveConstructors; 6092 6093 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 6094 DeclareImplicitMoveConstructor(ClassDecl); 6095 } 6096 6097 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 6098 ++ASTContext::NumImplicitCopyAssignmentOperators; 6099 6100 // If we have a dynamic class, then the copy assignment operator may be 6101 // virtual, so we have to declare it immediately. This ensures that, e.g., 6102 // it shows up in the right place in the vtable and that we diagnose 6103 // problems with the implicit exception specification. 6104 if (ClassDecl->isDynamicClass() || 6105 ClassDecl->needsOverloadResolutionForCopyAssignment()) 6106 DeclareImplicitCopyAssignment(ClassDecl); 6107 } 6108 6109 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 6110 ++ASTContext::NumImplicitMoveAssignmentOperators; 6111 6112 // Likewise for the move assignment operator. 6113 if (ClassDecl->isDynamicClass() || 6114 ClassDecl->needsOverloadResolutionForMoveAssignment()) 6115 DeclareImplicitMoveAssignment(ClassDecl); 6116 } 6117 6118 if (!ClassDecl->hasUserDeclaredDestructor()) { 6119 ++ASTContext::NumImplicitDestructors; 6120 6121 // If we have a dynamic class, then the destructor may be virtual, so we 6122 // have to declare the destructor immediately. This ensures that, e.g., it 6123 // shows up in the right place in the vtable and that we diagnose problems 6124 // with the implicit exception specification. 6125 if (ClassDecl->isDynamicClass() || 6126 ClassDecl->needsOverloadResolutionForDestructor()) 6127 DeclareImplicitDestructor(ClassDecl); 6128 } 6129 } 6130 6131 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 6132 if (!D) 6133 return 0; 6134 6135 // The order of template parameters is not important here. All names 6136 // get added to the same scope. 6137 SmallVector<TemplateParameterList *, 4> ParameterLists; 6138 6139 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 6140 D = TD->getTemplatedDecl(); 6141 6142 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6143 ParameterLists.push_back(PSD->getTemplateParameters()); 6144 6145 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 6146 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 6147 ParameterLists.push_back(DD->getTemplateParameterList(i)); 6148 6149 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6150 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 6151 ParameterLists.push_back(FTD->getTemplateParameters()); 6152 } 6153 } 6154 6155 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 6156 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 6157 ParameterLists.push_back(TD->getTemplateParameterList(i)); 6158 6159 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 6160 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 6161 ParameterLists.push_back(CTD->getTemplateParameters()); 6162 } 6163 } 6164 6165 unsigned Count = 0; 6166 for (TemplateParameterList *Params : ParameterLists) { 6167 if (Params->size() > 0) 6168 // Ignore explicit specializations; they don't contribute to the template 6169 // depth. 6170 ++Count; 6171 for (NamedDecl *Param : *Params) { 6172 if (Param->getDeclName()) { 6173 S->AddDecl(Param); 6174 IdResolver.AddDecl(Param); 6175 } 6176 } 6177 } 6178 6179 return Count; 6180 } 6181 6182 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6183 if (!RecordD) return; 6184 AdjustDeclIfTemplate(RecordD); 6185 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6186 PushDeclContext(S, Record); 6187 } 6188 6189 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6190 if (!RecordD) return; 6191 PopDeclContext(); 6192 } 6193 6194 /// This is used to implement the constant expression evaluation part of the 6195 /// attribute enable_if extension. There is nothing in standard C++ which would 6196 /// require reentering parameters. 6197 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 6198 if (!Param) 6199 return; 6200 6201 S->AddDecl(Param); 6202 if (Param->getDeclName()) 6203 IdResolver.AddDecl(Param); 6204 } 6205 6206 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 6207 /// parsing a top-level (non-nested) C++ class, and we are now 6208 /// parsing those parts of the given Method declaration that could 6209 /// not be parsed earlier (C++ [class.mem]p2), such as default 6210 /// arguments. This action should enter the scope of the given 6211 /// Method declaration as if we had just parsed the qualified method 6212 /// name. However, it should not bring the parameters into scope; 6213 /// that will be performed by ActOnDelayedCXXMethodParameter. 6214 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6215 } 6216 6217 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 6218 /// C++ method declaration. We're (re-)introducing the given 6219 /// function parameter into scope for use in parsing later parts of 6220 /// the method declaration. For example, we could see an 6221 /// ActOnParamDefaultArgument event for this parameter. 6222 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6223 if (!ParamD) 6224 return; 6225 6226 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6227 6228 // If this parameter has an unparsed default argument, clear it out 6229 // to make way for the parsed default argument. 6230 if (Param->hasUnparsedDefaultArg()) 6231 Param->setDefaultArg(nullptr); 6232 6233 S->AddDecl(Param); 6234 if (Param->getDeclName()) 6235 IdResolver.AddDecl(Param); 6236 } 6237 6238 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6239 /// processing the delayed method declaration for Method. The method 6240 /// declaration is now considered finished. There may be a separate 6241 /// ActOnStartOfFunctionDef action later (not necessarily 6242 /// immediately!) for this method, if it was also defined inside the 6243 /// class body. 6244 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6245 if (!MethodD) 6246 return; 6247 6248 AdjustDeclIfTemplate(MethodD); 6249 6250 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6251 6252 // Now that we have our default arguments, check the constructor 6253 // again. It could produce additional diagnostics or affect whether 6254 // the class has implicitly-declared destructors, among other 6255 // things. 6256 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6257 CheckConstructor(Constructor); 6258 6259 // Check the default arguments, which we may have added. 6260 if (!Method->isInvalidDecl()) 6261 CheckCXXDefaultArguments(Method); 6262 } 6263 6264 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6265 /// the well-formedness of the constructor declarator @p D with type @p 6266 /// R. If there are any errors in the declarator, this routine will 6267 /// emit diagnostics and set the invalid bit to true. In any case, the type 6268 /// will be updated to reflect a well-formed type for the constructor and 6269 /// returned. 6270 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6271 StorageClass &SC) { 6272 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6273 6274 // C++ [class.ctor]p3: 6275 // A constructor shall not be virtual (10.3) or static (9.4). A 6276 // constructor can be invoked for a const, volatile or const 6277 // volatile object. A constructor shall not be declared const, 6278 // volatile, or const volatile (9.3.2). 6279 if (isVirtual) { 6280 if (!D.isInvalidType()) 6281 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6282 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6283 << SourceRange(D.getIdentifierLoc()); 6284 D.setInvalidType(); 6285 } 6286 if (SC == SC_Static) { 6287 if (!D.isInvalidType()) 6288 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6289 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6290 << SourceRange(D.getIdentifierLoc()); 6291 D.setInvalidType(); 6292 SC = SC_None; 6293 } 6294 6295 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6296 diagnoseIgnoredQualifiers( 6297 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 6298 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 6299 D.getDeclSpec().getRestrictSpecLoc(), 6300 D.getDeclSpec().getAtomicSpecLoc()); 6301 D.setInvalidType(); 6302 } 6303 6304 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6305 if (FTI.TypeQuals != 0) { 6306 if (FTI.TypeQuals & Qualifiers::Const) 6307 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6308 << "const" << SourceRange(D.getIdentifierLoc()); 6309 if (FTI.TypeQuals & Qualifiers::Volatile) 6310 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6311 << "volatile" << SourceRange(D.getIdentifierLoc()); 6312 if (FTI.TypeQuals & Qualifiers::Restrict) 6313 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6314 << "restrict" << SourceRange(D.getIdentifierLoc()); 6315 D.setInvalidType(); 6316 } 6317 6318 // C++0x [class.ctor]p4: 6319 // A constructor shall not be declared with a ref-qualifier. 6320 if (FTI.hasRefQualifier()) { 6321 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6322 << FTI.RefQualifierIsLValueRef 6323 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6324 D.setInvalidType(); 6325 } 6326 6327 // Rebuild the function type "R" without any type qualifiers (in 6328 // case any of the errors above fired) and with "void" as the 6329 // return type, since constructors don't have return types. 6330 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6331 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 6332 return R; 6333 6334 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6335 EPI.TypeQuals = 0; 6336 EPI.RefQualifier = RQ_None; 6337 6338 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 6339 } 6340 6341 /// CheckConstructor - Checks a fully-formed constructor for 6342 /// well-formedness, issuing any diagnostics required. Returns true if 6343 /// the constructor declarator is invalid. 6344 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6345 CXXRecordDecl *ClassDecl 6346 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6347 if (!ClassDecl) 6348 return Constructor->setInvalidDecl(); 6349 6350 // C++ [class.copy]p3: 6351 // A declaration of a constructor for a class X is ill-formed if 6352 // its first parameter is of type (optionally cv-qualified) X and 6353 // either there are no other parameters or else all other 6354 // parameters have default arguments. 6355 if (!Constructor->isInvalidDecl() && 6356 ((Constructor->getNumParams() == 1) || 6357 (Constructor->getNumParams() > 1 && 6358 Constructor->getParamDecl(1)->hasDefaultArg())) && 6359 Constructor->getTemplateSpecializationKind() 6360 != TSK_ImplicitInstantiation) { 6361 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6362 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6363 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6364 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6365 const char *ConstRef 6366 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6367 : " const &"; 6368 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6369 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6370 6371 // FIXME: Rather that making the constructor invalid, we should endeavor 6372 // to fix the type. 6373 Constructor->setInvalidDecl(); 6374 } 6375 } 6376 } 6377 6378 /// CheckDestructor - Checks a fully-formed destructor definition for 6379 /// well-formedness, issuing any diagnostics required. Returns true 6380 /// on error. 6381 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6382 CXXRecordDecl *RD = Destructor->getParent(); 6383 6384 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6385 SourceLocation Loc; 6386 6387 if (!Destructor->isImplicit()) 6388 Loc = Destructor->getLocation(); 6389 else 6390 Loc = RD->getLocation(); 6391 6392 // If we have a virtual destructor, look up the deallocation function 6393 FunctionDecl *OperatorDelete = nullptr; 6394 DeclarationName Name = 6395 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6396 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6397 return true; 6398 // If there's no class-specific operator delete, look up the global 6399 // non-array delete. 6400 if (!OperatorDelete) 6401 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name); 6402 6403 MarkFunctionReferenced(Loc, OperatorDelete); 6404 6405 Destructor->setOperatorDelete(OperatorDelete); 6406 } 6407 6408 return false; 6409 } 6410 6411 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6412 /// the well-formednes of the destructor declarator @p D with type @p 6413 /// R. If there are any errors in the declarator, this routine will 6414 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6415 /// will be updated to reflect a well-formed type for the destructor and 6416 /// returned. 6417 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6418 StorageClass& SC) { 6419 // C++ [class.dtor]p1: 6420 // [...] A typedef-name that names a class is a class-name 6421 // (7.1.3); however, a typedef-name that names a class shall not 6422 // be used as the identifier in the declarator for a destructor 6423 // declaration. 6424 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6425 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6426 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6427 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6428 else if (const TemplateSpecializationType *TST = 6429 DeclaratorType->getAs<TemplateSpecializationType>()) 6430 if (TST->isTypeAlias()) 6431 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6432 << DeclaratorType << 1; 6433 6434 // C++ [class.dtor]p2: 6435 // A destructor is used to destroy objects of its class type. A 6436 // destructor takes no parameters, and no return type can be 6437 // specified for it (not even void). The address of a destructor 6438 // shall not be taken. A destructor shall not be static. A 6439 // destructor can be invoked for a const, volatile or const 6440 // volatile object. A destructor shall not be declared const, 6441 // volatile or const volatile (9.3.2). 6442 if (SC == SC_Static) { 6443 if (!D.isInvalidType()) 6444 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6445 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6446 << SourceRange(D.getIdentifierLoc()) 6447 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6448 6449 SC = SC_None; 6450 } 6451 if (!D.isInvalidType()) { 6452 // Destructors don't have return types, but the parser will 6453 // happily parse something like: 6454 // 6455 // class X { 6456 // float ~X(); 6457 // }; 6458 // 6459 // The return type will be eliminated later. 6460 if (D.getDeclSpec().hasTypeSpecifier()) 6461 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6462 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6463 << SourceRange(D.getIdentifierLoc()); 6464 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6465 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 6466 SourceLocation(), 6467 D.getDeclSpec().getConstSpecLoc(), 6468 D.getDeclSpec().getVolatileSpecLoc(), 6469 D.getDeclSpec().getRestrictSpecLoc(), 6470 D.getDeclSpec().getAtomicSpecLoc()); 6471 D.setInvalidType(); 6472 } 6473 } 6474 6475 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6476 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6477 if (FTI.TypeQuals & Qualifiers::Const) 6478 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6479 << "const" << SourceRange(D.getIdentifierLoc()); 6480 if (FTI.TypeQuals & Qualifiers::Volatile) 6481 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6482 << "volatile" << SourceRange(D.getIdentifierLoc()); 6483 if (FTI.TypeQuals & Qualifiers::Restrict) 6484 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6485 << "restrict" << SourceRange(D.getIdentifierLoc()); 6486 D.setInvalidType(); 6487 } 6488 6489 // C++0x [class.dtor]p2: 6490 // A destructor shall not be declared with a ref-qualifier. 6491 if (FTI.hasRefQualifier()) { 6492 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6493 << FTI.RefQualifierIsLValueRef 6494 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6495 D.setInvalidType(); 6496 } 6497 6498 // Make sure we don't have any parameters. 6499 if (FTIHasNonVoidParameters(FTI)) { 6500 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6501 6502 // Delete the parameters. 6503 FTI.freeParams(); 6504 D.setInvalidType(); 6505 } 6506 6507 // Make sure the destructor isn't variadic. 6508 if (FTI.isVariadic) { 6509 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6510 D.setInvalidType(); 6511 } 6512 6513 // Rebuild the function type "R" without any type qualifiers or 6514 // parameters (in case any of the errors above fired) and with 6515 // "void" as the return type, since destructors don't have return 6516 // types. 6517 if (!D.isInvalidType()) 6518 return R; 6519 6520 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6521 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6522 EPI.Variadic = false; 6523 EPI.TypeQuals = 0; 6524 EPI.RefQualifier = RQ_None; 6525 return Context.getFunctionType(Context.VoidTy, None, EPI); 6526 } 6527 6528 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6529 /// well-formednes of the conversion function declarator @p D with 6530 /// type @p R. If there are any errors in the declarator, this routine 6531 /// will emit diagnostics and return true. Otherwise, it will return 6532 /// false. Either way, the type @p R will be updated to reflect a 6533 /// well-formed type for the conversion operator. 6534 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6535 StorageClass& SC) { 6536 // C++ [class.conv.fct]p1: 6537 // Neither parameter types nor return type can be specified. The 6538 // type of a conversion function (8.3.5) is "function taking no 6539 // parameter returning conversion-type-id." 6540 if (SC == SC_Static) { 6541 if (!D.isInvalidType()) 6542 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6543 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6544 << D.getName().getSourceRange(); 6545 D.setInvalidType(); 6546 SC = SC_None; 6547 } 6548 6549 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 6550 6551 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6552 // Conversion functions don't have return types, but the parser will 6553 // happily parse something like: 6554 // 6555 // class X { 6556 // float operator bool(); 6557 // }; 6558 // 6559 // The return type will be changed later anyway. 6560 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6561 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6562 << SourceRange(D.getIdentifierLoc()); 6563 D.setInvalidType(); 6564 } 6565 6566 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6567 6568 // Make sure we don't have any parameters. 6569 if (Proto->getNumParams() > 0) { 6570 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6571 6572 // Delete the parameters. 6573 D.getFunctionTypeInfo().freeParams(); 6574 D.setInvalidType(); 6575 } else if (Proto->isVariadic()) { 6576 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6577 D.setInvalidType(); 6578 } 6579 6580 // Diagnose "&operator bool()" and other such nonsense. This 6581 // is actually a gcc extension which we don't support. 6582 if (Proto->getReturnType() != ConvType) { 6583 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 6584 << Proto->getReturnType(); 6585 D.setInvalidType(); 6586 ConvType = Proto->getReturnType(); 6587 } 6588 6589 // C++ [class.conv.fct]p4: 6590 // The conversion-type-id shall not represent a function type nor 6591 // an array type. 6592 if (ConvType->isArrayType()) { 6593 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 6594 ConvType = Context.getPointerType(ConvType); 6595 D.setInvalidType(); 6596 } else if (ConvType->isFunctionType()) { 6597 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 6598 ConvType = Context.getPointerType(ConvType); 6599 D.setInvalidType(); 6600 } 6601 6602 // Rebuild the function type "R" without any parameters (in case any 6603 // of the errors above fired) and with the conversion type as the 6604 // return type. 6605 if (D.isInvalidType()) 6606 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 6607 6608 // C++0x explicit conversion operators. 6609 if (D.getDeclSpec().isExplicitSpecified()) 6610 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6611 getLangOpts().CPlusPlus11 ? 6612 diag::warn_cxx98_compat_explicit_conversion_functions : 6613 diag::ext_explicit_conversion_functions) 6614 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 6615 } 6616 6617 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 6618 /// the declaration of the given C++ conversion function. This routine 6619 /// is responsible for recording the conversion function in the C++ 6620 /// class, if possible. 6621 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 6622 assert(Conversion && "Expected to receive a conversion function declaration"); 6623 6624 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 6625 6626 // Make sure we aren't redeclaring the conversion function. 6627 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 6628 6629 // C++ [class.conv.fct]p1: 6630 // [...] A conversion function is never used to convert a 6631 // (possibly cv-qualified) object to the (possibly cv-qualified) 6632 // same object type (or a reference to it), to a (possibly 6633 // cv-qualified) base class of that type (or a reference to it), 6634 // or to (possibly cv-qualified) void. 6635 // FIXME: Suppress this warning if the conversion function ends up being a 6636 // virtual function that overrides a virtual function in a base class. 6637 QualType ClassType 6638 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6639 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 6640 ConvType = ConvTypeRef->getPointeeType(); 6641 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6642 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6643 /* Suppress diagnostics for instantiations. */; 6644 else if (ConvType->isRecordType()) { 6645 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6646 if (ConvType == ClassType) 6647 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6648 << ClassType; 6649 else if (IsDerivedFrom(ClassType, ConvType)) 6650 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6651 << ClassType << ConvType; 6652 } else if (ConvType->isVoidType()) { 6653 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6654 << ClassType << ConvType; 6655 } 6656 6657 if (FunctionTemplateDecl *ConversionTemplate 6658 = Conversion->getDescribedFunctionTemplate()) 6659 return ConversionTemplate; 6660 6661 return Conversion; 6662 } 6663 6664 //===----------------------------------------------------------------------===// 6665 // Namespace Handling 6666 //===----------------------------------------------------------------------===// 6667 6668 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6669 /// reopened. 6670 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6671 SourceLocation Loc, 6672 IdentifierInfo *II, bool *IsInline, 6673 NamespaceDecl *PrevNS) { 6674 assert(*IsInline != PrevNS->isInline()); 6675 6676 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6677 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6678 // inline namespaces, with the intention of bringing names into namespace std. 6679 // 6680 // We support this just well enough to get that case working; this is not 6681 // sufficient to support reopening namespaces as inline in general. 6682 if (*IsInline && II && II->getName().startswith("__atomic") && 6683 S.getSourceManager().isInSystemHeader(Loc)) { 6684 // Mark all prior declarations of the namespace as inline. 6685 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6686 NS = NS->getPreviousDecl()) 6687 NS->setInline(*IsInline); 6688 // Patch up the lookup table for the containing namespace. This isn't really 6689 // correct, but it's good enough for this particular case. 6690 for (auto *I : PrevNS->decls()) 6691 if (auto *ND = dyn_cast<NamedDecl>(I)) 6692 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6693 return; 6694 } 6695 6696 if (PrevNS->isInline()) 6697 // The user probably just forgot the 'inline', so suggest that it 6698 // be added back. 6699 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6700 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6701 else 6702 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline; 6703 6704 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6705 *IsInline = PrevNS->isInline(); 6706 } 6707 6708 /// ActOnStartNamespaceDef - This is called at the start of a namespace 6709 /// definition. 6710 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6711 SourceLocation InlineLoc, 6712 SourceLocation NamespaceLoc, 6713 SourceLocation IdentLoc, 6714 IdentifierInfo *II, 6715 SourceLocation LBrace, 6716 AttributeList *AttrList) { 6717 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6718 // For anonymous namespace, take the location of the left brace. 6719 SourceLocation Loc = II ? IdentLoc : LBrace; 6720 bool IsInline = InlineLoc.isValid(); 6721 bool IsInvalid = false; 6722 bool IsStd = false; 6723 bool AddToKnown = false; 6724 Scope *DeclRegionScope = NamespcScope->getParent(); 6725 6726 NamespaceDecl *PrevNS = nullptr; 6727 if (II) { 6728 // C++ [namespace.def]p2: 6729 // The identifier in an original-namespace-definition shall not 6730 // have been previously defined in the declarative region in 6731 // which the original-namespace-definition appears. The 6732 // identifier in an original-namespace-definition is the name of 6733 // the namespace. Subsequently in that declarative region, it is 6734 // treated as an original-namespace-name. 6735 // 6736 // Since namespace names are unique in their scope, and we don't 6737 // look through using directives, just look for any ordinary names. 6738 6739 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6740 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6741 Decl::IDNS_Namespace; 6742 NamedDecl *PrevDecl = nullptr; 6743 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6744 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6745 ++I) { 6746 if ((*I)->getIdentifierNamespace() & IDNS) { 6747 PrevDecl = *I; 6748 break; 6749 } 6750 } 6751 6752 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6753 6754 if (PrevNS) { 6755 // This is an extended namespace definition. 6756 if (IsInline != PrevNS->isInline()) 6757 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6758 &IsInline, PrevNS); 6759 } else if (PrevDecl) { 6760 // This is an invalid name redefinition. 6761 Diag(Loc, diag::err_redefinition_different_kind) 6762 << II; 6763 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6764 IsInvalid = true; 6765 // Continue on to push Namespc as current DeclContext and return it. 6766 } else if (II->isStr("std") && 6767 CurContext->getRedeclContext()->isTranslationUnit()) { 6768 // This is the first "real" definition of the namespace "std", so update 6769 // our cache of the "std" namespace to point at this definition. 6770 PrevNS = getStdNamespace(); 6771 IsStd = true; 6772 AddToKnown = !IsInline; 6773 } else { 6774 // We've seen this namespace for the first time. 6775 AddToKnown = !IsInline; 6776 } 6777 } else { 6778 // Anonymous namespaces. 6779 6780 // Determine whether the parent already has an anonymous namespace. 6781 DeclContext *Parent = CurContext->getRedeclContext(); 6782 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6783 PrevNS = TU->getAnonymousNamespace(); 6784 } else { 6785 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6786 PrevNS = ND->getAnonymousNamespace(); 6787 } 6788 6789 if (PrevNS && IsInline != PrevNS->isInline()) 6790 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6791 &IsInline, PrevNS); 6792 } 6793 6794 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6795 StartLoc, Loc, II, PrevNS); 6796 if (IsInvalid) 6797 Namespc->setInvalidDecl(); 6798 6799 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6800 6801 // FIXME: Should we be merging attributes? 6802 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6803 PushNamespaceVisibilityAttr(Attr, Loc); 6804 6805 if (IsStd) 6806 StdNamespace = Namespc; 6807 if (AddToKnown) 6808 KnownNamespaces[Namespc] = false; 6809 6810 if (II) { 6811 PushOnScopeChains(Namespc, DeclRegionScope); 6812 } else { 6813 // Link the anonymous namespace into its parent. 6814 DeclContext *Parent = CurContext->getRedeclContext(); 6815 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6816 TU->setAnonymousNamespace(Namespc); 6817 } else { 6818 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6819 } 6820 6821 CurContext->addDecl(Namespc); 6822 6823 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6824 // behaves as if it were replaced by 6825 // namespace unique { /* empty body */ } 6826 // using namespace unique; 6827 // namespace unique { namespace-body } 6828 // where all occurrences of 'unique' in a translation unit are 6829 // replaced by the same identifier and this identifier differs 6830 // from all other identifiers in the entire program. 6831 6832 // We just create the namespace with an empty name and then add an 6833 // implicit using declaration, just like the standard suggests. 6834 // 6835 // CodeGen enforces the "universally unique" aspect by giving all 6836 // declarations semantically contained within an anonymous 6837 // namespace internal linkage. 6838 6839 if (!PrevNS) { 6840 UsingDirectiveDecl* UD 6841 = UsingDirectiveDecl::Create(Context, Parent, 6842 /* 'using' */ LBrace, 6843 /* 'namespace' */ SourceLocation(), 6844 /* qualifier */ NestedNameSpecifierLoc(), 6845 /* identifier */ SourceLocation(), 6846 Namespc, 6847 /* Ancestor */ Parent); 6848 UD->setImplicit(); 6849 Parent->addDecl(UD); 6850 } 6851 } 6852 6853 ActOnDocumentableDecl(Namespc); 6854 6855 // Although we could have an invalid decl (i.e. the namespace name is a 6856 // redefinition), push it as current DeclContext and try to continue parsing. 6857 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6858 // for the namespace has the declarations that showed up in that particular 6859 // namespace definition. 6860 PushDeclContext(NamespcScope, Namespc); 6861 return Namespc; 6862 } 6863 6864 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6865 /// is a namespace alias, returns the namespace it points to. 6866 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6867 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6868 return AD->getNamespace(); 6869 return dyn_cast_or_null<NamespaceDecl>(D); 6870 } 6871 6872 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 6873 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6874 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6875 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6876 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6877 Namespc->setRBraceLoc(RBrace); 6878 PopDeclContext(); 6879 if (Namespc->hasAttr<VisibilityAttr>()) 6880 PopPragmaVisibility(true, RBrace); 6881 } 6882 6883 CXXRecordDecl *Sema::getStdBadAlloc() const { 6884 return cast_or_null<CXXRecordDecl>( 6885 StdBadAlloc.get(Context.getExternalSource())); 6886 } 6887 6888 NamespaceDecl *Sema::getStdNamespace() const { 6889 return cast_or_null<NamespaceDecl>( 6890 StdNamespace.get(Context.getExternalSource())); 6891 } 6892 6893 /// \brief Retrieve the special "std" namespace, which may require us to 6894 /// implicitly define the namespace. 6895 NamespaceDecl *Sema::getOrCreateStdNamespace() { 6896 if (!StdNamespace) { 6897 // The "std" namespace has not yet been defined, so build one implicitly. 6898 StdNamespace = NamespaceDecl::Create(Context, 6899 Context.getTranslationUnitDecl(), 6900 /*Inline=*/false, 6901 SourceLocation(), SourceLocation(), 6902 &PP.getIdentifierTable().get("std"), 6903 /*PrevDecl=*/nullptr); 6904 getStdNamespace()->setImplicit(true); 6905 } 6906 6907 return getStdNamespace(); 6908 } 6909 6910 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6911 assert(getLangOpts().CPlusPlus && 6912 "Looking for std::initializer_list outside of C++."); 6913 6914 // We're looking for implicit instantiations of 6915 // template <typename E> class std::initializer_list. 6916 6917 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 6918 return false; 6919 6920 ClassTemplateDecl *Template = nullptr; 6921 const TemplateArgument *Arguments = nullptr; 6922 6923 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6924 6925 ClassTemplateSpecializationDecl *Specialization = 6926 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6927 if (!Specialization) 6928 return false; 6929 6930 Template = Specialization->getSpecializedTemplate(); 6931 Arguments = Specialization->getTemplateArgs().data(); 6932 } else if (const TemplateSpecializationType *TST = 6933 Ty->getAs<TemplateSpecializationType>()) { 6934 Template = dyn_cast_or_null<ClassTemplateDecl>( 6935 TST->getTemplateName().getAsTemplateDecl()); 6936 Arguments = TST->getArgs(); 6937 } 6938 if (!Template) 6939 return false; 6940 6941 if (!StdInitializerList) { 6942 // Haven't recognized std::initializer_list yet, maybe this is it. 6943 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 6944 if (TemplateClass->getIdentifier() != 6945 &PP.getIdentifierTable().get("initializer_list") || 6946 !getStdNamespace()->InEnclosingNamespaceSetOf( 6947 TemplateClass->getDeclContext())) 6948 return false; 6949 // This is a template called std::initializer_list, but is it the right 6950 // template? 6951 TemplateParameterList *Params = Template->getTemplateParameters(); 6952 if (Params->getMinRequiredArguments() != 1) 6953 return false; 6954 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 6955 return false; 6956 6957 // It's the right template. 6958 StdInitializerList = Template; 6959 } 6960 6961 if (Template != StdInitializerList) 6962 return false; 6963 6964 // This is an instance of std::initializer_list. Find the argument type. 6965 if (Element) 6966 *Element = Arguments[0].getAsType(); 6967 return true; 6968 } 6969 6970 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 6971 NamespaceDecl *Std = S.getStdNamespace(); 6972 if (!Std) { 6973 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6974 return nullptr; 6975 } 6976 6977 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 6978 Loc, Sema::LookupOrdinaryName); 6979 if (!S.LookupQualifiedName(Result, Std)) { 6980 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6981 return nullptr; 6982 } 6983 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 6984 if (!Template) { 6985 Result.suppressDiagnostics(); 6986 // We found something weird. Complain about the first thing we found. 6987 NamedDecl *Found = *Result.begin(); 6988 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 6989 return nullptr; 6990 } 6991 6992 // We found some template called std::initializer_list. Now verify that it's 6993 // correct. 6994 TemplateParameterList *Params = Template->getTemplateParameters(); 6995 if (Params->getMinRequiredArguments() != 1 || 6996 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6997 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 6998 return nullptr; 6999 } 7000 7001 return Template; 7002 } 7003 7004 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 7005 if (!StdInitializerList) { 7006 StdInitializerList = LookupStdInitializerList(*this, Loc); 7007 if (!StdInitializerList) 7008 return QualType(); 7009 } 7010 7011 TemplateArgumentListInfo Args(Loc, Loc); 7012 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 7013 Context.getTrivialTypeSourceInfo(Element, 7014 Loc))); 7015 return Context.getCanonicalType( 7016 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 7017 } 7018 7019 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 7020 // C++ [dcl.init.list]p2: 7021 // A constructor is an initializer-list constructor if its first parameter 7022 // is of type std::initializer_list<E> or reference to possibly cv-qualified 7023 // std::initializer_list<E> for some type E, and either there are no other 7024 // parameters or else all other parameters have default arguments. 7025 if (Ctor->getNumParams() < 1 || 7026 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 7027 return false; 7028 7029 QualType ArgType = Ctor->getParamDecl(0)->getType(); 7030 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 7031 ArgType = RT->getPointeeType().getUnqualifiedType(); 7032 7033 return isStdInitializerList(ArgType, nullptr); 7034 } 7035 7036 /// \brief Determine whether a using statement is in a context where it will be 7037 /// apply in all contexts. 7038 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 7039 switch (CurContext->getDeclKind()) { 7040 case Decl::TranslationUnit: 7041 return true; 7042 case Decl::LinkageSpec: 7043 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 7044 default: 7045 return false; 7046 } 7047 } 7048 7049 namespace { 7050 7051 // Callback to only accept typo corrections that are namespaces. 7052 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 7053 public: 7054 bool ValidateCandidate(const TypoCorrection &candidate) override { 7055 if (NamedDecl *ND = candidate.getCorrectionDecl()) 7056 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 7057 return false; 7058 } 7059 }; 7060 7061 } 7062 7063 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 7064 CXXScopeSpec &SS, 7065 SourceLocation IdentLoc, 7066 IdentifierInfo *Ident) { 7067 NamespaceValidatorCCC Validator; 7068 R.clear(); 7069 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 7070 R.getLookupKind(), Sc, &SS, 7071 Validator, 7072 Sema::CTK_ErrorRecovery)) { 7073 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 7074 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 7075 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 7076 Ident->getName().equals(CorrectedStr); 7077 S.diagnoseTypo(Corrected, 7078 S.PDiag(diag::err_using_directive_member_suggest) 7079 << Ident << DC << DroppedSpecifier << SS.getRange(), 7080 S.PDiag(diag::note_namespace_defined_here)); 7081 } else { 7082 S.diagnoseTypo(Corrected, 7083 S.PDiag(diag::err_using_directive_suggest) << Ident, 7084 S.PDiag(diag::note_namespace_defined_here)); 7085 } 7086 R.addDecl(Corrected.getCorrectionDecl()); 7087 return true; 7088 } 7089 return false; 7090 } 7091 7092 Decl *Sema::ActOnUsingDirective(Scope *S, 7093 SourceLocation UsingLoc, 7094 SourceLocation NamespcLoc, 7095 CXXScopeSpec &SS, 7096 SourceLocation IdentLoc, 7097 IdentifierInfo *NamespcName, 7098 AttributeList *AttrList) { 7099 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7100 assert(NamespcName && "Invalid NamespcName."); 7101 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 7102 7103 // This can only happen along a recovery path. 7104 while (S->getFlags() & Scope::TemplateParamScope) 7105 S = S->getParent(); 7106 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7107 7108 UsingDirectiveDecl *UDir = nullptr; 7109 NestedNameSpecifier *Qualifier = nullptr; 7110 if (SS.isSet()) 7111 Qualifier = SS.getScopeRep(); 7112 7113 // Lookup namespace name. 7114 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 7115 LookupParsedName(R, S, &SS); 7116 if (R.isAmbiguous()) 7117 return nullptr; 7118 7119 if (R.empty()) { 7120 R.clear(); 7121 // Allow "using namespace std;" or "using namespace ::std;" even if 7122 // "std" hasn't been defined yet, for GCC compatibility. 7123 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 7124 NamespcName->isStr("std")) { 7125 Diag(IdentLoc, diag::ext_using_undefined_std); 7126 R.addDecl(getOrCreateStdNamespace()); 7127 R.resolveKind(); 7128 } 7129 // Otherwise, attempt typo correction. 7130 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 7131 } 7132 7133 if (!R.empty()) { 7134 NamedDecl *Named = R.getFoundDecl(); 7135 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 7136 && "expected namespace decl"); 7137 // C++ [namespace.udir]p1: 7138 // A using-directive specifies that the names in the nominated 7139 // namespace can be used in the scope in which the 7140 // using-directive appears after the using-directive. During 7141 // unqualified name lookup (3.4.1), the names appear as if they 7142 // were declared in the nearest enclosing namespace which 7143 // contains both the using-directive and the nominated 7144 // namespace. [Note: in this context, "contains" means "contains 7145 // directly or indirectly". ] 7146 7147 // Find enclosing context containing both using-directive and 7148 // nominated namespace. 7149 NamespaceDecl *NS = getNamespaceDecl(Named); 7150 DeclContext *CommonAncestor = cast<DeclContext>(NS); 7151 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 7152 CommonAncestor = CommonAncestor->getParent(); 7153 7154 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 7155 SS.getWithLocInContext(Context), 7156 IdentLoc, Named, CommonAncestor); 7157 7158 if (IsUsingDirectiveInToplevelContext(CurContext) && 7159 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 7160 Diag(IdentLoc, diag::warn_using_directive_in_header); 7161 } 7162 7163 PushUsingDirective(S, UDir); 7164 } else { 7165 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7166 } 7167 7168 if (UDir) 7169 ProcessDeclAttributeList(S, UDir, AttrList); 7170 7171 return UDir; 7172 } 7173 7174 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 7175 // If the scope has an associated entity and the using directive is at 7176 // namespace or translation unit scope, add the UsingDirectiveDecl into 7177 // its lookup structure so qualified name lookup can find it. 7178 DeclContext *Ctx = S->getEntity(); 7179 if (Ctx && !Ctx->isFunctionOrMethod()) 7180 Ctx->addDecl(UDir); 7181 else 7182 // Otherwise, it is at block scope. The using-directives will affect lookup 7183 // only to the end of the scope. 7184 S->PushUsingDirective(UDir); 7185 } 7186 7187 7188 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7189 AccessSpecifier AS, 7190 bool HasUsingKeyword, 7191 SourceLocation UsingLoc, 7192 CXXScopeSpec &SS, 7193 UnqualifiedId &Name, 7194 AttributeList *AttrList, 7195 bool HasTypenameKeyword, 7196 SourceLocation TypenameLoc) { 7197 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7198 7199 switch (Name.getKind()) { 7200 case UnqualifiedId::IK_ImplicitSelfParam: 7201 case UnqualifiedId::IK_Identifier: 7202 case UnqualifiedId::IK_OperatorFunctionId: 7203 case UnqualifiedId::IK_LiteralOperatorId: 7204 case UnqualifiedId::IK_ConversionFunctionId: 7205 break; 7206 7207 case UnqualifiedId::IK_ConstructorName: 7208 case UnqualifiedId::IK_ConstructorTemplateId: 7209 // C++11 inheriting constructors. 7210 Diag(Name.getLocStart(), 7211 getLangOpts().CPlusPlus11 ? 7212 diag::warn_cxx98_compat_using_decl_constructor : 7213 diag::err_using_decl_constructor) 7214 << SS.getRange(); 7215 7216 if (getLangOpts().CPlusPlus11) break; 7217 7218 return nullptr; 7219 7220 case UnqualifiedId::IK_DestructorName: 7221 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7222 << SS.getRange(); 7223 return nullptr; 7224 7225 case UnqualifiedId::IK_TemplateId: 7226 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7227 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7228 return nullptr; 7229 } 7230 7231 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7232 DeclarationName TargetName = TargetNameInfo.getName(); 7233 if (!TargetName) 7234 return nullptr; 7235 7236 // Warn about access declarations. 7237 if (!HasUsingKeyword) { 7238 Diag(Name.getLocStart(), 7239 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7240 : diag::warn_access_decl_deprecated) 7241 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7242 } 7243 7244 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7245 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7246 return nullptr; 7247 7248 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7249 TargetNameInfo, AttrList, 7250 /* IsInstantiation */ false, 7251 HasTypenameKeyword, TypenameLoc); 7252 if (UD) 7253 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7254 7255 return UD; 7256 } 7257 7258 /// \brief Determine whether a using declaration considers the given 7259 /// declarations as "equivalent", e.g., if they are redeclarations of 7260 /// the same entity or are both typedefs of the same type. 7261 static bool 7262 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7263 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7264 return true; 7265 7266 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7267 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7268 return Context.hasSameType(TD1->getUnderlyingType(), 7269 TD2->getUnderlyingType()); 7270 7271 return false; 7272 } 7273 7274 7275 /// Determines whether to create a using shadow decl for a particular 7276 /// decl, given the set of decls existing prior to this using lookup. 7277 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7278 const LookupResult &Previous, 7279 UsingShadowDecl *&PrevShadow) { 7280 // Diagnose finding a decl which is not from a base class of the 7281 // current class. We do this now because there are cases where this 7282 // function will silently decide not to build a shadow decl, which 7283 // will pre-empt further diagnostics. 7284 // 7285 // We don't need to do this in C++0x because we do the check once on 7286 // the qualifier. 7287 // 7288 // FIXME: diagnose the following if we care enough: 7289 // struct A { int foo; }; 7290 // struct B : A { using A::foo; }; 7291 // template <class T> struct C : A {}; 7292 // template <class T> struct D : C<T> { using B::foo; } // <--- 7293 // This is invalid (during instantiation) in C++03 because B::foo 7294 // resolves to the using decl in B, which is not a base class of D<T>. 7295 // We can't diagnose it immediately because C<T> is an unknown 7296 // specialization. The UsingShadowDecl in D<T> then points directly 7297 // to A::foo, which will look well-formed when we instantiate. 7298 // The right solution is to not collapse the shadow-decl chain. 7299 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7300 DeclContext *OrigDC = Orig->getDeclContext(); 7301 7302 // Handle enums and anonymous structs. 7303 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7304 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7305 while (OrigRec->isAnonymousStructOrUnion()) 7306 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7307 7308 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7309 if (OrigDC == CurContext) { 7310 Diag(Using->getLocation(), 7311 diag::err_using_decl_nested_name_specifier_is_current_class) 7312 << Using->getQualifierLoc().getSourceRange(); 7313 Diag(Orig->getLocation(), diag::note_using_decl_target); 7314 return true; 7315 } 7316 7317 Diag(Using->getQualifierLoc().getBeginLoc(), 7318 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7319 << Using->getQualifier() 7320 << cast<CXXRecordDecl>(CurContext) 7321 << Using->getQualifierLoc().getSourceRange(); 7322 Diag(Orig->getLocation(), diag::note_using_decl_target); 7323 return true; 7324 } 7325 } 7326 7327 if (Previous.empty()) return false; 7328 7329 NamedDecl *Target = Orig; 7330 if (isa<UsingShadowDecl>(Target)) 7331 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7332 7333 // If the target happens to be one of the previous declarations, we 7334 // don't have a conflict. 7335 // 7336 // FIXME: but we might be increasing its access, in which case we 7337 // should redeclare it. 7338 NamedDecl *NonTag = nullptr, *Tag = nullptr; 7339 bool FoundEquivalentDecl = false; 7340 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7341 I != E; ++I) { 7342 NamedDecl *D = (*I)->getUnderlyingDecl(); 7343 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7344 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7345 PrevShadow = Shadow; 7346 FoundEquivalentDecl = true; 7347 } 7348 7349 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7350 } 7351 7352 if (FoundEquivalentDecl) 7353 return false; 7354 7355 if (FunctionDecl *FD = Target->getAsFunction()) { 7356 NamedDecl *OldDecl = nullptr; 7357 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 7358 /*IsForUsingDecl*/ true)) { 7359 case Ovl_Overload: 7360 return false; 7361 7362 case Ovl_NonFunction: 7363 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7364 break; 7365 7366 // We found a decl with the exact signature. 7367 case Ovl_Match: 7368 // If we're in a record, we want to hide the target, so we 7369 // return true (without a diagnostic) to tell the caller not to 7370 // build a shadow decl. 7371 if (CurContext->isRecord()) 7372 return true; 7373 7374 // If we're not in a record, this is an error. 7375 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7376 break; 7377 } 7378 7379 Diag(Target->getLocation(), diag::note_using_decl_target); 7380 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7381 return true; 7382 } 7383 7384 // Target is not a function. 7385 7386 if (isa<TagDecl>(Target)) { 7387 // No conflict between a tag and a non-tag. 7388 if (!Tag) return false; 7389 7390 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7391 Diag(Target->getLocation(), diag::note_using_decl_target); 7392 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7393 return true; 7394 } 7395 7396 // No conflict between a tag and a non-tag. 7397 if (!NonTag) return false; 7398 7399 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7400 Diag(Target->getLocation(), diag::note_using_decl_target); 7401 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7402 return true; 7403 } 7404 7405 /// Builds a shadow declaration corresponding to a 'using' declaration. 7406 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7407 UsingDecl *UD, 7408 NamedDecl *Orig, 7409 UsingShadowDecl *PrevDecl) { 7410 7411 // If we resolved to another shadow declaration, just coalesce them. 7412 NamedDecl *Target = Orig; 7413 if (isa<UsingShadowDecl>(Target)) { 7414 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7415 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7416 } 7417 7418 UsingShadowDecl *Shadow 7419 = UsingShadowDecl::Create(Context, CurContext, 7420 UD->getLocation(), UD, Target); 7421 UD->addShadowDecl(Shadow); 7422 7423 Shadow->setAccess(UD->getAccess()); 7424 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7425 Shadow->setInvalidDecl(); 7426 7427 Shadow->setPreviousDecl(PrevDecl); 7428 7429 if (S) 7430 PushOnScopeChains(Shadow, S); 7431 else 7432 CurContext->addDecl(Shadow); 7433 7434 7435 return Shadow; 7436 } 7437 7438 /// Hides a using shadow declaration. This is required by the current 7439 /// using-decl implementation when a resolvable using declaration in a 7440 /// class is followed by a declaration which would hide or override 7441 /// one or more of the using decl's targets; for example: 7442 /// 7443 /// struct Base { void foo(int); }; 7444 /// struct Derived : Base { 7445 /// using Base::foo; 7446 /// void foo(int); 7447 /// }; 7448 /// 7449 /// The governing language is C++03 [namespace.udecl]p12: 7450 /// 7451 /// When a using-declaration brings names from a base class into a 7452 /// derived class scope, member functions in the derived class 7453 /// override and/or hide member functions with the same name and 7454 /// parameter types in a base class (rather than conflicting). 7455 /// 7456 /// There are two ways to implement this: 7457 /// (1) optimistically create shadow decls when they're not hidden 7458 /// by existing declarations, or 7459 /// (2) don't create any shadow decls (or at least don't make them 7460 /// visible) until we've fully parsed/instantiated the class. 7461 /// The problem with (1) is that we might have to retroactively remove 7462 /// a shadow decl, which requires several O(n) operations because the 7463 /// decl structures are (very reasonably) not designed for removal. 7464 /// (2) avoids this but is very fiddly and phase-dependent. 7465 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7466 if (Shadow->getDeclName().getNameKind() == 7467 DeclarationName::CXXConversionFunctionName) 7468 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7469 7470 // Remove it from the DeclContext... 7471 Shadow->getDeclContext()->removeDecl(Shadow); 7472 7473 // ...and the scope, if applicable... 7474 if (S) { 7475 S->RemoveDecl(Shadow); 7476 IdResolver.RemoveDecl(Shadow); 7477 } 7478 7479 // ...and the using decl. 7480 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7481 7482 // TODO: complain somehow if Shadow was used. It shouldn't 7483 // be possible for this to happen, because...? 7484 } 7485 7486 /// Find the base specifier for a base class with the given type. 7487 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 7488 QualType DesiredBase, 7489 bool &AnyDependentBases) { 7490 // Check whether the named type is a direct base class. 7491 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 7492 for (auto &Base : Derived->bases()) { 7493 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 7494 if (CanonicalDesiredBase == BaseType) 7495 return &Base; 7496 if (BaseType->isDependentType()) 7497 AnyDependentBases = true; 7498 } 7499 return nullptr; 7500 } 7501 7502 namespace { 7503 class UsingValidatorCCC : public CorrectionCandidateCallback { 7504 public: 7505 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7506 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 7507 : HasTypenameKeyword(HasTypenameKeyword), 7508 IsInstantiation(IsInstantiation), OldNNS(NNS), 7509 RequireMemberOf(RequireMemberOf) {} 7510 7511 bool ValidateCandidate(const TypoCorrection &Candidate) override { 7512 NamedDecl *ND = Candidate.getCorrectionDecl(); 7513 7514 // Keywords are not valid here. 7515 if (!ND || isa<NamespaceDecl>(ND)) 7516 return false; 7517 7518 // Completely unqualified names are invalid for a 'using' declaration. 7519 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7520 return false; 7521 7522 if (RequireMemberOf) { 7523 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 7524 if (FoundRecord && FoundRecord->isInjectedClassName()) { 7525 // No-one ever wants a using-declaration to name an injected-class-name 7526 // of a base class, unless they're declaring an inheriting constructor. 7527 ASTContext &Ctx = ND->getASTContext(); 7528 if (!Ctx.getLangOpts().CPlusPlus11) 7529 return false; 7530 QualType FoundType = Ctx.getRecordType(FoundRecord); 7531 7532 // Check that the injected-class-name is named as a member of its own 7533 // type; we don't want to suggest 'using Derived::Base;', since that 7534 // means something else. 7535 NestedNameSpecifier *Specifier = 7536 Candidate.WillReplaceSpecifier() 7537 ? Candidate.getCorrectionSpecifier() 7538 : OldNNS; 7539 if (!Specifier->getAsType() || 7540 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 7541 return false; 7542 7543 // Check that this inheriting constructor declaration actually names a 7544 // direct base class of the current class. 7545 bool AnyDependentBases = false; 7546 if (!findDirectBaseWithType(RequireMemberOf, 7547 Ctx.getRecordType(FoundRecord), 7548 AnyDependentBases) && 7549 !AnyDependentBases) 7550 return false; 7551 } else { 7552 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 7553 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 7554 return false; 7555 7556 // FIXME: Check that the base class member is accessible? 7557 } 7558 } 7559 7560 if (isa<TypeDecl>(ND)) 7561 return HasTypenameKeyword || !IsInstantiation; 7562 7563 return !HasTypenameKeyword; 7564 } 7565 7566 private: 7567 bool HasTypenameKeyword; 7568 bool IsInstantiation; 7569 NestedNameSpecifier *OldNNS; 7570 CXXRecordDecl *RequireMemberOf; 7571 }; 7572 } // end anonymous namespace 7573 7574 /// Builds a using declaration. 7575 /// 7576 /// \param IsInstantiation - Whether this call arises from an 7577 /// instantiation of an unresolved using declaration. We treat 7578 /// the lookup differently for these declarations. 7579 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7580 SourceLocation UsingLoc, 7581 CXXScopeSpec &SS, 7582 DeclarationNameInfo NameInfo, 7583 AttributeList *AttrList, 7584 bool IsInstantiation, 7585 bool HasTypenameKeyword, 7586 SourceLocation TypenameLoc) { 7587 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7588 SourceLocation IdentLoc = NameInfo.getLoc(); 7589 assert(IdentLoc.isValid() && "Invalid TargetName location."); 7590 7591 // FIXME: We ignore attributes for now. 7592 7593 if (SS.isEmpty()) { 7594 Diag(IdentLoc, diag::err_using_requires_qualname); 7595 return nullptr; 7596 } 7597 7598 // Do the redeclaration lookup in the current scope. 7599 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 7600 ForRedeclaration); 7601 Previous.setHideTags(false); 7602 if (S) { 7603 LookupName(Previous, S); 7604 7605 // It is really dumb that we have to do this. 7606 LookupResult::Filter F = Previous.makeFilter(); 7607 while (F.hasNext()) { 7608 NamedDecl *D = F.next(); 7609 if (!isDeclInScope(D, CurContext, S)) 7610 F.erase(); 7611 // If we found a local extern declaration that's not ordinarily visible, 7612 // and this declaration is being added to a non-block scope, ignore it. 7613 // We're only checking for scope conflicts here, not also for violations 7614 // of the linkage rules. 7615 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 7616 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 7617 F.erase(); 7618 } 7619 F.done(); 7620 } else { 7621 assert(IsInstantiation && "no scope in non-instantiation"); 7622 assert(CurContext->isRecord() && "scope not record in instantiation"); 7623 LookupQualifiedName(Previous, CurContext); 7624 } 7625 7626 // Check for invalid redeclarations. 7627 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 7628 SS, IdentLoc, Previous)) 7629 return nullptr; 7630 7631 // Check for bad qualifiers. 7632 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 7633 return nullptr; 7634 7635 DeclContext *LookupContext = computeDeclContext(SS); 7636 NamedDecl *D; 7637 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7638 if (!LookupContext) { 7639 if (HasTypenameKeyword) { 7640 // FIXME: not all declaration name kinds are legal here 7641 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 7642 UsingLoc, TypenameLoc, 7643 QualifierLoc, 7644 IdentLoc, NameInfo.getName()); 7645 } else { 7646 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 7647 QualifierLoc, NameInfo); 7648 } 7649 D->setAccess(AS); 7650 CurContext->addDecl(D); 7651 return D; 7652 } 7653 7654 auto Build = [&](bool Invalid) { 7655 UsingDecl *UD = 7656 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo, 7657 HasTypenameKeyword); 7658 UD->setAccess(AS); 7659 CurContext->addDecl(UD); 7660 UD->setInvalidDecl(Invalid); 7661 return UD; 7662 }; 7663 auto BuildInvalid = [&]{ return Build(true); }; 7664 auto BuildValid = [&]{ return Build(false); }; 7665 7666 if (RequireCompleteDeclContext(SS, LookupContext)) 7667 return BuildInvalid(); 7668 7669 // The normal rules do not apply to inheriting constructor declarations. 7670 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 7671 UsingDecl *UD = BuildValid(); 7672 CheckInheritingConstructorUsingDecl(UD); 7673 return UD; 7674 } 7675 7676 // Otherwise, look up the target name. 7677 7678 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7679 7680 // Unlike most lookups, we don't always want to hide tag 7681 // declarations: tag names are visible through the using declaration 7682 // even if hidden by ordinary names, *except* in a dependent context 7683 // where it's important for the sanity of two-phase lookup. 7684 if (!IsInstantiation) 7685 R.setHideTags(false); 7686 7687 // For the purposes of this lookup, we have a base object type 7688 // equal to that of the current context. 7689 if (CurContext->isRecord()) { 7690 R.setBaseObjectType( 7691 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 7692 } 7693 7694 LookupQualifiedName(R, LookupContext); 7695 7696 // Try to correct typos if possible. 7697 if (R.empty()) { 7698 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 7699 dyn_cast<CXXRecordDecl>(CurContext)); 7700 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(), 7701 R.getLookupKind(), S, &SS, CCC, 7702 CTK_ErrorRecovery)){ 7703 // We reject any correction for which ND would be NULL. 7704 NamedDecl *ND = Corrected.getCorrectionDecl(); 7705 7706 // We reject candidates where DroppedSpecifier == true, hence the 7707 // literal '0' below. 7708 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 7709 << NameInfo.getName() << LookupContext << 0 7710 << SS.getRange()); 7711 7712 // If we corrected to an inheriting constructor, handle it as one. 7713 auto *RD = dyn_cast<CXXRecordDecl>(ND); 7714 if (RD && RD->isInjectedClassName()) { 7715 // Fix up the information we'll use to build the using declaration. 7716 if (Corrected.WillReplaceSpecifier()) { 7717 NestedNameSpecifierLocBuilder Builder; 7718 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 7719 QualifierLoc.getSourceRange()); 7720 QualifierLoc = Builder.getWithLocInContext(Context); 7721 } 7722 7723 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 7724 Context.getCanonicalType(Context.getRecordType(RD)))); 7725 NameInfo.setNamedTypeInfo(nullptr); 7726 7727 // Build it and process it as an inheriting constructor. 7728 UsingDecl *UD = BuildValid(); 7729 CheckInheritingConstructorUsingDecl(UD); 7730 return UD; 7731 } 7732 7733 // FIXME: Pick up all the declarations if we found an overloaded function. 7734 R.setLookupName(Corrected.getCorrection()); 7735 R.addDecl(ND); 7736 } else { 7737 Diag(IdentLoc, diag::err_no_member) 7738 << NameInfo.getName() << LookupContext << SS.getRange(); 7739 return BuildInvalid(); 7740 } 7741 } 7742 7743 if (R.isAmbiguous()) 7744 return BuildInvalid(); 7745 7746 if (HasTypenameKeyword) { 7747 // If we asked for a typename and got a non-type decl, error out. 7748 if (!R.getAsSingle<TypeDecl>()) { 7749 Diag(IdentLoc, diag::err_using_typename_non_type); 7750 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 7751 Diag((*I)->getUnderlyingDecl()->getLocation(), 7752 diag::note_using_decl_target); 7753 return BuildInvalid(); 7754 } 7755 } else { 7756 // If we asked for a non-typename and we got a type, error out, 7757 // but only if this is an instantiation of an unresolved using 7758 // decl. Otherwise just silently find the type name. 7759 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 7760 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 7761 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 7762 return BuildInvalid(); 7763 } 7764 } 7765 7766 // C++0x N2914 [namespace.udecl]p6: 7767 // A using-declaration shall not name a namespace. 7768 if (R.getAsSingle<NamespaceDecl>()) { 7769 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 7770 << SS.getRange(); 7771 return BuildInvalid(); 7772 } 7773 7774 UsingDecl *UD = BuildValid(); 7775 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7776 UsingShadowDecl *PrevDecl = nullptr; 7777 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 7778 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 7779 } 7780 7781 return UD; 7782 } 7783 7784 /// Additional checks for a using declaration referring to a constructor name. 7785 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 7786 assert(!UD->hasTypename() && "expecting a constructor name"); 7787 7788 const Type *SourceType = UD->getQualifier()->getAsType(); 7789 assert(SourceType && 7790 "Using decl naming constructor doesn't have type in scope spec."); 7791 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7792 7793 // Check whether the named type is a direct base class. 7794 bool AnyDependentBases = false; 7795 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 7796 AnyDependentBases); 7797 if (!Base && !AnyDependentBases) { 7798 Diag(UD->getUsingLoc(), 7799 diag::err_using_decl_constructor_not_in_direct_base) 7800 << UD->getNameInfo().getSourceRange() 7801 << QualType(SourceType, 0) << TargetClass; 7802 UD->setInvalidDecl(); 7803 return true; 7804 } 7805 7806 if (Base) 7807 Base->setInheritConstructors(); 7808 7809 return false; 7810 } 7811 7812 /// Checks that the given using declaration is not an invalid 7813 /// redeclaration. Note that this is checking only for the using decl 7814 /// itself, not for any ill-formedness among the UsingShadowDecls. 7815 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7816 bool HasTypenameKeyword, 7817 const CXXScopeSpec &SS, 7818 SourceLocation NameLoc, 7819 const LookupResult &Prev) { 7820 // C++03 [namespace.udecl]p8: 7821 // C++0x [namespace.udecl]p10: 7822 // A using-declaration is a declaration and can therefore be used 7823 // repeatedly where (and only where) multiple declarations are 7824 // allowed. 7825 // 7826 // That's in non-member contexts. 7827 if (!CurContext->getRedeclContext()->isRecord()) 7828 return false; 7829 7830 NestedNameSpecifier *Qual = SS.getScopeRep(); 7831 7832 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7833 NamedDecl *D = *I; 7834 7835 bool DTypename; 7836 NestedNameSpecifier *DQual; 7837 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7838 DTypename = UD->hasTypename(); 7839 DQual = UD->getQualifier(); 7840 } else if (UnresolvedUsingValueDecl *UD 7841 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7842 DTypename = false; 7843 DQual = UD->getQualifier(); 7844 } else if (UnresolvedUsingTypenameDecl *UD 7845 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7846 DTypename = true; 7847 DQual = UD->getQualifier(); 7848 } else continue; 7849 7850 // using decls differ if one says 'typename' and the other doesn't. 7851 // FIXME: non-dependent using decls? 7852 if (HasTypenameKeyword != DTypename) continue; 7853 7854 // using decls differ if they name different scopes (but note that 7855 // template instantiation can cause this check to trigger when it 7856 // didn't before instantiation). 7857 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7858 Context.getCanonicalNestedNameSpecifier(DQual)) 7859 continue; 7860 7861 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7862 Diag(D->getLocation(), diag::note_using_decl) << 1; 7863 return true; 7864 } 7865 7866 return false; 7867 } 7868 7869 7870 /// Checks that the given nested-name qualifier used in a using decl 7871 /// in the current context is appropriately related to the current 7872 /// scope. If an error is found, diagnoses it and returns true. 7873 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7874 const CXXScopeSpec &SS, 7875 const DeclarationNameInfo &NameInfo, 7876 SourceLocation NameLoc) { 7877 DeclContext *NamedContext = computeDeclContext(SS); 7878 7879 if (!CurContext->isRecord()) { 7880 // C++03 [namespace.udecl]p3: 7881 // C++0x [namespace.udecl]p8: 7882 // A using-declaration for a class member shall be a member-declaration. 7883 7884 // If we weren't able to compute a valid scope, it must be a 7885 // dependent class scope. 7886 if (!NamedContext || NamedContext->isRecord()) { 7887 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext); 7888 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 7889 RD = nullptr; 7890 7891 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7892 << SS.getRange(); 7893 7894 // If we have a complete, non-dependent source type, try to suggest a 7895 // way to get the same effect. 7896 if (!RD) 7897 return true; 7898 7899 // Find what this using-declaration was referring to. 7900 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7901 R.setHideTags(false); 7902 R.suppressDiagnostics(); 7903 LookupQualifiedName(R, RD); 7904 7905 if (R.getAsSingle<TypeDecl>()) { 7906 if (getLangOpts().CPlusPlus11) { 7907 // Convert 'using X::Y;' to 'using Y = X::Y;'. 7908 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 7909 << 0 // alias declaration 7910 << FixItHint::CreateInsertion(SS.getBeginLoc(), 7911 NameInfo.getName().getAsString() + 7912 " = "); 7913 } else { 7914 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 7915 SourceLocation InsertLoc = 7916 PP.getLocForEndOfToken(NameInfo.getLocEnd()); 7917 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 7918 << 1 // typedef declaration 7919 << FixItHint::CreateReplacement(UsingLoc, "typedef") 7920 << FixItHint::CreateInsertion( 7921 InsertLoc, " " + NameInfo.getName().getAsString()); 7922 } 7923 } else if (R.getAsSingle<VarDecl>()) { 7924 // Don't provide a fixit outside C++11 mode; we don't want to suggest 7925 // repeating the type of the static data member here. 7926 FixItHint FixIt; 7927 if (getLangOpts().CPlusPlus11) { 7928 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 7929 FixIt = FixItHint::CreateReplacement( 7930 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 7931 } 7932 7933 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 7934 << 2 // reference declaration 7935 << FixIt; 7936 } 7937 return true; 7938 } 7939 7940 // Otherwise, everything is known to be fine. 7941 return false; 7942 } 7943 7944 // The current scope is a record. 7945 7946 // If the named context is dependent, we can't decide much. 7947 if (!NamedContext) { 7948 // FIXME: in C++0x, we can diagnose if we can prove that the 7949 // nested-name-specifier does not refer to a base class, which is 7950 // still possible in some cases. 7951 7952 // Otherwise we have to conservatively report that things might be 7953 // okay. 7954 return false; 7955 } 7956 7957 if (!NamedContext->isRecord()) { 7958 // Ideally this would point at the last name in the specifier, 7959 // but we don't have that level of source info. 7960 Diag(SS.getRange().getBegin(), 7961 diag::err_using_decl_nested_name_specifier_is_not_class) 7962 << SS.getScopeRep() << SS.getRange(); 7963 return true; 7964 } 7965 7966 if (!NamedContext->isDependentContext() && 7967 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7968 return true; 7969 7970 if (getLangOpts().CPlusPlus11) { 7971 // C++0x [namespace.udecl]p3: 7972 // In a using-declaration used as a member-declaration, the 7973 // nested-name-specifier shall name a base class of the class 7974 // being defined. 7975 7976 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7977 cast<CXXRecordDecl>(NamedContext))) { 7978 if (CurContext == NamedContext) { 7979 Diag(NameLoc, 7980 diag::err_using_decl_nested_name_specifier_is_current_class) 7981 << SS.getRange(); 7982 return true; 7983 } 7984 7985 Diag(SS.getRange().getBegin(), 7986 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7987 << SS.getScopeRep() 7988 << cast<CXXRecordDecl>(CurContext) 7989 << SS.getRange(); 7990 return true; 7991 } 7992 7993 return false; 7994 } 7995 7996 // C++03 [namespace.udecl]p4: 7997 // A using-declaration used as a member-declaration shall refer 7998 // to a member of a base class of the class being defined [etc.]. 7999 8000 // Salient point: SS doesn't have to name a base class as long as 8001 // lookup only finds members from base classes. Therefore we can 8002 // diagnose here only if we can prove that that can't happen, 8003 // i.e. if the class hierarchies provably don't intersect. 8004 8005 // TODO: it would be nice if "definitely valid" results were cached 8006 // in the UsingDecl and UsingShadowDecl so that these checks didn't 8007 // need to be repeated. 8008 8009 struct UserData { 8010 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 8011 8012 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 8013 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8014 Data->Bases.insert(Base); 8015 return true; 8016 } 8017 8018 bool hasDependentBases(const CXXRecordDecl *Class) { 8019 return !Class->forallBases(collect, this); 8020 } 8021 8022 /// Returns true if the base is dependent or is one of the 8023 /// accumulated base classes. 8024 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 8025 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8026 return !Data->Bases.count(Base); 8027 } 8028 8029 bool mightShareBases(const CXXRecordDecl *Class) { 8030 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 8031 } 8032 }; 8033 8034 UserData Data; 8035 8036 // Returns false if we find a dependent base. 8037 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 8038 return false; 8039 8040 // Returns false if the class has a dependent base or if it or one 8041 // of its bases is present in the base set of the current context. 8042 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 8043 return false; 8044 8045 Diag(SS.getRange().getBegin(), 8046 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8047 << SS.getScopeRep() 8048 << cast<CXXRecordDecl>(CurContext) 8049 << SS.getRange(); 8050 8051 return true; 8052 } 8053 8054 Decl *Sema::ActOnAliasDeclaration(Scope *S, 8055 AccessSpecifier AS, 8056 MultiTemplateParamsArg TemplateParamLists, 8057 SourceLocation UsingLoc, 8058 UnqualifiedId &Name, 8059 AttributeList *AttrList, 8060 TypeResult Type) { 8061 // Skip up to the relevant declaration scope. 8062 while (S->getFlags() & Scope::TemplateParamScope) 8063 S = S->getParent(); 8064 assert((S->getFlags() & Scope::DeclScope) && 8065 "got alias-declaration outside of declaration scope"); 8066 8067 if (Type.isInvalid()) 8068 return nullptr; 8069 8070 bool Invalid = false; 8071 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 8072 TypeSourceInfo *TInfo = nullptr; 8073 GetTypeFromParser(Type.get(), &TInfo); 8074 8075 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 8076 return nullptr; 8077 8078 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 8079 UPPC_DeclarationType)) { 8080 Invalid = true; 8081 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 8082 TInfo->getTypeLoc().getBeginLoc()); 8083 } 8084 8085 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 8086 LookupName(Previous, S); 8087 8088 // Warn about shadowing the name of a template parameter. 8089 if (Previous.isSingleResult() && 8090 Previous.getFoundDecl()->isTemplateParameter()) { 8091 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 8092 Previous.clear(); 8093 } 8094 8095 assert(Name.Kind == UnqualifiedId::IK_Identifier && 8096 "name in alias declaration must be an identifier"); 8097 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 8098 Name.StartLocation, 8099 Name.Identifier, TInfo); 8100 8101 NewTD->setAccess(AS); 8102 8103 if (Invalid) 8104 NewTD->setInvalidDecl(); 8105 8106 ProcessDeclAttributeList(S, NewTD, AttrList); 8107 8108 CheckTypedefForVariablyModifiedType(S, NewTD); 8109 Invalid |= NewTD->isInvalidDecl(); 8110 8111 bool Redeclaration = false; 8112 8113 NamedDecl *NewND; 8114 if (TemplateParamLists.size()) { 8115 TypeAliasTemplateDecl *OldDecl = nullptr; 8116 TemplateParameterList *OldTemplateParams = nullptr; 8117 8118 if (TemplateParamLists.size() != 1) { 8119 Diag(UsingLoc, diag::err_alias_template_extra_headers) 8120 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 8121 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 8122 } 8123 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 8124 8125 // Only consider previous declarations in the same scope. 8126 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 8127 /*ExplicitInstantiationOrSpecialization*/false); 8128 if (!Previous.empty()) { 8129 Redeclaration = true; 8130 8131 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 8132 if (!OldDecl && !Invalid) { 8133 Diag(UsingLoc, diag::err_redefinition_different_kind) 8134 << Name.Identifier; 8135 8136 NamedDecl *OldD = Previous.getRepresentativeDecl(); 8137 if (OldD->getLocation().isValid()) 8138 Diag(OldD->getLocation(), diag::note_previous_definition); 8139 8140 Invalid = true; 8141 } 8142 8143 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 8144 if (TemplateParameterListsAreEqual(TemplateParams, 8145 OldDecl->getTemplateParameters(), 8146 /*Complain=*/true, 8147 TPL_TemplateMatch)) 8148 OldTemplateParams = OldDecl->getTemplateParameters(); 8149 else 8150 Invalid = true; 8151 8152 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 8153 if (!Invalid && 8154 !Context.hasSameType(OldTD->getUnderlyingType(), 8155 NewTD->getUnderlyingType())) { 8156 // FIXME: The C++0x standard does not clearly say this is ill-formed, 8157 // but we can't reasonably accept it. 8158 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 8159 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 8160 if (OldTD->getLocation().isValid()) 8161 Diag(OldTD->getLocation(), diag::note_previous_definition); 8162 Invalid = true; 8163 } 8164 } 8165 } 8166 8167 // Merge any previous default template arguments into our parameters, 8168 // and check the parameter list. 8169 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 8170 TPC_TypeAliasTemplate)) 8171 return nullptr; 8172 8173 TypeAliasTemplateDecl *NewDecl = 8174 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 8175 Name.Identifier, TemplateParams, 8176 NewTD); 8177 8178 NewDecl->setAccess(AS); 8179 8180 if (Invalid) 8181 NewDecl->setInvalidDecl(); 8182 else if (OldDecl) 8183 NewDecl->setPreviousDecl(OldDecl); 8184 8185 NewND = NewDecl; 8186 } else { 8187 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 8188 NewND = NewTD; 8189 } 8190 8191 if (!Redeclaration) 8192 PushOnScopeChains(NewND, S); 8193 8194 ActOnDocumentableDecl(NewND); 8195 return NewND; 8196 } 8197 8198 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 8199 SourceLocation NamespaceLoc, 8200 SourceLocation AliasLoc, 8201 IdentifierInfo *Alias, 8202 CXXScopeSpec &SS, 8203 SourceLocation IdentLoc, 8204 IdentifierInfo *Ident) { 8205 8206 // Lookup the namespace name. 8207 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 8208 LookupParsedName(R, S, &SS); 8209 8210 // Check if we have a previous declaration with the same name. 8211 NamedDecl *PrevDecl 8212 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 8213 ForRedeclaration); 8214 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 8215 PrevDecl = nullptr; 8216 8217 if (PrevDecl) { 8218 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 8219 // We already have an alias with the same name that points to the same 8220 // namespace, so don't create a new one. 8221 // FIXME: At some point, we'll want to create the (redundant) 8222 // declaration to maintain better source information. 8223 if (!R.isAmbiguous() && !R.empty() && 8224 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 8225 return nullptr; 8226 } 8227 8228 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 8229 diag::err_redefinition_different_kind; 8230 Diag(AliasLoc, DiagID) << Alias; 8231 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8232 return nullptr; 8233 } 8234 8235 if (R.isAmbiguous()) 8236 return nullptr; 8237 8238 if (R.empty()) { 8239 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 8240 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8241 return nullptr; 8242 } 8243 } 8244 8245 NamespaceAliasDecl *AliasDecl = 8246 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 8247 Alias, SS.getWithLocInContext(Context), 8248 IdentLoc, R.getFoundDecl()); 8249 8250 PushOnScopeChains(AliasDecl, S); 8251 return AliasDecl; 8252 } 8253 8254 Sema::ImplicitExceptionSpecification 8255 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 8256 CXXMethodDecl *MD) { 8257 CXXRecordDecl *ClassDecl = MD->getParent(); 8258 8259 // C++ [except.spec]p14: 8260 // An implicitly declared special member function (Clause 12) shall have an 8261 // exception-specification. [...] 8262 ImplicitExceptionSpecification ExceptSpec(*this); 8263 if (ClassDecl->isInvalidDecl()) 8264 return ExceptSpec; 8265 8266 // Direct base-class constructors. 8267 for (const auto &B : ClassDecl->bases()) { 8268 if (B.isVirtual()) // Handled below. 8269 continue; 8270 8271 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8272 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8273 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8274 // If this is a deleted function, add it anyway. This might be conformant 8275 // with the standard. This might not. I'm not sure. It might not matter. 8276 if (Constructor) 8277 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8278 } 8279 } 8280 8281 // Virtual base-class constructors. 8282 for (const auto &B : ClassDecl->vbases()) { 8283 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8284 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8285 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8286 // If this is a deleted function, add it anyway. This might be conformant 8287 // with the standard. This might not. I'm not sure. It might not matter. 8288 if (Constructor) 8289 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8290 } 8291 } 8292 8293 // Field constructors. 8294 for (const auto *F : ClassDecl->fields()) { 8295 if (F->hasInClassInitializer()) { 8296 if (Expr *E = F->getInClassInitializer()) 8297 ExceptSpec.CalledExpr(E); 8298 else if (!F->isInvalidDecl()) 8299 // DR1351: 8300 // If the brace-or-equal-initializer of a non-static data member 8301 // invokes a defaulted default constructor of its class or of an 8302 // enclosing class in a potentially evaluated subexpression, the 8303 // program is ill-formed. 8304 // 8305 // This resolution is unworkable: the exception specification of the 8306 // default constructor can be needed in an unevaluated context, in 8307 // particular, in the operand of a noexcept-expression, and we can be 8308 // unable to compute an exception specification for an enclosed class. 8309 // 8310 // We do not allow an in-class initializer to require the evaluation 8311 // of the exception specification for any in-class initializer whose 8312 // definition is not lexically complete. 8313 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 8314 } else if (const RecordType *RecordTy 8315 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8316 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8317 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8318 // If this is a deleted function, add it anyway. This might be conformant 8319 // with the standard. This might not. I'm not sure. It might not matter. 8320 // In particular, the problem is that this function never gets called. It 8321 // might just be ill-formed because this function attempts to refer to 8322 // a deleted function here. 8323 if (Constructor) 8324 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8325 } 8326 } 8327 8328 return ExceptSpec; 8329 } 8330 8331 Sema::ImplicitExceptionSpecification 8332 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8333 CXXRecordDecl *ClassDecl = CD->getParent(); 8334 8335 // C++ [except.spec]p14: 8336 // An inheriting constructor [...] shall have an exception-specification. [...] 8337 ImplicitExceptionSpecification ExceptSpec(*this); 8338 if (ClassDecl->isInvalidDecl()) 8339 return ExceptSpec; 8340 8341 // Inherited constructor. 8342 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8343 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8344 // FIXME: Copying or moving the parameters could add extra exceptions to the 8345 // set, as could the default arguments for the inherited constructor. This 8346 // will be addressed when we implement the resolution of core issue 1351. 8347 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8348 8349 // Direct base-class constructors. 8350 for (const auto &B : ClassDecl->bases()) { 8351 if (B.isVirtual()) // Handled below. 8352 continue; 8353 8354 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8355 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8356 if (BaseClassDecl == InheritedDecl) 8357 continue; 8358 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8359 if (Constructor) 8360 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8361 } 8362 } 8363 8364 // Virtual base-class constructors. 8365 for (const auto &B : ClassDecl->vbases()) { 8366 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8367 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8368 if (BaseClassDecl == InheritedDecl) 8369 continue; 8370 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8371 if (Constructor) 8372 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8373 } 8374 } 8375 8376 // Field constructors. 8377 for (const auto *F : ClassDecl->fields()) { 8378 if (F->hasInClassInitializer()) { 8379 if (Expr *E = F->getInClassInitializer()) 8380 ExceptSpec.CalledExpr(E); 8381 else if (!F->isInvalidDecl()) 8382 Diag(CD->getLocation(), 8383 diag::err_in_class_initializer_references_def_ctor) << CD; 8384 } else if (const RecordType *RecordTy 8385 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8386 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8387 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8388 if (Constructor) 8389 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8390 } 8391 } 8392 8393 return ExceptSpec; 8394 } 8395 8396 namespace { 8397 /// RAII object to register a special member as being currently declared. 8398 struct DeclaringSpecialMember { 8399 Sema &S; 8400 Sema::SpecialMemberDecl D; 8401 bool WasAlreadyBeingDeclared; 8402 8403 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8404 : S(S), D(RD, CSM) { 8405 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 8406 if (WasAlreadyBeingDeclared) 8407 // This almost never happens, but if it does, ensure that our cache 8408 // doesn't contain a stale result. 8409 S.SpecialMemberCache.clear(); 8410 8411 // FIXME: Register a note to be produced if we encounter an error while 8412 // declaring the special member. 8413 } 8414 ~DeclaringSpecialMember() { 8415 if (!WasAlreadyBeingDeclared) 8416 S.SpecialMembersBeingDeclared.erase(D); 8417 } 8418 8419 /// \brief Are we already trying to declare this special member? 8420 bool isAlreadyBeingDeclared() const { 8421 return WasAlreadyBeingDeclared; 8422 } 8423 }; 8424 } 8425 8426 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8427 CXXRecordDecl *ClassDecl) { 8428 // C++ [class.ctor]p5: 8429 // A default constructor for a class X is a constructor of class X 8430 // that can be called without an argument. If there is no 8431 // user-declared constructor for class X, a default constructor is 8432 // implicitly declared. An implicitly-declared default constructor 8433 // is an inline public member of its class. 8434 assert(ClassDecl->needsImplicitDefaultConstructor() && 8435 "Should not build implicit default constructor!"); 8436 8437 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8438 if (DSM.isAlreadyBeingDeclared()) 8439 return nullptr; 8440 8441 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8442 CXXDefaultConstructor, 8443 false); 8444 8445 // Create the actual constructor declaration. 8446 CanQualType ClassType 8447 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8448 SourceLocation ClassLoc = ClassDecl->getLocation(); 8449 DeclarationName Name 8450 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8451 DeclarationNameInfo NameInfo(Name, ClassLoc); 8452 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8453 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 8454 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 8455 /*isImplicitlyDeclared=*/true, Constexpr); 8456 DefaultCon->setAccess(AS_public); 8457 DefaultCon->setDefaulted(); 8458 DefaultCon->setImplicit(); 8459 8460 // Build an exception specification pointing back at this constructor. 8461 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8462 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8463 8464 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8465 // constructors is easy to compute. 8466 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8467 8468 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8469 SetDeclDeleted(DefaultCon, ClassLoc); 8470 8471 // Note that we have declared this constructor. 8472 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8473 8474 if (Scope *S = getScopeForContext(ClassDecl)) 8475 PushOnScopeChains(DefaultCon, S, false); 8476 ClassDecl->addDecl(DefaultCon); 8477 8478 return DefaultCon; 8479 } 8480 8481 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8482 CXXConstructorDecl *Constructor) { 8483 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8484 !Constructor->doesThisDeclarationHaveABody() && 8485 !Constructor->isDeleted()) && 8486 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8487 8488 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8489 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8490 8491 SynthesizedFunctionScope Scope(*this, Constructor); 8492 DiagnosticErrorTrap Trap(Diags); 8493 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8494 Trap.hasErrorOccurred()) { 8495 Diag(CurrentLocation, diag::note_member_synthesized_at) 8496 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8497 Constructor->setInvalidDecl(); 8498 return; 8499 } 8500 8501 SourceLocation Loc = Constructor->getLocEnd().isValid() 8502 ? Constructor->getLocEnd() 8503 : Constructor->getLocation(); 8504 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8505 8506 Constructor->markUsed(Context); 8507 MarkVTableUsed(CurrentLocation, ClassDecl); 8508 8509 if (ASTMutationListener *L = getASTMutationListener()) { 8510 L->CompletedImplicitDefinition(Constructor); 8511 } 8512 8513 DiagnoseUninitializedFields(*this, Constructor); 8514 } 8515 8516 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8517 // Perform any delayed checks on exception specifications. 8518 CheckDelayedMemberExceptionSpecs(); 8519 } 8520 8521 namespace { 8522 /// Information on inheriting constructors to declare. 8523 class InheritingConstructorInfo { 8524 public: 8525 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8526 : SemaRef(SemaRef), Derived(Derived) { 8527 // Mark the constructors that we already have in the derived class. 8528 // 8529 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8530 // unless there is a user-declared constructor with the same signature in 8531 // the class where the using-declaration appears. 8532 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8533 } 8534 8535 void inheritAll(CXXRecordDecl *RD) { 8536 visitAll(RD, &InheritingConstructorInfo::inherit); 8537 } 8538 8539 private: 8540 /// Information about an inheriting constructor. 8541 struct InheritingConstructor { 8542 InheritingConstructor() 8543 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {} 8544 8545 /// If \c true, a constructor with this signature is already declared 8546 /// in the derived class. 8547 bool DeclaredInDerived; 8548 8549 /// The constructor which is inherited. 8550 const CXXConstructorDecl *BaseCtor; 8551 8552 /// The derived constructor we declared. 8553 CXXConstructorDecl *DerivedCtor; 8554 }; 8555 8556 /// Inheriting constructors with a given canonical type. There can be at 8557 /// most one such non-template constructor, and any number of templated 8558 /// constructors. 8559 struct InheritingConstructorsForType { 8560 InheritingConstructor NonTemplate; 8561 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 8562 Templates; 8563 8564 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 8565 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 8566 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 8567 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 8568 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 8569 false, S.TPL_TemplateMatch)) 8570 return Templates[I].second; 8571 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 8572 return Templates.back().second; 8573 } 8574 8575 return NonTemplate; 8576 } 8577 }; 8578 8579 /// Get or create the inheriting constructor record for a constructor. 8580 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 8581 QualType CtorType) { 8582 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 8583 .getEntry(SemaRef, Ctor); 8584 } 8585 8586 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 8587 8588 /// Process all constructors for a class. 8589 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 8590 for (const auto *Ctor : RD->ctors()) 8591 (this->*Callback)(Ctor); 8592 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 8593 I(RD->decls_begin()), E(RD->decls_end()); 8594 I != E; ++I) { 8595 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 8596 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 8597 (this->*Callback)(CD); 8598 } 8599 } 8600 8601 /// Note that a constructor (or constructor template) was declared in Derived. 8602 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 8603 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 8604 } 8605 8606 /// Inherit a single constructor. 8607 void inherit(const CXXConstructorDecl *Ctor) { 8608 const FunctionProtoType *CtorType = 8609 Ctor->getType()->castAs<FunctionProtoType>(); 8610 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes()); 8611 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 8612 8613 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 8614 8615 // Core issue (no number yet): the ellipsis is always discarded. 8616 if (EPI.Variadic) { 8617 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 8618 SemaRef.Diag(Ctor->getLocation(), 8619 diag::note_using_decl_constructor_ellipsis); 8620 EPI.Variadic = false; 8621 } 8622 8623 // Declare a constructor for each number of parameters. 8624 // 8625 // C++11 [class.inhctor]p1: 8626 // The candidate set of inherited constructors from the class X named in 8627 // the using-declaration consists of [... modulo defects ...] for each 8628 // constructor or constructor template of X, the set of constructors or 8629 // constructor templates that results from omitting any ellipsis parameter 8630 // specification and successively omitting parameters with a default 8631 // argument from the end of the parameter-type-list 8632 unsigned MinParams = minParamsToInherit(Ctor); 8633 unsigned Params = Ctor->getNumParams(); 8634 if (Params >= MinParams) { 8635 do 8636 declareCtor(UsingLoc, Ctor, 8637 SemaRef.Context.getFunctionType( 8638 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 8639 while (Params > MinParams && 8640 Ctor->getParamDecl(--Params)->hasDefaultArg()); 8641 } 8642 } 8643 8644 /// Find the using-declaration which specified that we should inherit the 8645 /// constructors of \p Base. 8646 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 8647 // No fancy lookup required; just look for the base constructor name 8648 // directly within the derived class. 8649 ASTContext &Context = SemaRef.Context; 8650 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8651 Context.getCanonicalType(Context.getRecordType(Base))); 8652 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 8653 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 8654 } 8655 8656 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 8657 // C++11 [class.inhctor]p3: 8658 // [F]or each constructor template in the candidate set of inherited 8659 // constructors, a constructor template is implicitly declared 8660 if (Ctor->getDescribedFunctionTemplate()) 8661 return 0; 8662 8663 // For each non-template constructor in the candidate set of inherited 8664 // constructors other than a constructor having no parameters or a 8665 // copy/move constructor having a single parameter, a constructor is 8666 // implicitly declared [...] 8667 if (Ctor->getNumParams() == 0) 8668 return 1; 8669 if (Ctor->isCopyOrMoveConstructor()) 8670 return 2; 8671 8672 // Per discussion on core reflector, never inherit a constructor which 8673 // would become a default, copy, or move constructor of Derived either. 8674 const ParmVarDecl *PD = Ctor->getParamDecl(0); 8675 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 8676 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 8677 } 8678 8679 /// Declare a single inheriting constructor, inheriting the specified 8680 /// constructor, with the given type. 8681 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 8682 QualType DerivedType) { 8683 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 8684 8685 // C++11 [class.inhctor]p3: 8686 // ... a constructor is implicitly declared with the same constructor 8687 // characteristics unless there is a user-declared constructor with 8688 // the same signature in the class where the using-declaration appears 8689 if (Entry.DeclaredInDerived) 8690 return; 8691 8692 // C++11 [class.inhctor]p7: 8693 // If two using-declarations declare inheriting constructors with the 8694 // same signature, the program is ill-formed 8695 if (Entry.DerivedCtor) { 8696 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 8697 // Only diagnose this once per constructor. 8698 if (Entry.DerivedCtor->isInvalidDecl()) 8699 return; 8700 Entry.DerivedCtor->setInvalidDecl(); 8701 8702 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 8703 SemaRef.Diag(BaseCtor->getLocation(), 8704 diag::note_using_decl_constructor_conflict_current_ctor); 8705 SemaRef.Diag(Entry.BaseCtor->getLocation(), 8706 diag::note_using_decl_constructor_conflict_previous_ctor); 8707 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 8708 diag::note_using_decl_constructor_conflict_previous_using); 8709 } else { 8710 // Core issue (no number): if the same inheriting constructor is 8711 // produced by multiple base class constructors from the same base 8712 // class, the inheriting constructor is defined as deleted. 8713 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 8714 } 8715 8716 return; 8717 } 8718 8719 ASTContext &Context = SemaRef.Context; 8720 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8721 Context.getCanonicalType(Context.getRecordType(Derived))); 8722 DeclarationNameInfo NameInfo(Name, UsingLoc); 8723 8724 TemplateParameterList *TemplateParams = nullptr; 8725 if (const FunctionTemplateDecl *FTD = 8726 BaseCtor->getDescribedFunctionTemplate()) { 8727 TemplateParams = FTD->getTemplateParameters(); 8728 // We're reusing template parameters from a different DeclContext. This 8729 // is questionable at best, but works out because the template depth in 8730 // both places is guaranteed to be 0. 8731 // FIXME: Rebuild the template parameters in the new context, and 8732 // transform the function type to refer to them. 8733 } 8734 8735 // Build type source info pointing at the using-declaration. This is 8736 // required by template instantiation. 8737 TypeSourceInfo *TInfo = 8738 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 8739 FunctionProtoTypeLoc ProtoLoc = 8740 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 8741 8742 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 8743 Context, Derived, UsingLoc, NameInfo, DerivedType, 8744 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 8745 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 8746 8747 // Build an unevaluated exception specification for this constructor. 8748 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 8749 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8750 EPI.ExceptionSpec.Type = EST_Unevaluated; 8751 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 8752 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 8753 FPT->getParamTypes(), EPI)); 8754 8755 // Build the parameter declarations. 8756 SmallVector<ParmVarDecl *, 16> ParamDecls; 8757 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 8758 TypeSourceInfo *TInfo = 8759 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 8760 ParmVarDecl *PD = ParmVarDecl::Create( 8761 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 8762 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 8763 PD->setScopeInfo(0, I); 8764 PD->setImplicit(); 8765 ParamDecls.push_back(PD); 8766 ProtoLoc.setParam(I, PD); 8767 } 8768 8769 // Set up the new constructor. 8770 DerivedCtor->setAccess(BaseCtor->getAccess()); 8771 DerivedCtor->setParams(ParamDecls); 8772 DerivedCtor->setInheritedConstructor(BaseCtor); 8773 if (BaseCtor->isDeleted()) 8774 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 8775 8776 // If this is a constructor template, build the template declaration. 8777 if (TemplateParams) { 8778 FunctionTemplateDecl *DerivedTemplate = 8779 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 8780 TemplateParams, DerivedCtor); 8781 DerivedTemplate->setAccess(BaseCtor->getAccess()); 8782 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 8783 Derived->addDecl(DerivedTemplate); 8784 } else { 8785 Derived->addDecl(DerivedCtor); 8786 } 8787 8788 Entry.BaseCtor = BaseCtor; 8789 Entry.DerivedCtor = DerivedCtor; 8790 } 8791 8792 Sema &SemaRef; 8793 CXXRecordDecl *Derived; 8794 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 8795 MapType Map; 8796 }; 8797 } 8798 8799 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 8800 // Defer declaring the inheriting constructors until the class is 8801 // instantiated. 8802 if (ClassDecl->isDependentContext()) 8803 return; 8804 8805 // Find base classes from which we might inherit constructors. 8806 SmallVector<CXXRecordDecl*, 4> InheritedBases; 8807 for (const auto &BaseIt : ClassDecl->bases()) 8808 if (BaseIt.getInheritConstructors()) 8809 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl()); 8810 8811 // Go no further if we're not inheriting any constructors. 8812 if (InheritedBases.empty()) 8813 return; 8814 8815 // Declare the inherited constructors. 8816 InheritingConstructorInfo ICI(*this, ClassDecl); 8817 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 8818 ICI.inheritAll(InheritedBases[I]); 8819 } 8820 8821 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 8822 CXXConstructorDecl *Constructor) { 8823 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8824 assert(Constructor->getInheritedConstructor() && 8825 !Constructor->doesThisDeclarationHaveABody() && 8826 !Constructor->isDeleted()); 8827 8828 SynthesizedFunctionScope Scope(*this, Constructor); 8829 DiagnosticErrorTrap Trap(Diags); 8830 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8831 Trap.hasErrorOccurred()) { 8832 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 8833 << Context.getTagDeclType(ClassDecl); 8834 Constructor->setInvalidDecl(); 8835 return; 8836 } 8837 8838 SourceLocation Loc = Constructor->getLocation(); 8839 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8840 8841 Constructor->markUsed(Context); 8842 MarkVTableUsed(CurrentLocation, ClassDecl); 8843 8844 if (ASTMutationListener *L = getASTMutationListener()) { 8845 L->CompletedImplicitDefinition(Constructor); 8846 } 8847 } 8848 8849 8850 Sema::ImplicitExceptionSpecification 8851 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 8852 CXXRecordDecl *ClassDecl = MD->getParent(); 8853 8854 // C++ [except.spec]p14: 8855 // An implicitly declared special member function (Clause 12) shall have 8856 // an exception-specification. 8857 ImplicitExceptionSpecification ExceptSpec(*this); 8858 if (ClassDecl->isInvalidDecl()) 8859 return ExceptSpec; 8860 8861 // Direct base-class destructors. 8862 for (const auto &B : ClassDecl->bases()) { 8863 if (B.isVirtual()) // Handled below. 8864 continue; 8865 8866 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 8867 ExceptSpec.CalledDecl(B.getLocStart(), 8868 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8869 } 8870 8871 // Virtual base-class destructors. 8872 for (const auto &B : ClassDecl->vbases()) { 8873 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 8874 ExceptSpec.CalledDecl(B.getLocStart(), 8875 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8876 } 8877 8878 // Field destructors. 8879 for (const auto *F : ClassDecl->fields()) { 8880 if (const RecordType *RecordTy 8881 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 8882 ExceptSpec.CalledDecl(F->getLocation(), 8883 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 8884 } 8885 8886 return ExceptSpec; 8887 } 8888 8889 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 8890 // C++ [class.dtor]p2: 8891 // If a class has no user-declared destructor, a destructor is 8892 // declared implicitly. An implicitly-declared destructor is an 8893 // inline public member of its class. 8894 assert(ClassDecl->needsImplicitDestructor()); 8895 8896 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 8897 if (DSM.isAlreadyBeingDeclared()) 8898 return nullptr; 8899 8900 // Create the actual destructor declaration. 8901 CanQualType ClassType 8902 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8903 SourceLocation ClassLoc = ClassDecl->getLocation(); 8904 DeclarationName Name 8905 = Context.DeclarationNames.getCXXDestructorName(ClassType); 8906 DeclarationNameInfo NameInfo(Name, ClassLoc); 8907 CXXDestructorDecl *Destructor 8908 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8909 QualType(), nullptr, /*isInline=*/true, 8910 /*isImplicitlyDeclared=*/true); 8911 Destructor->setAccess(AS_public); 8912 Destructor->setDefaulted(); 8913 Destructor->setImplicit(); 8914 8915 // Build an exception specification pointing back at this destructor. 8916 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 8917 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8918 8919 AddOverriddenMethods(ClassDecl, Destructor); 8920 8921 // We don't need to use SpecialMemberIsTrivial here; triviality for 8922 // destructors is easy to compute. 8923 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 8924 8925 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 8926 SetDeclDeleted(Destructor, ClassLoc); 8927 8928 // Note that we have declared this destructor. 8929 ++ASTContext::NumImplicitDestructorsDeclared; 8930 8931 // Introduce this destructor into its scope. 8932 if (Scope *S = getScopeForContext(ClassDecl)) 8933 PushOnScopeChains(Destructor, S, false); 8934 ClassDecl->addDecl(Destructor); 8935 8936 return Destructor; 8937 } 8938 8939 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 8940 CXXDestructorDecl *Destructor) { 8941 assert((Destructor->isDefaulted() && 8942 !Destructor->doesThisDeclarationHaveABody() && 8943 !Destructor->isDeleted()) && 8944 "DefineImplicitDestructor - call it for implicit default dtor"); 8945 CXXRecordDecl *ClassDecl = Destructor->getParent(); 8946 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 8947 8948 if (Destructor->isInvalidDecl()) 8949 return; 8950 8951 SynthesizedFunctionScope Scope(*this, Destructor); 8952 8953 DiagnosticErrorTrap Trap(Diags); 8954 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8955 Destructor->getParent()); 8956 8957 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 8958 Diag(CurrentLocation, diag::note_member_synthesized_at) 8959 << CXXDestructor << Context.getTagDeclType(ClassDecl); 8960 8961 Destructor->setInvalidDecl(); 8962 return; 8963 } 8964 8965 SourceLocation Loc = Destructor->getLocEnd().isValid() 8966 ? Destructor->getLocEnd() 8967 : Destructor->getLocation(); 8968 Destructor->setBody(new (Context) CompoundStmt(Loc)); 8969 Destructor->markUsed(Context); 8970 MarkVTableUsed(CurrentLocation, ClassDecl); 8971 8972 if (ASTMutationListener *L = getASTMutationListener()) { 8973 L->CompletedImplicitDefinition(Destructor); 8974 } 8975 } 8976 8977 /// \brief Perform any semantic analysis which needs to be delayed until all 8978 /// pending class member declarations have been parsed. 8979 void Sema::ActOnFinishCXXMemberDecls() { 8980 // If the context is an invalid C++ class, just suppress these checks. 8981 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 8982 if (Record->isInvalidDecl()) { 8983 DelayedDefaultedMemberExceptionSpecs.clear(); 8984 DelayedDestructorExceptionSpecChecks.clear(); 8985 return; 8986 } 8987 } 8988 } 8989 8990 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 8991 CXXDestructorDecl *Destructor) { 8992 assert(getLangOpts().CPlusPlus11 && 8993 "adjusting dtor exception specs was introduced in c++11"); 8994 8995 // C++11 [class.dtor]p3: 8996 // A declaration of a destructor that does not have an exception- 8997 // specification is implicitly considered to have the same exception- 8998 // specification as an implicit declaration. 8999 const FunctionProtoType *DtorType = Destructor->getType()-> 9000 getAs<FunctionProtoType>(); 9001 if (DtorType->hasExceptionSpec()) 9002 return; 9003 9004 // Replace the destructor's type, building off the existing one. Fortunately, 9005 // the only thing of interest in the destructor type is its extended info. 9006 // The return and arguments are fixed. 9007 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 9008 EPI.ExceptionSpec.Type = EST_Unevaluated; 9009 EPI.ExceptionSpec.SourceDecl = Destructor; 9010 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9011 9012 // FIXME: If the destructor has a body that could throw, and the newly created 9013 // spec doesn't allow exceptions, we should emit a warning, because this 9014 // change in behavior can break conforming C++03 programs at runtime. 9015 // However, we don't have a body or an exception specification yet, so it 9016 // needs to be done somewhere else. 9017 } 9018 9019 namespace { 9020 /// \brief An abstract base class for all helper classes used in building the 9021 // copy/move operators. These classes serve as factory functions and help us 9022 // avoid using the same Expr* in the AST twice. 9023 class ExprBuilder { 9024 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION; 9025 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION; 9026 9027 protected: 9028 static Expr *assertNotNull(Expr *E) { 9029 assert(E && "Expression construction must not fail."); 9030 return E; 9031 } 9032 9033 public: 9034 ExprBuilder() {} 9035 virtual ~ExprBuilder() {} 9036 9037 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 9038 }; 9039 9040 class RefBuilder: public ExprBuilder { 9041 VarDecl *Var; 9042 QualType VarType; 9043 9044 public: 9045 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9046 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 9047 } 9048 9049 RefBuilder(VarDecl *Var, QualType VarType) 9050 : Var(Var), VarType(VarType) {} 9051 }; 9052 9053 class ThisBuilder: public ExprBuilder { 9054 public: 9055 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9056 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 9057 } 9058 }; 9059 9060 class CastBuilder: public ExprBuilder { 9061 const ExprBuilder &Builder; 9062 QualType Type; 9063 ExprValueKind Kind; 9064 const CXXCastPath &Path; 9065 9066 public: 9067 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9068 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 9069 CK_UncheckedDerivedToBase, Kind, 9070 &Path).get()); 9071 } 9072 9073 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 9074 const CXXCastPath &Path) 9075 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 9076 }; 9077 9078 class DerefBuilder: public ExprBuilder { 9079 const ExprBuilder &Builder; 9080 9081 public: 9082 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9083 return assertNotNull( 9084 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 9085 } 9086 9087 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9088 }; 9089 9090 class MemberBuilder: public ExprBuilder { 9091 const ExprBuilder &Builder; 9092 QualType Type; 9093 CXXScopeSpec SS; 9094 bool IsArrow; 9095 LookupResult &MemberLookup; 9096 9097 public: 9098 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9099 return assertNotNull(S.BuildMemberReferenceExpr( 9100 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 9101 nullptr, MemberLookup, nullptr).get()); 9102 } 9103 9104 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 9105 LookupResult &MemberLookup) 9106 : Builder(Builder), Type(Type), IsArrow(IsArrow), 9107 MemberLookup(MemberLookup) {} 9108 }; 9109 9110 class MoveCastBuilder: public ExprBuilder { 9111 const ExprBuilder &Builder; 9112 9113 public: 9114 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9115 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 9116 } 9117 9118 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9119 }; 9120 9121 class LvalueConvBuilder: public ExprBuilder { 9122 const ExprBuilder &Builder; 9123 9124 public: 9125 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9126 return assertNotNull( 9127 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 9128 } 9129 9130 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9131 }; 9132 9133 class SubscriptBuilder: public ExprBuilder { 9134 const ExprBuilder &Base; 9135 const ExprBuilder &Index; 9136 9137 public: 9138 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9139 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 9140 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 9141 } 9142 9143 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 9144 : Base(Base), Index(Index) {} 9145 }; 9146 9147 } // end anonymous namespace 9148 9149 /// When generating a defaulted copy or move assignment operator, if a field 9150 /// should be copied with __builtin_memcpy rather than via explicit assignments, 9151 /// do so. This optimization only applies for arrays of scalars, and for arrays 9152 /// of class type where the selected copy/move-assignment operator is trivial. 9153 static StmtResult 9154 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 9155 const ExprBuilder &ToB, const ExprBuilder &FromB) { 9156 // Compute the size of the memory buffer to be copied. 9157 QualType SizeType = S.Context.getSizeType(); 9158 llvm::APInt Size(S.Context.getTypeSize(SizeType), 9159 S.Context.getTypeSizeInChars(T).getQuantity()); 9160 9161 // Take the address of the field references for "from" and "to". We 9162 // directly construct UnaryOperators here because semantic analysis 9163 // does not permit us to take the address of an xvalue. 9164 Expr *From = FromB.build(S, Loc); 9165 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 9166 S.Context.getPointerType(From->getType()), 9167 VK_RValue, OK_Ordinary, Loc); 9168 Expr *To = ToB.build(S, Loc); 9169 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 9170 S.Context.getPointerType(To->getType()), 9171 VK_RValue, OK_Ordinary, Loc); 9172 9173 const Type *E = T->getBaseElementTypeUnsafe(); 9174 bool NeedsCollectableMemCpy = 9175 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 9176 9177 // Create a reference to the __builtin_objc_memmove_collectable function 9178 StringRef MemCpyName = NeedsCollectableMemCpy ? 9179 "__builtin_objc_memmove_collectable" : 9180 "__builtin_memcpy"; 9181 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 9182 Sema::LookupOrdinaryName); 9183 S.LookupName(R, S.TUScope, true); 9184 9185 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 9186 if (!MemCpy) 9187 // Something went horribly wrong earlier, and we will have complained 9188 // about it. 9189 return StmtError(); 9190 9191 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 9192 VK_RValue, Loc, nullptr); 9193 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 9194 9195 Expr *CallArgs[] = { 9196 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 9197 }; 9198 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 9199 Loc, CallArgs, Loc); 9200 9201 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 9202 return Call.getAs<Stmt>(); 9203 } 9204 9205 /// \brief Builds a statement that copies/moves the given entity from \p From to 9206 /// \c To. 9207 /// 9208 /// This routine is used to copy/move the members of a class with an 9209 /// implicitly-declared copy/move assignment operator. When the entities being 9210 /// copied are arrays, this routine builds for loops to copy them. 9211 /// 9212 /// \param S The Sema object used for type-checking. 9213 /// 9214 /// \param Loc The location where the implicit copy/move is being generated. 9215 /// 9216 /// \param T The type of the expressions being copied/moved. Both expressions 9217 /// must have this type. 9218 /// 9219 /// \param To The expression we are copying/moving to. 9220 /// 9221 /// \param From The expression we are copying/moving from. 9222 /// 9223 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 9224 /// Otherwise, it's a non-static member subobject. 9225 /// 9226 /// \param Copying Whether we're copying or moving. 9227 /// 9228 /// \param Depth Internal parameter recording the depth of the recursion. 9229 /// 9230 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 9231 /// if a memcpy should be used instead. 9232 static StmtResult 9233 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 9234 const ExprBuilder &To, const ExprBuilder &From, 9235 bool CopyingBaseSubobject, bool Copying, 9236 unsigned Depth = 0) { 9237 // C++11 [class.copy]p28: 9238 // Each subobject is assigned in the manner appropriate to its type: 9239 // 9240 // - if the subobject is of class type, as if by a call to operator= with 9241 // the subobject as the object expression and the corresponding 9242 // subobject of x as a single function argument (as if by explicit 9243 // qualification; that is, ignoring any possible virtual overriding 9244 // functions in more derived classes); 9245 // 9246 // C++03 [class.copy]p13: 9247 // - if the subobject is of class type, the copy assignment operator for 9248 // the class is used (as if by explicit qualification; that is, 9249 // ignoring any possible virtual overriding functions in more derived 9250 // classes); 9251 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9252 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9253 9254 // Look for operator=. 9255 DeclarationName Name 9256 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9257 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9258 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9259 9260 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9261 // operator. 9262 if (!S.getLangOpts().CPlusPlus11) { 9263 LookupResult::Filter F = OpLookup.makeFilter(); 9264 while (F.hasNext()) { 9265 NamedDecl *D = F.next(); 9266 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9267 if (Method->isCopyAssignmentOperator() || 9268 (!Copying && Method->isMoveAssignmentOperator())) 9269 continue; 9270 9271 F.erase(); 9272 } 9273 F.done(); 9274 } 9275 9276 // Suppress the protected check (C++ [class.protected]) for each of the 9277 // assignment operators we found. This strange dance is required when 9278 // we're assigning via a base classes's copy-assignment operator. To 9279 // ensure that we're getting the right base class subobject (without 9280 // ambiguities), we need to cast "this" to that subobject type; to 9281 // ensure that we don't go through the virtual call mechanism, we need 9282 // to qualify the operator= name with the base class (see below). However, 9283 // this means that if the base class has a protected copy assignment 9284 // operator, the protected member access check will fail. So, we 9285 // rewrite "protected" access to "public" access in this case, since we 9286 // know by construction that we're calling from a derived class. 9287 if (CopyingBaseSubobject) { 9288 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9289 L != LEnd; ++L) { 9290 if (L.getAccess() == AS_protected) 9291 L.setAccess(AS_public); 9292 } 9293 } 9294 9295 // Create the nested-name-specifier that will be used to qualify the 9296 // reference to operator=; this is required to suppress the virtual 9297 // call mechanism. 9298 CXXScopeSpec SS; 9299 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9300 SS.MakeTrivial(S.Context, 9301 NestedNameSpecifier::Create(S.Context, nullptr, false, 9302 CanonicalT), 9303 Loc); 9304 9305 // Create the reference to operator=. 9306 ExprResult OpEqualRef 9307 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9308 SS, /*TemplateKWLoc=*/SourceLocation(), 9309 /*FirstQualifierInScope=*/nullptr, 9310 OpLookup, 9311 /*TemplateArgs=*/nullptr, 9312 /*SuppressQualifierCheck=*/true); 9313 if (OpEqualRef.isInvalid()) 9314 return StmtError(); 9315 9316 // Build the call to the assignment operator. 9317 9318 Expr *FromInst = From.build(S, Loc); 9319 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 9320 OpEqualRef.getAs<Expr>(), 9321 Loc, FromInst, Loc); 9322 if (Call.isInvalid()) 9323 return StmtError(); 9324 9325 // If we built a call to a trivial 'operator=' while copying an array, 9326 // bail out. We'll replace the whole shebang with a memcpy. 9327 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9328 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9329 return StmtResult((Stmt*)nullptr); 9330 9331 // Convert to an expression-statement, and clean up any produced 9332 // temporaries. 9333 return S.ActOnExprStmt(Call); 9334 } 9335 9336 // - if the subobject is of scalar type, the built-in assignment 9337 // operator is used. 9338 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9339 if (!ArrayTy) { 9340 ExprResult Assignment = S.CreateBuiltinBinOp( 9341 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9342 if (Assignment.isInvalid()) 9343 return StmtError(); 9344 return S.ActOnExprStmt(Assignment); 9345 } 9346 9347 // - if the subobject is an array, each element is assigned, in the 9348 // manner appropriate to the element type; 9349 9350 // Construct a loop over the array bounds, e.g., 9351 // 9352 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9353 // 9354 // that will copy each of the array elements. 9355 QualType SizeType = S.Context.getSizeType(); 9356 9357 // Create the iteration variable. 9358 IdentifierInfo *IterationVarName = nullptr; 9359 { 9360 SmallString<8> Str; 9361 llvm::raw_svector_ostream OS(Str); 9362 OS << "__i" << Depth; 9363 IterationVarName = &S.Context.Idents.get(OS.str()); 9364 } 9365 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9366 IterationVarName, SizeType, 9367 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9368 SC_None); 9369 9370 // Initialize the iteration variable to zero. 9371 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9372 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9373 9374 // Creates a reference to the iteration variable. 9375 RefBuilder IterationVarRef(IterationVar, SizeType); 9376 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9377 9378 // Create the DeclStmt that holds the iteration variable. 9379 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9380 9381 // Subscript the "from" and "to" expressions with the iteration variable. 9382 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9383 MoveCastBuilder FromIndexMove(FromIndexCopy); 9384 const ExprBuilder *FromIndex; 9385 if (Copying) 9386 FromIndex = &FromIndexCopy; 9387 else 9388 FromIndex = &FromIndexMove; 9389 9390 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9391 9392 // Build the copy/move for an individual element of the array. 9393 StmtResult Copy = 9394 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9395 ToIndex, *FromIndex, CopyingBaseSubobject, 9396 Copying, Depth + 1); 9397 // Bail out if copying fails or if we determined that we should use memcpy. 9398 if (Copy.isInvalid() || !Copy.get()) 9399 return Copy; 9400 9401 // Create the comparison against the array bound. 9402 llvm::APInt Upper 9403 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9404 Expr *Comparison 9405 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9406 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9407 BO_NE, S.Context.BoolTy, 9408 VK_RValue, OK_Ordinary, Loc, false); 9409 9410 // Create the pre-increment of the iteration variable. 9411 Expr *Increment 9412 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9413 SizeType, VK_LValue, OK_Ordinary, Loc); 9414 9415 // Construct the loop that copies all elements of this array. 9416 return S.ActOnForStmt(Loc, Loc, InitStmt, 9417 S.MakeFullExpr(Comparison), 9418 nullptr, S.MakeFullDiscardedValueExpr(Increment), 9419 Loc, Copy.get()); 9420 } 9421 9422 static StmtResult 9423 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9424 const ExprBuilder &To, const ExprBuilder &From, 9425 bool CopyingBaseSubobject, bool Copying) { 9426 // Maybe we should use a memcpy? 9427 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9428 T.isTriviallyCopyableType(S.Context)) 9429 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9430 9431 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9432 CopyingBaseSubobject, 9433 Copying, 0)); 9434 9435 // If we ended up picking a trivial assignment operator for an array of a 9436 // non-trivially-copyable class type, just emit a memcpy. 9437 if (!Result.isInvalid() && !Result.get()) 9438 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9439 9440 return Result; 9441 } 9442 9443 Sema::ImplicitExceptionSpecification 9444 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9445 CXXRecordDecl *ClassDecl = MD->getParent(); 9446 9447 ImplicitExceptionSpecification ExceptSpec(*this); 9448 if (ClassDecl->isInvalidDecl()) 9449 return ExceptSpec; 9450 9451 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9452 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9453 unsigned ArgQuals = 9454 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9455 9456 // C++ [except.spec]p14: 9457 // An implicitly declared special member function (Clause 12) shall have an 9458 // exception-specification. [...] 9459 9460 // It is unspecified whether or not an implicit copy assignment operator 9461 // attempts to deduplicate calls to assignment operators of virtual bases are 9462 // made. As such, this exception specification is effectively unspecified. 9463 // Based on a similar decision made for constness in C++0x, we're erring on 9464 // the side of assuming such calls to be made regardless of whether they 9465 // actually happen. 9466 for (const auto &Base : ClassDecl->bases()) { 9467 if (Base.isVirtual()) 9468 continue; 9469 9470 CXXRecordDecl *BaseClassDecl 9471 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9472 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9473 ArgQuals, false, 0)) 9474 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9475 } 9476 9477 for (const auto &Base : ClassDecl->vbases()) { 9478 CXXRecordDecl *BaseClassDecl 9479 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9480 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9481 ArgQuals, false, 0)) 9482 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9483 } 9484 9485 for (const auto *Field : ClassDecl->fields()) { 9486 QualType FieldType = Context.getBaseElementType(Field->getType()); 9487 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9488 if (CXXMethodDecl *CopyAssign = 9489 LookupCopyingAssignment(FieldClassDecl, 9490 ArgQuals | FieldType.getCVRQualifiers(), 9491 false, 0)) 9492 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 9493 } 9494 } 9495 9496 return ExceptSpec; 9497 } 9498 9499 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 9500 // Note: The following rules are largely analoguous to the copy 9501 // constructor rules. Note that virtual bases are not taken into account 9502 // for determining the argument type of the operator. Note also that 9503 // operators taking an object instead of a reference are allowed. 9504 assert(ClassDecl->needsImplicitCopyAssignment()); 9505 9506 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 9507 if (DSM.isAlreadyBeingDeclared()) 9508 return nullptr; 9509 9510 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9511 QualType RetType = Context.getLValueReferenceType(ArgType); 9512 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 9513 if (Const) 9514 ArgType = ArgType.withConst(); 9515 ArgType = Context.getLValueReferenceType(ArgType); 9516 9517 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9518 CXXCopyAssignment, 9519 Const); 9520 9521 // An implicitly-declared copy assignment operator is an inline public 9522 // member of its class. 9523 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9524 SourceLocation ClassLoc = ClassDecl->getLocation(); 9525 DeclarationNameInfo NameInfo(Name, ClassLoc); 9526 CXXMethodDecl *CopyAssignment = 9527 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9528 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 9529 /*isInline=*/true, Constexpr, SourceLocation()); 9530 CopyAssignment->setAccess(AS_public); 9531 CopyAssignment->setDefaulted(); 9532 CopyAssignment->setImplicit(); 9533 9534 // Build an exception specification pointing back at this member. 9535 FunctionProtoType::ExtProtoInfo EPI = 9536 getImplicitMethodEPI(*this, CopyAssignment); 9537 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9538 9539 // Add the parameter to the operator. 9540 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 9541 ClassLoc, ClassLoc, 9542 /*Id=*/nullptr, ArgType, 9543 /*TInfo=*/nullptr, SC_None, 9544 nullptr); 9545 CopyAssignment->setParams(FromParam); 9546 9547 AddOverriddenMethods(ClassDecl, CopyAssignment); 9548 9549 CopyAssignment->setTrivial( 9550 ClassDecl->needsOverloadResolutionForCopyAssignment() 9551 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 9552 : ClassDecl->hasTrivialCopyAssignment()); 9553 9554 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 9555 SetDeclDeleted(CopyAssignment, ClassLoc); 9556 9557 // Note that we have added this copy-assignment operator. 9558 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 9559 9560 if (Scope *S = getScopeForContext(ClassDecl)) 9561 PushOnScopeChains(CopyAssignment, S, false); 9562 ClassDecl->addDecl(CopyAssignment); 9563 9564 return CopyAssignment; 9565 } 9566 9567 /// Diagnose an implicit copy operation for a class which is odr-used, but 9568 /// which is deprecated because the class has a user-declared copy constructor, 9569 /// copy assignment operator, or destructor. 9570 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 9571 SourceLocation UseLoc) { 9572 assert(CopyOp->isImplicit()); 9573 9574 CXXRecordDecl *RD = CopyOp->getParent(); 9575 CXXMethodDecl *UserDeclaredOperation = nullptr; 9576 9577 // In Microsoft mode, assignment operations don't affect constructors and 9578 // vice versa. 9579 if (RD->hasUserDeclaredDestructor()) { 9580 UserDeclaredOperation = RD->getDestructor(); 9581 } else if (!isa<CXXConstructorDecl>(CopyOp) && 9582 RD->hasUserDeclaredCopyConstructor() && 9583 !S.getLangOpts().MSVCCompat) { 9584 // Find any user-declared copy constructor. 9585 for (auto *I : RD->ctors()) { 9586 if (I->isCopyConstructor()) { 9587 UserDeclaredOperation = I; 9588 break; 9589 } 9590 } 9591 assert(UserDeclaredOperation); 9592 } else if (isa<CXXConstructorDecl>(CopyOp) && 9593 RD->hasUserDeclaredCopyAssignment() && 9594 !S.getLangOpts().MSVCCompat) { 9595 // Find any user-declared move assignment operator. 9596 for (auto *I : RD->methods()) { 9597 if (I->isCopyAssignmentOperator()) { 9598 UserDeclaredOperation = I; 9599 break; 9600 } 9601 } 9602 assert(UserDeclaredOperation); 9603 } 9604 9605 if (UserDeclaredOperation) { 9606 S.Diag(UserDeclaredOperation->getLocation(), 9607 diag::warn_deprecated_copy_operation) 9608 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 9609 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 9610 S.Diag(UseLoc, diag::note_member_synthesized_at) 9611 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 9612 : Sema::CXXCopyAssignment) 9613 << RD; 9614 } 9615 } 9616 9617 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 9618 CXXMethodDecl *CopyAssignOperator) { 9619 assert((CopyAssignOperator->isDefaulted() && 9620 CopyAssignOperator->isOverloadedOperator() && 9621 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 9622 !CopyAssignOperator->doesThisDeclarationHaveABody() && 9623 !CopyAssignOperator->isDeleted()) && 9624 "DefineImplicitCopyAssignment called for wrong function"); 9625 9626 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 9627 9628 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 9629 CopyAssignOperator->setInvalidDecl(); 9630 return; 9631 } 9632 9633 // C++11 [class.copy]p18: 9634 // The [definition of an implicitly declared copy assignment operator] is 9635 // deprecated if the class has a user-declared copy constructor or a 9636 // user-declared destructor. 9637 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 9638 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 9639 9640 CopyAssignOperator->markUsed(Context); 9641 9642 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 9643 DiagnosticErrorTrap Trap(Diags); 9644 9645 // C++0x [class.copy]p30: 9646 // The implicitly-defined or explicitly-defaulted copy assignment operator 9647 // for a non-union class X performs memberwise copy assignment of its 9648 // subobjects. The direct base classes of X are assigned first, in the 9649 // order of their declaration in the base-specifier-list, and then the 9650 // immediate non-static data members of X are assigned, in the order in 9651 // which they were declared in the class definition. 9652 9653 // The statements that form the synthesized function body. 9654 SmallVector<Stmt*, 8> Statements; 9655 9656 // The parameter for the "other" object, which we are copying from. 9657 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 9658 Qualifiers OtherQuals = Other->getType().getQualifiers(); 9659 QualType OtherRefType = Other->getType(); 9660 if (const LValueReferenceType *OtherRef 9661 = OtherRefType->getAs<LValueReferenceType>()) { 9662 OtherRefType = OtherRef->getPointeeType(); 9663 OtherQuals = OtherRefType.getQualifiers(); 9664 } 9665 9666 // Our location for everything implicitly-generated. 9667 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 9668 ? CopyAssignOperator->getLocEnd() 9669 : CopyAssignOperator->getLocation(); 9670 9671 // Builds a DeclRefExpr for the "other" object. 9672 RefBuilder OtherRef(Other, OtherRefType); 9673 9674 // Builds the "this" pointer. 9675 ThisBuilder This; 9676 9677 // Assign base classes. 9678 bool Invalid = false; 9679 for (auto &Base : ClassDecl->bases()) { 9680 // Form the assignment: 9681 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 9682 QualType BaseType = Base.getType().getUnqualifiedType(); 9683 if (!BaseType->isRecordType()) { 9684 Invalid = true; 9685 continue; 9686 } 9687 9688 CXXCastPath BasePath; 9689 BasePath.push_back(&Base); 9690 9691 // Construct the "from" expression, which is an implicit cast to the 9692 // appropriately-qualified base type. 9693 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 9694 VK_LValue, BasePath); 9695 9696 // Dereference "this". 9697 DerefBuilder DerefThis(This); 9698 CastBuilder To(DerefThis, 9699 Context.getCVRQualifiedType( 9700 BaseType, CopyAssignOperator->getTypeQualifiers()), 9701 VK_LValue, BasePath); 9702 9703 // Build the copy. 9704 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 9705 To, From, 9706 /*CopyingBaseSubobject=*/true, 9707 /*Copying=*/true); 9708 if (Copy.isInvalid()) { 9709 Diag(CurrentLocation, diag::note_member_synthesized_at) 9710 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9711 CopyAssignOperator->setInvalidDecl(); 9712 return; 9713 } 9714 9715 // Success! Record the copy. 9716 Statements.push_back(Copy.getAs<Expr>()); 9717 } 9718 9719 // Assign non-static members. 9720 for (auto *Field : ClassDecl->fields()) { 9721 if (Field->isUnnamedBitfield()) 9722 continue; 9723 9724 if (Field->isInvalidDecl()) { 9725 Invalid = true; 9726 continue; 9727 } 9728 9729 // Check for members of reference type; we can't copy those. 9730 if (Field->getType()->isReferenceType()) { 9731 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9732 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9733 Diag(Field->getLocation(), diag::note_declared_at); 9734 Diag(CurrentLocation, diag::note_member_synthesized_at) 9735 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9736 Invalid = true; 9737 continue; 9738 } 9739 9740 // Check for members of const-qualified, non-class type. 9741 QualType BaseType = Context.getBaseElementType(Field->getType()); 9742 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9743 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9744 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9745 Diag(Field->getLocation(), diag::note_declared_at); 9746 Diag(CurrentLocation, diag::note_member_synthesized_at) 9747 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9748 Invalid = true; 9749 continue; 9750 } 9751 9752 // Suppress assigning zero-width bitfields. 9753 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9754 continue; 9755 9756 QualType FieldType = Field->getType().getNonReferenceType(); 9757 if (FieldType->isIncompleteArrayType()) { 9758 assert(ClassDecl->hasFlexibleArrayMember() && 9759 "Incomplete array type is not valid"); 9760 continue; 9761 } 9762 9763 // Build references to the field in the object we're copying from and to. 9764 CXXScopeSpec SS; // Intentionally empty 9765 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9766 LookupMemberName); 9767 MemberLookup.addDecl(Field); 9768 MemberLookup.resolveKind(); 9769 9770 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 9771 9772 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 9773 9774 // Build the copy of this field. 9775 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 9776 To, From, 9777 /*CopyingBaseSubobject=*/false, 9778 /*Copying=*/true); 9779 if (Copy.isInvalid()) { 9780 Diag(CurrentLocation, diag::note_member_synthesized_at) 9781 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9782 CopyAssignOperator->setInvalidDecl(); 9783 return; 9784 } 9785 9786 // Success! Record the copy. 9787 Statements.push_back(Copy.getAs<Stmt>()); 9788 } 9789 9790 if (!Invalid) { 9791 // Add a "return *this;" 9792 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 9793 9794 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 9795 if (Return.isInvalid()) 9796 Invalid = true; 9797 else { 9798 Statements.push_back(Return.getAs<Stmt>()); 9799 9800 if (Trap.hasErrorOccurred()) { 9801 Diag(CurrentLocation, diag::note_member_synthesized_at) 9802 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9803 Invalid = true; 9804 } 9805 } 9806 } 9807 9808 if (Invalid) { 9809 CopyAssignOperator->setInvalidDecl(); 9810 return; 9811 } 9812 9813 StmtResult Body; 9814 { 9815 CompoundScopeRAII CompoundScope(*this); 9816 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9817 /*isStmtExpr=*/false); 9818 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9819 } 9820 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 9821 9822 if (ASTMutationListener *L = getASTMutationListener()) { 9823 L->CompletedImplicitDefinition(CopyAssignOperator); 9824 } 9825 } 9826 9827 Sema::ImplicitExceptionSpecification 9828 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 9829 CXXRecordDecl *ClassDecl = MD->getParent(); 9830 9831 ImplicitExceptionSpecification ExceptSpec(*this); 9832 if (ClassDecl->isInvalidDecl()) 9833 return ExceptSpec; 9834 9835 // C++0x [except.spec]p14: 9836 // An implicitly declared special member function (Clause 12) shall have an 9837 // exception-specification. [...] 9838 9839 // It is unspecified whether or not an implicit move assignment operator 9840 // attempts to deduplicate calls to assignment operators of virtual bases are 9841 // made. As such, this exception specification is effectively unspecified. 9842 // Based on a similar decision made for constness in C++0x, we're erring on 9843 // the side of assuming such calls to be made regardless of whether they 9844 // actually happen. 9845 // Note that a move constructor is not implicitly declared when there are 9846 // virtual bases, but it can still be user-declared and explicitly defaulted. 9847 for (const auto &Base : ClassDecl->bases()) { 9848 if (Base.isVirtual()) 9849 continue; 9850 9851 CXXRecordDecl *BaseClassDecl 9852 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9853 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9854 0, false, 0)) 9855 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 9856 } 9857 9858 for (const auto &Base : ClassDecl->vbases()) { 9859 CXXRecordDecl *BaseClassDecl 9860 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9861 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9862 0, false, 0)) 9863 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 9864 } 9865 9866 for (const auto *Field : ClassDecl->fields()) { 9867 QualType FieldType = Context.getBaseElementType(Field->getType()); 9868 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9869 if (CXXMethodDecl *MoveAssign = 9870 LookupMovingAssignment(FieldClassDecl, 9871 FieldType.getCVRQualifiers(), 9872 false, 0)) 9873 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 9874 } 9875 } 9876 9877 return ExceptSpec; 9878 } 9879 9880 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 9881 assert(ClassDecl->needsImplicitMoveAssignment()); 9882 9883 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 9884 if (DSM.isAlreadyBeingDeclared()) 9885 return nullptr; 9886 9887 // Note: The following rules are largely analoguous to the move 9888 // constructor rules. 9889 9890 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9891 QualType RetType = Context.getLValueReferenceType(ArgType); 9892 ArgType = Context.getRValueReferenceType(ArgType); 9893 9894 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9895 CXXMoveAssignment, 9896 false); 9897 9898 // An implicitly-declared move assignment operator is an inline public 9899 // member of its class. 9900 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9901 SourceLocation ClassLoc = ClassDecl->getLocation(); 9902 DeclarationNameInfo NameInfo(Name, ClassLoc); 9903 CXXMethodDecl *MoveAssignment = 9904 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9905 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 9906 /*isInline=*/true, Constexpr, SourceLocation()); 9907 MoveAssignment->setAccess(AS_public); 9908 MoveAssignment->setDefaulted(); 9909 MoveAssignment->setImplicit(); 9910 9911 // Build an exception specification pointing back at this member. 9912 FunctionProtoType::ExtProtoInfo EPI = 9913 getImplicitMethodEPI(*this, MoveAssignment); 9914 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9915 9916 // Add the parameter to the operator. 9917 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 9918 ClassLoc, ClassLoc, 9919 /*Id=*/nullptr, ArgType, 9920 /*TInfo=*/nullptr, SC_None, 9921 nullptr); 9922 MoveAssignment->setParams(FromParam); 9923 9924 AddOverriddenMethods(ClassDecl, MoveAssignment); 9925 9926 MoveAssignment->setTrivial( 9927 ClassDecl->needsOverloadResolutionForMoveAssignment() 9928 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 9929 : ClassDecl->hasTrivialMoveAssignment()); 9930 9931 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 9932 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 9933 SetDeclDeleted(MoveAssignment, ClassLoc); 9934 } 9935 9936 // Note that we have added this copy-assignment operator. 9937 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 9938 9939 if (Scope *S = getScopeForContext(ClassDecl)) 9940 PushOnScopeChains(MoveAssignment, S, false); 9941 ClassDecl->addDecl(MoveAssignment); 9942 9943 return MoveAssignment; 9944 } 9945 9946 /// Check if we're implicitly defining a move assignment operator for a class 9947 /// with virtual bases. Such a move assignment might move-assign the virtual 9948 /// base multiple times. 9949 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 9950 SourceLocation CurrentLocation) { 9951 assert(!Class->isDependentContext() && "should not define dependent move"); 9952 9953 // Only a virtual base could get implicitly move-assigned multiple times. 9954 // Only a non-trivial move assignment can observe this. We only want to 9955 // diagnose if we implicitly define an assignment operator that assigns 9956 // two base classes, both of which move-assign the same virtual base. 9957 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 9958 Class->getNumBases() < 2) 9959 return; 9960 9961 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 9962 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 9963 VBaseMap VBases; 9964 9965 for (auto &BI : Class->bases()) { 9966 Worklist.push_back(&BI); 9967 while (!Worklist.empty()) { 9968 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 9969 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 9970 9971 // If the base has no non-trivial move assignment operators, 9972 // we don't care about moves from it. 9973 if (!Base->hasNonTrivialMoveAssignment()) 9974 continue; 9975 9976 // If there's nothing virtual here, skip it. 9977 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 9978 continue; 9979 9980 // If we're not actually going to call a move assignment for this base, 9981 // or the selected move assignment is trivial, skip it. 9982 Sema::SpecialMemberOverloadResult *SMOR = 9983 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 9984 /*ConstArg*/false, /*VolatileArg*/false, 9985 /*RValueThis*/true, /*ConstThis*/false, 9986 /*VolatileThis*/false); 9987 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 9988 !SMOR->getMethod()->isMoveAssignmentOperator()) 9989 continue; 9990 9991 if (BaseSpec->isVirtual()) { 9992 // We're going to move-assign this virtual base, and its move 9993 // assignment operator is not trivial. If this can happen for 9994 // multiple distinct direct bases of Class, diagnose it. (If it 9995 // only happens in one base, we'll diagnose it when synthesizing 9996 // that base class's move assignment operator.) 9997 CXXBaseSpecifier *&Existing = 9998 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 9999 .first->second; 10000 if (Existing && Existing != &BI) { 10001 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 10002 << Class << Base; 10003 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 10004 << (Base->getCanonicalDecl() == 10005 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10006 << Base << Existing->getType() << Existing->getSourceRange(); 10007 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 10008 << (Base->getCanonicalDecl() == 10009 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10010 << Base << BI.getType() << BaseSpec->getSourceRange(); 10011 10012 // Only diagnose each vbase once. 10013 Existing = nullptr; 10014 } 10015 } else { 10016 // Only walk over bases that have defaulted move assignment operators. 10017 // We assume that any user-provided move assignment operator handles 10018 // the multiple-moves-of-vbase case itself somehow. 10019 if (!SMOR->getMethod()->isDefaulted()) 10020 continue; 10021 10022 // We're going to move the base classes of Base. Add them to the list. 10023 for (auto &BI : Base->bases()) 10024 Worklist.push_back(&BI); 10025 } 10026 } 10027 } 10028 } 10029 10030 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 10031 CXXMethodDecl *MoveAssignOperator) { 10032 assert((MoveAssignOperator->isDefaulted() && 10033 MoveAssignOperator->isOverloadedOperator() && 10034 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 10035 !MoveAssignOperator->doesThisDeclarationHaveABody() && 10036 !MoveAssignOperator->isDeleted()) && 10037 "DefineImplicitMoveAssignment called for wrong function"); 10038 10039 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 10040 10041 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 10042 MoveAssignOperator->setInvalidDecl(); 10043 return; 10044 } 10045 10046 MoveAssignOperator->markUsed(Context); 10047 10048 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 10049 DiagnosticErrorTrap Trap(Diags); 10050 10051 // C++0x [class.copy]p28: 10052 // The implicitly-defined or move assignment operator for a non-union class 10053 // X performs memberwise move assignment of its subobjects. The direct base 10054 // classes of X are assigned first, in the order of their declaration in the 10055 // base-specifier-list, and then the immediate non-static data members of X 10056 // are assigned, in the order in which they were declared in the class 10057 // definition. 10058 10059 // Issue a warning if our implicit move assignment operator will move 10060 // from a virtual base more than once. 10061 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 10062 10063 // The statements that form the synthesized function body. 10064 SmallVector<Stmt*, 8> Statements; 10065 10066 // The parameter for the "other" object, which we are move from. 10067 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 10068 QualType OtherRefType = Other->getType()-> 10069 getAs<RValueReferenceType>()->getPointeeType(); 10070 assert(!OtherRefType.getQualifiers() && 10071 "Bad argument type of defaulted move assignment"); 10072 10073 // Our location for everything implicitly-generated. 10074 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 10075 ? MoveAssignOperator->getLocEnd() 10076 : MoveAssignOperator->getLocation(); 10077 10078 // Builds a reference to the "other" object. 10079 RefBuilder OtherRef(Other, OtherRefType); 10080 // Cast to rvalue. 10081 MoveCastBuilder MoveOther(OtherRef); 10082 10083 // Builds the "this" pointer. 10084 ThisBuilder This; 10085 10086 // Assign base classes. 10087 bool Invalid = false; 10088 for (auto &Base : ClassDecl->bases()) { 10089 // C++11 [class.copy]p28: 10090 // It is unspecified whether subobjects representing virtual base classes 10091 // are assigned more than once by the implicitly-defined copy assignment 10092 // operator. 10093 // FIXME: Do not assign to a vbase that will be assigned by some other base 10094 // class. For a move-assignment, this can result in the vbase being moved 10095 // multiple times. 10096 10097 // Form the assignment: 10098 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 10099 QualType BaseType = Base.getType().getUnqualifiedType(); 10100 if (!BaseType->isRecordType()) { 10101 Invalid = true; 10102 continue; 10103 } 10104 10105 CXXCastPath BasePath; 10106 BasePath.push_back(&Base); 10107 10108 // Construct the "from" expression, which is an implicit cast to the 10109 // appropriately-qualified base type. 10110 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 10111 10112 // Dereference "this". 10113 DerefBuilder DerefThis(This); 10114 10115 // Implicitly cast "this" to the appropriately-qualified base type. 10116 CastBuilder To(DerefThis, 10117 Context.getCVRQualifiedType( 10118 BaseType, MoveAssignOperator->getTypeQualifiers()), 10119 VK_LValue, BasePath); 10120 10121 // Build the move. 10122 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 10123 To, From, 10124 /*CopyingBaseSubobject=*/true, 10125 /*Copying=*/false); 10126 if (Move.isInvalid()) { 10127 Diag(CurrentLocation, diag::note_member_synthesized_at) 10128 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10129 MoveAssignOperator->setInvalidDecl(); 10130 return; 10131 } 10132 10133 // Success! Record the move. 10134 Statements.push_back(Move.getAs<Expr>()); 10135 } 10136 10137 // Assign non-static members. 10138 for (auto *Field : ClassDecl->fields()) { 10139 if (Field->isUnnamedBitfield()) 10140 continue; 10141 10142 if (Field->isInvalidDecl()) { 10143 Invalid = true; 10144 continue; 10145 } 10146 10147 // Check for members of reference type; we can't move those. 10148 if (Field->getType()->isReferenceType()) { 10149 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10150 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10151 Diag(Field->getLocation(), diag::note_declared_at); 10152 Diag(CurrentLocation, diag::note_member_synthesized_at) 10153 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10154 Invalid = true; 10155 continue; 10156 } 10157 10158 // Check for members of const-qualified, non-class type. 10159 QualType BaseType = Context.getBaseElementType(Field->getType()); 10160 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10161 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10162 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10163 Diag(Field->getLocation(), diag::note_declared_at); 10164 Diag(CurrentLocation, diag::note_member_synthesized_at) 10165 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10166 Invalid = true; 10167 continue; 10168 } 10169 10170 // Suppress assigning zero-width bitfields. 10171 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10172 continue; 10173 10174 QualType FieldType = Field->getType().getNonReferenceType(); 10175 if (FieldType->isIncompleteArrayType()) { 10176 assert(ClassDecl->hasFlexibleArrayMember() && 10177 "Incomplete array type is not valid"); 10178 continue; 10179 } 10180 10181 // Build references to the field in the object we're copying from and to. 10182 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10183 LookupMemberName); 10184 MemberLookup.addDecl(Field); 10185 MemberLookup.resolveKind(); 10186 MemberBuilder From(MoveOther, OtherRefType, 10187 /*IsArrow=*/false, MemberLookup); 10188 MemberBuilder To(This, getCurrentThisType(), 10189 /*IsArrow=*/true, MemberLookup); 10190 10191 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 10192 "Member reference with rvalue base must be rvalue except for reference " 10193 "members, which aren't allowed for move assignment."); 10194 10195 // Build the move of this field. 10196 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 10197 To, From, 10198 /*CopyingBaseSubobject=*/false, 10199 /*Copying=*/false); 10200 if (Move.isInvalid()) { 10201 Diag(CurrentLocation, diag::note_member_synthesized_at) 10202 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10203 MoveAssignOperator->setInvalidDecl(); 10204 return; 10205 } 10206 10207 // Success! Record the copy. 10208 Statements.push_back(Move.getAs<Stmt>()); 10209 } 10210 10211 if (!Invalid) { 10212 // Add a "return *this;" 10213 ExprResult ThisObj = 10214 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10215 10216 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10217 if (Return.isInvalid()) 10218 Invalid = true; 10219 else { 10220 Statements.push_back(Return.getAs<Stmt>()); 10221 10222 if (Trap.hasErrorOccurred()) { 10223 Diag(CurrentLocation, diag::note_member_synthesized_at) 10224 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10225 Invalid = true; 10226 } 10227 } 10228 } 10229 10230 if (Invalid) { 10231 MoveAssignOperator->setInvalidDecl(); 10232 return; 10233 } 10234 10235 StmtResult Body; 10236 { 10237 CompoundScopeRAII CompoundScope(*this); 10238 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10239 /*isStmtExpr=*/false); 10240 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10241 } 10242 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 10243 10244 if (ASTMutationListener *L = getASTMutationListener()) { 10245 L->CompletedImplicitDefinition(MoveAssignOperator); 10246 } 10247 } 10248 10249 Sema::ImplicitExceptionSpecification 10250 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10251 CXXRecordDecl *ClassDecl = MD->getParent(); 10252 10253 ImplicitExceptionSpecification ExceptSpec(*this); 10254 if (ClassDecl->isInvalidDecl()) 10255 return ExceptSpec; 10256 10257 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10258 assert(T->getNumParams() >= 1 && "not a copy ctor"); 10259 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10260 10261 // C++ [except.spec]p14: 10262 // An implicitly declared special member function (Clause 12) shall have an 10263 // exception-specification. [...] 10264 for (const auto &Base : ClassDecl->bases()) { 10265 // Virtual bases are handled below. 10266 if (Base.isVirtual()) 10267 continue; 10268 10269 CXXRecordDecl *BaseClassDecl 10270 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10271 if (CXXConstructorDecl *CopyConstructor = 10272 LookupCopyingConstructor(BaseClassDecl, Quals)) 10273 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10274 } 10275 for (const auto &Base : ClassDecl->vbases()) { 10276 CXXRecordDecl *BaseClassDecl 10277 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10278 if (CXXConstructorDecl *CopyConstructor = 10279 LookupCopyingConstructor(BaseClassDecl, Quals)) 10280 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10281 } 10282 for (const auto *Field : ClassDecl->fields()) { 10283 QualType FieldType = Context.getBaseElementType(Field->getType()); 10284 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10285 if (CXXConstructorDecl *CopyConstructor = 10286 LookupCopyingConstructor(FieldClassDecl, 10287 Quals | FieldType.getCVRQualifiers())) 10288 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10289 } 10290 } 10291 10292 return ExceptSpec; 10293 } 10294 10295 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10296 CXXRecordDecl *ClassDecl) { 10297 // C++ [class.copy]p4: 10298 // If the class definition does not explicitly declare a copy 10299 // constructor, one is declared implicitly. 10300 assert(ClassDecl->needsImplicitCopyConstructor()); 10301 10302 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10303 if (DSM.isAlreadyBeingDeclared()) 10304 return nullptr; 10305 10306 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10307 QualType ArgType = ClassType; 10308 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10309 if (Const) 10310 ArgType = ArgType.withConst(); 10311 ArgType = Context.getLValueReferenceType(ArgType); 10312 10313 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10314 CXXCopyConstructor, 10315 Const); 10316 10317 DeclarationName Name 10318 = Context.DeclarationNames.getCXXConstructorName( 10319 Context.getCanonicalType(ClassType)); 10320 SourceLocation ClassLoc = ClassDecl->getLocation(); 10321 DeclarationNameInfo NameInfo(Name, ClassLoc); 10322 10323 // An implicitly-declared copy constructor is an inline public 10324 // member of its class. 10325 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10326 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10327 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10328 Constexpr); 10329 CopyConstructor->setAccess(AS_public); 10330 CopyConstructor->setDefaulted(); 10331 10332 // Build an exception specification pointing back at this member. 10333 FunctionProtoType::ExtProtoInfo EPI = 10334 getImplicitMethodEPI(*this, CopyConstructor); 10335 CopyConstructor->setType( 10336 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10337 10338 // Add the parameter to the constructor. 10339 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10340 ClassLoc, ClassLoc, 10341 /*IdentifierInfo=*/nullptr, 10342 ArgType, /*TInfo=*/nullptr, 10343 SC_None, nullptr); 10344 CopyConstructor->setParams(FromParam); 10345 10346 CopyConstructor->setTrivial( 10347 ClassDecl->needsOverloadResolutionForCopyConstructor() 10348 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10349 : ClassDecl->hasTrivialCopyConstructor()); 10350 10351 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10352 SetDeclDeleted(CopyConstructor, ClassLoc); 10353 10354 // Note that we have declared this constructor. 10355 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10356 10357 if (Scope *S = getScopeForContext(ClassDecl)) 10358 PushOnScopeChains(CopyConstructor, S, false); 10359 ClassDecl->addDecl(CopyConstructor); 10360 10361 return CopyConstructor; 10362 } 10363 10364 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10365 CXXConstructorDecl *CopyConstructor) { 10366 assert((CopyConstructor->isDefaulted() && 10367 CopyConstructor->isCopyConstructor() && 10368 !CopyConstructor->doesThisDeclarationHaveABody() && 10369 !CopyConstructor->isDeleted()) && 10370 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10371 10372 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10373 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10374 10375 // C++11 [class.copy]p7: 10376 // The [definition of an implicitly declared copy constructor] is 10377 // deprecated if the class has a user-declared copy assignment operator 10378 // or a user-declared destructor. 10379 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10380 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10381 10382 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10383 DiagnosticErrorTrap Trap(Diags); 10384 10385 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10386 Trap.hasErrorOccurred()) { 10387 Diag(CurrentLocation, diag::note_member_synthesized_at) 10388 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10389 CopyConstructor->setInvalidDecl(); 10390 } else { 10391 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 10392 ? CopyConstructor->getLocEnd() 10393 : CopyConstructor->getLocation(); 10394 Sema::CompoundScopeRAII CompoundScope(*this); 10395 CopyConstructor->setBody( 10396 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 10397 } 10398 10399 CopyConstructor->markUsed(Context); 10400 MarkVTableUsed(CurrentLocation, ClassDecl); 10401 10402 if (ASTMutationListener *L = getASTMutationListener()) { 10403 L->CompletedImplicitDefinition(CopyConstructor); 10404 } 10405 } 10406 10407 Sema::ImplicitExceptionSpecification 10408 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10409 CXXRecordDecl *ClassDecl = MD->getParent(); 10410 10411 // C++ [except.spec]p14: 10412 // An implicitly declared special member function (Clause 12) shall have an 10413 // exception-specification. [...] 10414 ImplicitExceptionSpecification ExceptSpec(*this); 10415 if (ClassDecl->isInvalidDecl()) 10416 return ExceptSpec; 10417 10418 // Direct base-class constructors. 10419 for (const auto &B : ClassDecl->bases()) { 10420 if (B.isVirtual()) // Handled below. 10421 continue; 10422 10423 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10424 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10425 CXXConstructorDecl *Constructor = 10426 LookupMovingConstructor(BaseClassDecl, 0); 10427 // If this is a deleted function, add it anyway. This might be conformant 10428 // with the standard. This might not. I'm not sure. It might not matter. 10429 if (Constructor) 10430 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10431 } 10432 } 10433 10434 // Virtual base-class constructors. 10435 for (const auto &B : ClassDecl->vbases()) { 10436 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10437 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10438 CXXConstructorDecl *Constructor = 10439 LookupMovingConstructor(BaseClassDecl, 0); 10440 // If this is a deleted function, add it anyway. This might be conformant 10441 // with the standard. This might not. I'm not sure. It might not matter. 10442 if (Constructor) 10443 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10444 } 10445 } 10446 10447 // Field constructors. 10448 for (const auto *F : ClassDecl->fields()) { 10449 QualType FieldType = Context.getBaseElementType(F->getType()); 10450 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 10451 CXXConstructorDecl *Constructor = 10452 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 10453 // If this is a deleted function, add it anyway. This might be conformant 10454 // with the standard. This might not. I'm not sure. It might not matter. 10455 // In particular, the problem is that this function never gets called. It 10456 // might just be ill-formed because this function attempts to refer to 10457 // a deleted function here. 10458 if (Constructor) 10459 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 10460 } 10461 } 10462 10463 return ExceptSpec; 10464 } 10465 10466 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 10467 CXXRecordDecl *ClassDecl) { 10468 assert(ClassDecl->needsImplicitMoveConstructor()); 10469 10470 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 10471 if (DSM.isAlreadyBeingDeclared()) 10472 return nullptr; 10473 10474 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10475 QualType ArgType = Context.getRValueReferenceType(ClassType); 10476 10477 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10478 CXXMoveConstructor, 10479 false); 10480 10481 DeclarationName Name 10482 = Context.DeclarationNames.getCXXConstructorName( 10483 Context.getCanonicalType(ClassType)); 10484 SourceLocation ClassLoc = ClassDecl->getLocation(); 10485 DeclarationNameInfo NameInfo(Name, ClassLoc); 10486 10487 // C++11 [class.copy]p11: 10488 // An implicitly-declared copy/move constructor is an inline public 10489 // member of its class. 10490 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 10491 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10492 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10493 Constexpr); 10494 MoveConstructor->setAccess(AS_public); 10495 MoveConstructor->setDefaulted(); 10496 10497 // Build an exception specification pointing back at this member. 10498 FunctionProtoType::ExtProtoInfo EPI = 10499 getImplicitMethodEPI(*this, MoveConstructor); 10500 MoveConstructor->setType( 10501 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10502 10503 // Add the parameter to the constructor. 10504 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 10505 ClassLoc, ClassLoc, 10506 /*IdentifierInfo=*/nullptr, 10507 ArgType, /*TInfo=*/nullptr, 10508 SC_None, nullptr); 10509 MoveConstructor->setParams(FromParam); 10510 10511 MoveConstructor->setTrivial( 10512 ClassDecl->needsOverloadResolutionForMoveConstructor() 10513 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 10514 : ClassDecl->hasTrivialMoveConstructor()); 10515 10516 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 10517 ClassDecl->setImplicitMoveConstructorIsDeleted(); 10518 SetDeclDeleted(MoveConstructor, ClassLoc); 10519 } 10520 10521 // Note that we have declared this constructor. 10522 ++ASTContext::NumImplicitMoveConstructorsDeclared; 10523 10524 if (Scope *S = getScopeForContext(ClassDecl)) 10525 PushOnScopeChains(MoveConstructor, S, false); 10526 ClassDecl->addDecl(MoveConstructor); 10527 10528 return MoveConstructor; 10529 } 10530 10531 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 10532 CXXConstructorDecl *MoveConstructor) { 10533 assert((MoveConstructor->isDefaulted() && 10534 MoveConstructor->isMoveConstructor() && 10535 !MoveConstructor->doesThisDeclarationHaveABody() && 10536 !MoveConstructor->isDeleted()) && 10537 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 10538 10539 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 10540 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 10541 10542 SynthesizedFunctionScope Scope(*this, MoveConstructor); 10543 DiagnosticErrorTrap Trap(Diags); 10544 10545 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 10546 Trap.hasErrorOccurred()) { 10547 Diag(CurrentLocation, diag::note_member_synthesized_at) 10548 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 10549 MoveConstructor->setInvalidDecl(); 10550 } else { 10551 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 10552 ? MoveConstructor->getLocEnd() 10553 : MoveConstructor->getLocation(); 10554 Sema::CompoundScopeRAII CompoundScope(*this); 10555 MoveConstructor->setBody(ActOnCompoundStmt( 10556 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 10557 } 10558 10559 MoveConstructor->markUsed(Context); 10560 MarkVTableUsed(CurrentLocation, ClassDecl); 10561 10562 if (ASTMutationListener *L = getASTMutationListener()) { 10563 L->CompletedImplicitDefinition(MoveConstructor); 10564 } 10565 } 10566 10567 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 10568 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 10569 } 10570 10571 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 10572 SourceLocation CurrentLocation, 10573 CXXConversionDecl *Conv) { 10574 CXXRecordDecl *Lambda = Conv->getParent(); 10575 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 10576 // If we are defining a specialization of a conversion to function-ptr 10577 // cache the deduced template arguments for this specialization 10578 // so that we can use them to retrieve the corresponding call-operator 10579 // and static-invoker. 10580 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 10581 10582 // Retrieve the corresponding call-operator specialization. 10583 if (Lambda->isGenericLambda()) { 10584 assert(Conv->isFunctionTemplateSpecialization()); 10585 FunctionTemplateDecl *CallOpTemplate = 10586 CallOp->getDescribedFunctionTemplate(); 10587 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 10588 void *InsertPos = nullptr; 10589 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 10590 DeducedTemplateArgs->asArray(), 10591 InsertPos); 10592 assert(CallOpSpec && 10593 "Conversion operator must have a corresponding call operator"); 10594 CallOp = cast<CXXMethodDecl>(CallOpSpec); 10595 } 10596 // Mark the call operator referenced (and add to pending instantiations 10597 // if necessary). 10598 // For both the conversion and static-invoker template specializations 10599 // we construct their body's in this function, so no need to add them 10600 // to the PendingInstantiations. 10601 MarkFunctionReferenced(CurrentLocation, CallOp); 10602 10603 SynthesizedFunctionScope Scope(*this, Conv); 10604 DiagnosticErrorTrap Trap(Diags); 10605 10606 // Retrieve the static invoker... 10607 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 10608 // ... and get the corresponding specialization for a generic lambda. 10609 if (Lambda->isGenericLambda()) { 10610 assert(DeducedTemplateArgs && 10611 "Must have deduced template arguments from Conversion Operator"); 10612 FunctionTemplateDecl *InvokeTemplate = 10613 Invoker->getDescribedFunctionTemplate(); 10614 void *InsertPos = nullptr; 10615 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 10616 DeducedTemplateArgs->asArray(), 10617 InsertPos); 10618 assert(InvokeSpec && 10619 "Must have a corresponding static invoker specialization"); 10620 Invoker = cast<CXXMethodDecl>(InvokeSpec); 10621 } 10622 // Construct the body of the conversion function { return __invoke; }. 10623 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 10624 VK_LValue, Conv->getLocation()).get(); 10625 assert(FunctionRef && "Can't refer to __invoke function?"); 10626 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 10627 Conv->setBody(new (Context) CompoundStmt(Context, Return, 10628 Conv->getLocation(), 10629 Conv->getLocation())); 10630 10631 Conv->markUsed(Context); 10632 Conv->setReferenced(); 10633 10634 // Fill in the __invoke function with a dummy implementation. IR generation 10635 // will fill in the actual details. 10636 Invoker->markUsed(Context); 10637 Invoker->setReferenced(); 10638 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 10639 10640 if (ASTMutationListener *L = getASTMutationListener()) { 10641 L->CompletedImplicitDefinition(Conv); 10642 L->CompletedImplicitDefinition(Invoker); 10643 } 10644 } 10645 10646 10647 10648 void Sema::DefineImplicitLambdaToBlockPointerConversion( 10649 SourceLocation CurrentLocation, 10650 CXXConversionDecl *Conv) 10651 { 10652 assert(!Conv->getParent()->isGenericLambda()); 10653 10654 Conv->markUsed(Context); 10655 10656 SynthesizedFunctionScope Scope(*this, Conv); 10657 DiagnosticErrorTrap Trap(Diags); 10658 10659 // Copy-initialize the lambda object as needed to capture it. 10660 Expr *This = ActOnCXXThis(CurrentLocation).get(); 10661 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 10662 10663 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 10664 Conv->getLocation(), 10665 Conv, DerefThis); 10666 10667 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 10668 // behavior. Note that only the general conversion function does this 10669 // (since it's unusable otherwise); in the case where we inline the 10670 // block literal, it has block literal lifetime semantics. 10671 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 10672 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 10673 CK_CopyAndAutoreleaseBlockObject, 10674 BuildBlock.get(), nullptr, VK_RValue); 10675 10676 if (BuildBlock.isInvalid()) { 10677 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10678 Conv->setInvalidDecl(); 10679 return; 10680 } 10681 10682 // Create the return statement that returns the block from the conversion 10683 // function. 10684 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 10685 if (Return.isInvalid()) { 10686 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10687 Conv->setInvalidDecl(); 10688 return; 10689 } 10690 10691 // Set the body of the conversion function. 10692 Stmt *ReturnS = Return.get(); 10693 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 10694 Conv->getLocation(), 10695 Conv->getLocation())); 10696 10697 // We're done; notify the mutation listener, if any. 10698 if (ASTMutationListener *L = getASTMutationListener()) { 10699 L->CompletedImplicitDefinition(Conv); 10700 } 10701 } 10702 10703 /// \brief Determine whether the given list arguments contains exactly one 10704 /// "real" (non-default) argument. 10705 static bool hasOneRealArgument(MultiExprArg Args) { 10706 switch (Args.size()) { 10707 case 0: 10708 return false; 10709 10710 default: 10711 if (!Args[1]->isDefaultArgument()) 10712 return false; 10713 10714 // fall through 10715 case 1: 10716 return !Args[0]->isDefaultArgument(); 10717 } 10718 10719 return false; 10720 } 10721 10722 ExprResult 10723 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10724 CXXConstructorDecl *Constructor, 10725 MultiExprArg ExprArgs, 10726 bool HadMultipleCandidates, 10727 bool IsListInitialization, 10728 bool IsStdInitListInitialization, 10729 bool RequiresZeroInit, 10730 unsigned ConstructKind, 10731 SourceRange ParenRange) { 10732 bool Elidable = false; 10733 10734 // C++0x [class.copy]p34: 10735 // When certain criteria are met, an implementation is allowed to 10736 // omit the copy/move construction of a class object, even if the 10737 // copy/move constructor and/or destructor for the object have 10738 // side effects. [...] 10739 // - when a temporary class object that has not been bound to a 10740 // reference (12.2) would be copied/moved to a class object 10741 // with the same cv-unqualified type, the copy/move operation 10742 // can be omitted by constructing the temporary object 10743 // directly into the target of the omitted copy/move 10744 if (ConstructKind == CXXConstructExpr::CK_Complete && 10745 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 10746 Expr *SubExpr = ExprArgs[0]; 10747 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 10748 } 10749 10750 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 10751 Elidable, ExprArgs, HadMultipleCandidates, 10752 IsListInitialization, 10753 IsStdInitListInitialization, RequiresZeroInit, 10754 ConstructKind, ParenRange); 10755 } 10756 10757 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 10758 /// including handling of its default argument expressions. 10759 ExprResult 10760 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10761 CXXConstructorDecl *Constructor, bool Elidable, 10762 MultiExprArg ExprArgs, 10763 bool HadMultipleCandidates, 10764 bool IsListInitialization, 10765 bool IsStdInitListInitialization, 10766 bool RequiresZeroInit, 10767 unsigned ConstructKind, 10768 SourceRange ParenRange) { 10769 MarkFunctionReferenced(ConstructLoc, Constructor); 10770 return CXXConstructExpr::Create( 10771 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 10772 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 10773 RequiresZeroInit, 10774 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 10775 ParenRange); 10776 } 10777 10778 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 10779 if (VD->isInvalidDecl()) return; 10780 10781 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 10782 if (ClassDecl->isInvalidDecl()) return; 10783 if (ClassDecl->hasIrrelevantDestructor()) return; 10784 if (ClassDecl->isDependentContext()) return; 10785 10786 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10787 MarkFunctionReferenced(VD->getLocation(), Destructor); 10788 CheckDestructorAccess(VD->getLocation(), Destructor, 10789 PDiag(diag::err_access_dtor_var) 10790 << VD->getDeclName() 10791 << VD->getType()); 10792 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 10793 10794 if (Destructor->isTrivial()) return; 10795 if (!VD->hasGlobalStorage()) return; 10796 10797 // Emit warning for non-trivial dtor in global scope (a real global, 10798 // class-static, function-static). 10799 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 10800 10801 // TODO: this should be re-enabled for static locals by !CXAAtExit 10802 if (!VD->isStaticLocal()) 10803 Diag(VD->getLocation(), diag::warn_global_destructor); 10804 } 10805 10806 /// \brief Given a constructor and the set of arguments provided for the 10807 /// constructor, convert the arguments and add any required default arguments 10808 /// to form a proper call to this constructor. 10809 /// 10810 /// \returns true if an error occurred, false otherwise. 10811 bool 10812 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 10813 MultiExprArg ArgsPtr, 10814 SourceLocation Loc, 10815 SmallVectorImpl<Expr*> &ConvertedArgs, 10816 bool AllowExplicit, 10817 bool IsListInitialization) { 10818 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 10819 unsigned NumArgs = ArgsPtr.size(); 10820 Expr **Args = ArgsPtr.data(); 10821 10822 const FunctionProtoType *Proto 10823 = Constructor->getType()->getAs<FunctionProtoType>(); 10824 assert(Proto && "Constructor without a prototype?"); 10825 unsigned NumParams = Proto->getNumParams(); 10826 10827 // If too few arguments are available, we'll fill in the rest with defaults. 10828 if (NumArgs < NumParams) 10829 ConvertedArgs.reserve(NumParams); 10830 else 10831 ConvertedArgs.reserve(NumArgs); 10832 10833 VariadicCallType CallType = 10834 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 10835 SmallVector<Expr *, 8> AllArgs; 10836 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 10837 Proto, 0, 10838 llvm::makeArrayRef(Args, NumArgs), 10839 AllArgs, 10840 CallType, AllowExplicit, 10841 IsListInitialization); 10842 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 10843 10844 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 10845 10846 CheckConstructorCall(Constructor, 10847 llvm::makeArrayRef<const Expr *>(AllArgs.data(), 10848 AllArgs.size()), 10849 Proto, Loc); 10850 10851 return Invalid; 10852 } 10853 10854 static inline bool 10855 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 10856 const FunctionDecl *FnDecl) { 10857 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 10858 if (isa<NamespaceDecl>(DC)) { 10859 return SemaRef.Diag(FnDecl->getLocation(), 10860 diag::err_operator_new_delete_declared_in_namespace) 10861 << FnDecl->getDeclName(); 10862 } 10863 10864 if (isa<TranslationUnitDecl>(DC) && 10865 FnDecl->getStorageClass() == SC_Static) { 10866 return SemaRef.Diag(FnDecl->getLocation(), 10867 diag::err_operator_new_delete_declared_static) 10868 << FnDecl->getDeclName(); 10869 } 10870 10871 return false; 10872 } 10873 10874 static inline bool 10875 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 10876 CanQualType ExpectedResultType, 10877 CanQualType ExpectedFirstParamType, 10878 unsigned DependentParamTypeDiag, 10879 unsigned InvalidParamTypeDiag) { 10880 QualType ResultType = 10881 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 10882 10883 // Check that the result type is not dependent. 10884 if (ResultType->isDependentType()) 10885 return SemaRef.Diag(FnDecl->getLocation(), 10886 diag::err_operator_new_delete_dependent_result_type) 10887 << FnDecl->getDeclName() << ExpectedResultType; 10888 10889 // Check that the result type is what we expect. 10890 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 10891 return SemaRef.Diag(FnDecl->getLocation(), 10892 diag::err_operator_new_delete_invalid_result_type) 10893 << FnDecl->getDeclName() << ExpectedResultType; 10894 10895 // A function template must have at least 2 parameters. 10896 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 10897 return SemaRef.Diag(FnDecl->getLocation(), 10898 diag::err_operator_new_delete_template_too_few_parameters) 10899 << FnDecl->getDeclName(); 10900 10901 // The function decl must have at least 1 parameter. 10902 if (FnDecl->getNumParams() == 0) 10903 return SemaRef.Diag(FnDecl->getLocation(), 10904 diag::err_operator_new_delete_too_few_parameters) 10905 << FnDecl->getDeclName(); 10906 10907 // Check the first parameter type is not dependent. 10908 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 10909 if (FirstParamType->isDependentType()) 10910 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 10911 << FnDecl->getDeclName() << ExpectedFirstParamType; 10912 10913 // Check that the first parameter type is what we expect. 10914 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 10915 ExpectedFirstParamType) 10916 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 10917 << FnDecl->getDeclName() << ExpectedFirstParamType; 10918 10919 return false; 10920 } 10921 10922 static bool 10923 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 10924 // C++ [basic.stc.dynamic.allocation]p1: 10925 // A program is ill-formed if an allocation function is declared in a 10926 // namespace scope other than global scope or declared static in global 10927 // scope. 10928 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10929 return true; 10930 10931 CanQualType SizeTy = 10932 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 10933 10934 // C++ [basic.stc.dynamic.allocation]p1: 10935 // The return type shall be void*. The first parameter shall have type 10936 // std::size_t. 10937 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 10938 SizeTy, 10939 diag::err_operator_new_dependent_param_type, 10940 diag::err_operator_new_param_type)) 10941 return true; 10942 10943 // C++ [basic.stc.dynamic.allocation]p1: 10944 // The first parameter shall not have an associated default argument. 10945 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 10946 return SemaRef.Diag(FnDecl->getLocation(), 10947 diag::err_operator_new_default_arg) 10948 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 10949 10950 return false; 10951 } 10952 10953 static bool 10954 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 10955 // C++ [basic.stc.dynamic.deallocation]p1: 10956 // A program is ill-formed if deallocation functions are declared in a 10957 // namespace scope other than global scope or declared static in global 10958 // scope. 10959 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10960 return true; 10961 10962 // C++ [basic.stc.dynamic.deallocation]p2: 10963 // Each deallocation function shall return void and its first parameter 10964 // shall be void*. 10965 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 10966 SemaRef.Context.VoidPtrTy, 10967 diag::err_operator_delete_dependent_param_type, 10968 diag::err_operator_delete_param_type)) 10969 return true; 10970 10971 return false; 10972 } 10973 10974 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 10975 /// of this overloaded operator is well-formed. If so, returns false; 10976 /// otherwise, emits appropriate diagnostics and returns true. 10977 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 10978 assert(FnDecl && FnDecl->isOverloadedOperator() && 10979 "Expected an overloaded operator declaration"); 10980 10981 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 10982 10983 // C++ [over.oper]p5: 10984 // The allocation and deallocation functions, operator new, 10985 // operator new[], operator delete and operator delete[], are 10986 // described completely in 3.7.3. The attributes and restrictions 10987 // found in the rest of this subclause do not apply to them unless 10988 // explicitly stated in 3.7.3. 10989 if (Op == OO_Delete || Op == OO_Array_Delete) 10990 return CheckOperatorDeleteDeclaration(*this, FnDecl); 10991 10992 if (Op == OO_New || Op == OO_Array_New) 10993 return CheckOperatorNewDeclaration(*this, FnDecl); 10994 10995 // C++ [over.oper]p6: 10996 // An operator function shall either be a non-static member 10997 // function or be a non-member function and have at least one 10998 // parameter whose type is a class, a reference to a class, an 10999 // enumeration, or a reference to an enumeration. 11000 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 11001 if (MethodDecl->isStatic()) 11002 return Diag(FnDecl->getLocation(), 11003 diag::err_operator_overload_static) << FnDecl->getDeclName(); 11004 } else { 11005 bool ClassOrEnumParam = false; 11006 for (auto Param : FnDecl->params()) { 11007 QualType ParamType = Param->getType().getNonReferenceType(); 11008 if (ParamType->isDependentType() || ParamType->isRecordType() || 11009 ParamType->isEnumeralType()) { 11010 ClassOrEnumParam = true; 11011 break; 11012 } 11013 } 11014 11015 if (!ClassOrEnumParam) 11016 return Diag(FnDecl->getLocation(), 11017 diag::err_operator_overload_needs_class_or_enum) 11018 << FnDecl->getDeclName(); 11019 } 11020 11021 // C++ [over.oper]p8: 11022 // An operator function cannot have default arguments (8.3.6), 11023 // except where explicitly stated below. 11024 // 11025 // Only the function-call operator allows default arguments 11026 // (C++ [over.call]p1). 11027 if (Op != OO_Call) { 11028 for (auto Param : FnDecl->params()) { 11029 if (Param->hasDefaultArg()) 11030 return Diag(Param->getLocation(), 11031 diag::err_operator_overload_default_arg) 11032 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 11033 } 11034 } 11035 11036 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 11037 { false, false, false } 11038 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 11039 , { Unary, Binary, MemberOnly } 11040 #include "clang/Basic/OperatorKinds.def" 11041 }; 11042 11043 bool CanBeUnaryOperator = OperatorUses[Op][0]; 11044 bool CanBeBinaryOperator = OperatorUses[Op][1]; 11045 bool MustBeMemberOperator = OperatorUses[Op][2]; 11046 11047 // C++ [over.oper]p8: 11048 // [...] Operator functions cannot have more or fewer parameters 11049 // than the number required for the corresponding operator, as 11050 // described in the rest of this subclause. 11051 unsigned NumParams = FnDecl->getNumParams() 11052 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 11053 if (Op != OO_Call && 11054 ((NumParams == 1 && !CanBeUnaryOperator) || 11055 (NumParams == 2 && !CanBeBinaryOperator) || 11056 (NumParams < 1) || (NumParams > 2))) { 11057 // We have the wrong number of parameters. 11058 unsigned ErrorKind; 11059 if (CanBeUnaryOperator && CanBeBinaryOperator) { 11060 ErrorKind = 2; // 2 -> unary or binary. 11061 } else if (CanBeUnaryOperator) { 11062 ErrorKind = 0; // 0 -> unary 11063 } else { 11064 assert(CanBeBinaryOperator && 11065 "All non-call overloaded operators are unary or binary!"); 11066 ErrorKind = 1; // 1 -> binary 11067 } 11068 11069 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 11070 << FnDecl->getDeclName() << NumParams << ErrorKind; 11071 } 11072 11073 // Overloaded operators other than operator() cannot be variadic. 11074 if (Op != OO_Call && 11075 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 11076 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 11077 << FnDecl->getDeclName(); 11078 } 11079 11080 // Some operators must be non-static member functions. 11081 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 11082 return Diag(FnDecl->getLocation(), 11083 diag::err_operator_overload_must_be_member) 11084 << FnDecl->getDeclName(); 11085 } 11086 11087 // C++ [over.inc]p1: 11088 // The user-defined function called operator++ implements the 11089 // prefix and postfix ++ operator. If this function is a member 11090 // function with no parameters, or a non-member function with one 11091 // parameter of class or enumeration type, it defines the prefix 11092 // increment operator ++ for objects of that type. If the function 11093 // is a member function with one parameter (which shall be of type 11094 // int) or a non-member function with two parameters (the second 11095 // of which shall be of type int), it defines the postfix 11096 // increment operator ++ for objects of that type. 11097 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 11098 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 11099 QualType ParamType = LastParam->getType(); 11100 11101 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 11102 !ParamType->isDependentType()) 11103 return Diag(LastParam->getLocation(), 11104 diag::err_operator_overload_post_incdec_must_be_int) 11105 << LastParam->getType() << (Op == OO_MinusMinus); 11106 } 11107 11108 return false; 11109 } 11110 11111 /// CheckLiteralOperatorDeclaration - Check whether the declaration 11112 /// of this literal operator function is well-formed. If so, returns 11113 /// false; otherwise, emits appropriate diagnostics and returns true. 11114 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 11115 if (isa<CXXMethodDecl>(FnDecl)) { 11116 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 11117 << FnDecl->getDeclName(); 11118 return true; 11119 } 11120 11121 if (FnDecl->isExternC()) { 11122 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 11123 return true; 11124 } 11125 11126 bool Valid = false; 11127 11128 // This might be the definition of a literal operator template. 11129 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 11130 // This might be a specialization of a literal operator template. 11131 if (!TpDecl) 11132 TpDecl = FnDecl->getPrimaryTemplate(); 11133 11134 // template <char...> type operator "" name() and 11135 // template <class T, T...> type operator "" name() are the only valid 11136 // template signatures, and the only valid signatures with no parameters. 11137 if (TpDecl) { 11138 if (FnDecl->param_size() == 0) { 11139 // Must have one or two template parameters 11140 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 11141 if (Params->size() == 1) { 11142 NonTypeTemplateParmDecl *PmDecl = 11143 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 11144 11145 // The template parameter must be a char parameter pack. 11146 if (PmDecl && PmDecl->isTemplateParameterPack() && 11147 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 11148 Valid = true; 11149 } else if (Params->size() == 2) { 11150 TemplateTypeParmDecl *PmType = 11151 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 11152 NonTypeTemplateParmDecl *PmArgs = 11153 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 11154 11155 // The second template parameter must be a parameter pack with the 11156 // first template parameter as its type. 11157 if (PmType && PmArgs && 11158 !PmType->isTemplateParameterPack() && 11159 PmArgs->isTemplateParameterPack()) { 11160 const TemplateTypeParmType *TArgs = 11161 PmArgs->getType()->getAs<TemplateTypeParmType>(); 11162 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 11163 TArgs->getIndex() == PmType->getIndex()) { 11164 Valid = true; 11165 if (ActiveTemplateInstantiations.empty()) 11166 Diag(FnDecl->getLocation(), 11167 diag::ext_string_literal_operator_template); 11168 } 11169 } 11170 } 11171 } 11172 } else if (FnDecl->param_size()) { 11173 // Check the first parameter 11174 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 11175 11176 QualType T = (*Param)->getType().getUnqualifiedType(); 11177 11178 // unsigned long long int, long double, and any character type are allowed 11179 // as the only parameters. 11180 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 11181 Context.hasSameType(T, Context.LongDoubleTy) || 11182 Context.hasSameType(T, Context.CharTy) || 11183 Context.hasSameType(T, Context.WideCharTy) || 11184 Context.hasSameType(T, Context.Char16Ty) || 11185 Context.hasSameType(T, Context.Char32Ty)) { 11186 if (++Param == FnDecl->param_end()) 11187 Valid = true; 11188 goto FinishedParams; 11189 } 11190 11191 // Otherwise it must be a pointer to const; let's strip those qualifiers. 11192 const PointerType *PT = T->getAs<PointerType>(); 11193 if (!PT) 11194 goto FinishedParams; 11195 T = PT->getPointeeType(); 11196 if (!T.isConstQualified() || T.isVolatileQualified()) 11197 goto FinishedParams; 11198 T = T.getUnqualifiedType(); 11199 11200 // Move on to the second parameter; 11201 ++Param; 11202 11203 // If there is no second parameter, the first must be a const char * 11204 if (Param == FnDecl->param_end()) { 11205 if (Context.hasSameType(T, Context.CharTy)) 11206 Valid = true; 11207 goto FinishedParams; 11208 } 11209 11210 // const char *, const wchar_t*, const char16_t*, and const char32_t* 11211 // are allowed as the first parameter to a two-parameter function 11212 if (!(Context.hasSameType(T, Context.CharTy) || 11213 Context.hasSameType(T, Context.WideCharTy) || 11214 Context.hasSameType(T, Context.Char16Ty) || 11215 Context.hasSameType(T, Context.Char32Ty))) 11216 goto FinishedParams; 11217 11218 // The second and final parameter must be an std::size_t 11219 T = (*Param)->getType().getUnqualifiedType(); 11220 if (Context.hasSameType(T, Context.getSizeType()) && 11221 ++Param == FnDecl->param_end()) 11222 Valid = true; 11223 } 11224 11225 // FIXME: This diagnostic is absolutely terrible. 11226 FinishedParams: 11227 if (!Valid) { 11228 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 11229 << FnDecl->getDeclName(); 11230 return true; 11231 } 11232 11233 // A parameter-declaration-clause containing a default argument is not 11234 // equivalent to any of the permitted forms. 11235 for (auto Param : FnDecl->params()) { 11236 if (Param->hasDefaultArg()) { 11237 Diag(Param->getDefaultArgRange().getBegin(), 11238 diag::err_literal_operator_default_argument) 11239 << Param->getDefaultArgRange(); 11240 break; 11241 } 11242 } 11243 11244 StringRef LiteralName 11245 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11246 if (LiteralName[0] != '_') { 11247 // C++11 [usrlit.suffix]p1: 11248 // Literal suffix identifiers that do not start with an underscore 11249 // are reserved for future standardization. 11250 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11251 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11252 } 11253 11254 return false; 11255 } 11256 11257 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11258 /// linkage specification, including the language and (if present) 11259 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 11260 /// language string literal. LBraceLoc, if valid, provides the location of 11261 /// the '{' brace. Otherwise, this linkage specification does not 11262 /// have any braces. 11263 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11264 Expr *LangStr, 11265 SourceLocation LBraceLoc) { 11266 StringLiteral *Lit = cast<StringLiteral>(LangStr); 11267 if (!Lit->isAscii()) { 11268 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 11269 << LangStr->getSourceRange(); 11270 return nullptr; 11271 } 11272 11273 StringRef Lang = Lit->getString(); 11274 LinkageSpecDecl::LanguageIDs Language; 11275 if (Lang == "C") 11276 Language = LinkageSpecDecl::lang_c; 11277 else if (Lang == "C++") 11278 Language = LinkageSpecDecl::lang_cxx; 11279 else { 11280 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11281 << LangStr->getSourceRange(); 11282 return nullptr; 11283 } 11284 11285 // FIXME: Add all the various semantics of linkage specifications 11286 11287 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11288 LangStr->getExprLoc(), Language, 11289 LBraceLoc.isValid()); 11290 CurContext->addDecl(D); 11291 PushDeclContext(S, D); 11292 return D; 11293 } 11294 11295 /// ActOnFinishLinkageSpecification - Complete the definition of 11296 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11297 /// valid, it's the position of the closing '}' brace in a linkage 11298 /// specification that uses braces. 11299 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11300 Decl *LinkageSpec, 11301 SourceLocation RBraceLoc) { 11302 if (RBraceLoc.isValid()) { 11303 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11304 LSDecl->setRBraceLoc(RBraceLoc); 11305 } 11306 PopDeclContext(); 11307 return LinkageSpec; 11308 } 11309 11310 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11311 AttributeList *AttrList, 11312 SourceLocation SemiLoc) { 11313 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11314 // Attribute declarations appertain to empty declaration so we handle 11315 // them here. 11316 if (AttrList) 11317 ProcessDeclAttributeList(S, ED, AttrList); 11318 11319 CurContext->addDecl(ED); 11320 return ED; 11321 } 11322 11323 /// \brief Perform semantic analysis for the variable declaration that 11324 /// occurs within a C++ catch clause, returning the newly-created 11325 /// variable. 11326 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11327 TypeSourceInfo *TInfo, 11328 SourceLocation StartLoc, 11329 SourceLocation Loc, 11330 IdentifierInfo *Name) { 11331 bool Invalid = false; 11332 QualType ExDeclType = TInfo->getType(); 11333 11334 // Arrays and functions decay. 11335 if (ExDeclType->isArrayType()) 11336 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11337 else if (ExDeclType->isFunctionType()) 11338 ExDeclType = Context.getPointerType(ExDeclType); 11339 11340 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11341 // The exception-declaration shall not denote a pointer or reference to an 11342 // incomplete type, other than [cv] void*. 11343 // N2844 forbids rvalue references. 11344 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11345 Diag(Loc, diag::err_catch_rvalue_ref); 11346 Invalid = true; 11347 } 11348 11349 QualType BaseType = ExDeclType; 11350 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11351 unsigned DK = diag::err_catch_incomplete; 11352 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11353 BaseType = Ptr->getPointeeType(); 11354 Mode = 1; 11355 DK = diag::err_catch_incomplete_ptr; 11356 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11357 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11358 BaseType = Ref->getPointeeType(); 11359 Mode = 2; 11360 DK = diag::err_catch_incomplete_ref; 11361 } 11362 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11363 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11364 Invalid = true; 11365 11366 if (!Invalid && !ExDeclType->isDependentType() && 11367 RequireNonAbstractType(Loc, ExDeclType, 11368 diag::err_abstract_type_in_decl, 11369 AbstractVariableType)) 11370 Invalid = true; 11371 11372 // Only the non-fragile NeXT runtime currently supports C++ catches 11373 // of ObjC types, and no runtime supports catching ObjC types by value. 11374 if (!Invalid && getLangOpts().ObjC1) { 11375 QualType T = ExDeclType; 11376 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11377 T = RT->getPointeeType(); 11378 11379 if (T->isObjCObjectType()) { 11380 Diag(Loc, diag::err_objc_object_catch); 11381 Invalid = true; 11382 } else if (T->isObjCObjectPointerType()) { 11383 // FIXME: should this be a test for macosx-fragile specifically? 11384 if (getLangOpts().ObjCRuntime.isFragile()) 11385 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 11386 } 11387 } 11388 11389 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 11390 ExDeclType, TInfo, SC_None); 11391 ExDecl->setExceptionVariable(true); 11392 11393 // In ARC, infer 'retaining' for variables of retainable type. 11394 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 11395 Invalid = true; 11396 11397 if (!Invalid && !ExDeclType->isDependentType()) { 11398 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 11399 // Insulate this from anything else we might currently be parsing. 11400 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11401 11402 // C++ [except.handle]p16: 11403 // The object declared in an exception-declaration or, if the 11404 // exception-declaration does not specify a name, a temporary (12.2) is 11405 // copy-initialized (8.5) from the exception object. [...] 11406 // The object is destroyed when the handler exits, after the destruction 11407 // of any automatic objects initialized within the handler. 11408 // 11409 // We just pretend to initialize the object with itself, then make sure 11410 // it can be destroyed later. 11411 QualType initType = ExDeclType; 11412 11413 InitializedEntity entity = 11414 InitializedEntity::InitializeVariable(ExDecl); 11415 InitializationKind initKind = 11416 InitializationKind::CreateCopy(Loc, SourceLocation()); 11417 11418 Expr *opaqueValue = 11419 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 11420 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 11421 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 11422 if (result.isInvalid()) 11423 Invalid = true; 11424 else { 11425 // If the constructor used was non-trivial, set this as the 11426 // "initializer". 11427 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 11428 if (!construct->getConstructor()->isTrivial()) { 11429 Expr *init = MaybeCreateExprWithCleanups(construct); 11430 ExDecl->setInit(init); 11431 } 11432 11433 // And make sure it's destructable. 11434 FinalizeVarWithDestructor(ExDecl, recordType); 11435 } 11436 } 11437 } 11438 11439 if (Invalid) 11440 ExDecl->setInvalidDecl(); 11441 11442 return ExDecl; 11443 } 11444 11445 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 11446 /// handler. 11447 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 11448 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11449 bool Invalid = D.isInvalidType(); 11450 11451 // Check for unexpanded parameter packs. 11452 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11453 UPPC_ExceptionType)) { 11454 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 11455 D.getIdentifierLoc()); 11456 Invalid = true; 11457 } 11458 11459 IdentifierInfo *II = D.getIdentifier(); 11460 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 11461 LookupOrdinaryName, 11462 ForRedeclaration)) { 11463 // The scope should be freshly made just for us. There is just no way 11464 // it contains any previous declaration, except for function parameters in 11465 // a function-try-block's catch statement. 11466 assert(!S->isDeclScope(PrevDecl)); 11467 if (isDeclInScope(PrevDecl, CurContext, S)) { 11468 Diag(D.getIdentifierLoc(), diag::err_redefinition) 11469 << D.getIdentifier(); 11470 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11471 Invalid = true; 11472 } else if (PrevDecl->isTemplateParameter()) 11473 // Maybe we will complain about the shadowed template parameter. 11474 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11475 } 11476 11477 if (D.getCXXScopeSpec().isSet() && !Invalid) { 11478 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 11479 << D.getCXXScopeSpec().getRange(); 11480 Invalid = true; 11481 } 11482 11483 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 11484 D.getLocStart(), 11485 D.getIdentifierLoc(), 11486 D.getIdentifier()); 11487 if (Invalid) 11488 ExDecl->setInvalidDecl(); 11489 11490 // Add the exception declaration into this scope. 11491 if (II) 11492 PushOnScopeChains(ExDecl, S); 11493 else 11494 CurContext->addDecl(ExDecl); 11495 11496 ProcessDeclAttributes(S, ExDecl, D); 11497 return ExDecl; 11498 } 11499 11500 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11501 Expr *AssertExpr, 11502 Expr *AssertMessageExpr, 11503 SourceLocation RParenLoc) { 11504 StringLiteral *AssertMessage = 11505 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 11506 11507 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 11508 return nullptr; 11509 11510 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 11511 AssertMessage, RParenLoc, false); 11512 } 11513 11514 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11515 Expr *AssertExpr, 11516 StringLiteral *AssertMessage, 11517 SourceLocation RParenLoc, 11518 bool Failed) { 11519 assert(AssertExpr != nullptr && "Expected non-null condition"); 11520 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 11521 !Failed) { 11522 // In a static_assert-declaration, the constant-expression shall be a 11523 // constant expression that can be contextually converted to bool. 11524 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 11525 if (Converted.isInvalid()) 11526 Failed = true; 11527 11528 llvm::APSInt Cond; 11529 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 11530 diag::err_static_assert_expression_is_not_constant, 11531 /*AllowFold=*/false).isInvalid()) 11532 Failed = true; 11533 11534 if (!Failed && !Cond) { 11535 SmallString<256> MsgBuffer; 11536 llvm::raw_svector_ostream Msg(MsgBuffer); 11537 if (AssertMessage) 11538 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 11539 Diag(StaticAssertLoc, diag::err_static_assert_failed) 11540 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 11541 Failed = true; 11542 } 11543 } 11544 11545 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 11546 AssertExpr, AssertMessage, RParenLoc, 11547 Failed); 11548 11549 CurContext->addDecl(Decl); 11550 return Decl; 11551 } 11552 11553 /// \brief Perform semantic analysis of the given friend type declaration. 11554 /// 11555 /// \returns A friend declaration that. 11556 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 11557 SourceLocation FriendLoc, 11558 TypeSourceInfo *TSInfo) { 11559 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 11560 11561 QualType T = TSInfo->getType(); 11562 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 11563 11564 // C++03 [class.friend]p2: 11565 // An elaborated-type-specifier shall be used in a friend declaration 11566 // for a class.* 11567 // 11568 // * The class-key of the elaborated-type-specifier is required. 11569 if (!ActiveTemplateInstantiations.empty()) { 11570 // Do not complain about the form of friend template types during 11571 // template instantiation; we will already have complained when the 11572 // template was declared. 11573 } else { 11574 if (!T->isElaboratedTypeSpecifier()) { 11575 // If we evaluated the type to a record type, suggest putting 11576 // a tag in front. 11577 if (const RecordType *RT = T->getAs<RecordType>()) { 11578 RecordDecl *RD = RT->getDecl(); 11579 11580 SmallString<16> InsertionText(" "); 11581 InsertionText += RD->getKindName(); 11582 11583 Diag(TypeRange.getBegin(), 11584 getLangOpts().CPlusPlus11 ? 11585 diag::warn_cxx98_compat_unelaborated_friend_type : 11586 diag::ext_unelaborated_friend_type) 11587 << (unsigned) RD->getTagKind() 11588 << T 11589 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 11590 InsertionText); 11591 } else { 11592 Diag(FriendLoc, 11593 getLangOpts().CPlusPlus11 ? 11594 diag::warn_cxx98_compat_nonclass_type_friend : 11595 diag::ext_nonclass_type_friend) 11596 << T 11597 << TypeRange; 11598 } 11599 } else if (T->getAs<EnumType>()) { 11600 Diag(FriendLoc, 11601 getLangOpts().CPlusPlus11 ? 11602 diag::warn_cxx98_compat_enum_friend : 11603 diag::ext_enum_friend) 11604 << T 11605 << TypeRange; 11606 } 11607 11608 // C++11 [class.friend]p3: 11609 // A friend declaration that does not declare a function shall have one 11610 // of the following forms: 11611 // friend elaborated-type-specifier ; 11612 // friend simple-type-specifier ; 11613 // friend typename-specifier ; 11614 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 11615 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 11616 } 11617 11618 // If the type specifier in a friend declaration designates a (possibly 11619 // cv-qualified) class type, that class is declared as a friend; otherwise, 11620 // the friend declaration is ignored. 11621 return FriendDecl::Create(Context, CurContext, 11622 TSInfo->getTypeLoc().getLocStart(), TSInfo, 11623 FriendLoc); 11624 } 11625 11626 /// Handle a friend tag declaration where the scope specifier was 11627 /// templated. 11628 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 11629 unsigned TagSpec, SourceLocation TagLoc, 11630 CXXScopeSpec &SS, 11631 IdentifierInfo *Name, 11632 SourceLocation NameLoc, 11633 AttributeList *Attr, 11634 MultiTemplateParamsArg TempParamLists) { 11635 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11636 11637 bool isExplicitSpecialization = false; 11638 bool Invalid = false; 11639 11640 if (TemplateParameterList *TemplateParams = 11641 MatchTemplateParametersToScopeSpecifier( 11642 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 11643 isExplicitSpecialization, Invalid)) { 11644 if (TemplateParams->size() > 0) { 11645 // This is a declaration of a class template. 11646 if (Invalid) 11647 return nullptr; 11648 11649 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 11650 NameLoc, Attr, TemplateParams, AS_public, 11651 /*ModulePrivateLoc=*/SourceLocation(), 11652 FriendLoc, TempParamLists.size() - 1, 11653 TempParamLists.data()).get(); 11654 } else { 11655 // The "template<>" header is extraneous. 11656 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11657 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11658 isExplicitSpecialization = true; 11659 } 11660 } 11661 11662 if (Invalid) return nullptr; 11663 11664 bool isAllExplicitSpecializations = true; 11665 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 11666 if (TempParamLists[I]->size()) { 11667 isAllExplicitSpecializations = false; 11668 break; 11669 } 11670 } 11671 11672 // FIXME: don't ignore attributes. 11673 11674 // If it's explicit specializations all the way down, just forget 11675 // about the template header and build an appropriate non-templated 11676 // friend. TODO: for source fidelity, remember the headers. 11677 if (isAllExplicitSpecializations) { 11678 if (SS.isEmpty()) { 11679 bool Owned = false; 11680 bool IsDependent = false; 11681 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 11682 Attr, AS_public, 11683 /*ModulePrivateLoc=*/SourceLocation(), 11684 MultiTemplateParamsArg(), Owned, IsDependent, 11685 /*ScopedEnumKWLoc=*/SourceLocation(), 11686 /*ScopedEnumUsesClassTag=*/false, 11687 /*UnderlyingType=*/TypeResult(), 11688 /*IsTypeSpecifier=*/false); 11689 } 11690 11691 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11692 ElaboratedTypeKeyword Keyword 11693 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11694 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 11695 *Name, NameLoc); 11696 if (T.isNull()) 11697 return nullptr; 11698 11699 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11700 if (isa<DependentNameType>(T)) { 11701 DependentNameTypeLoc TL = 11702 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11703 TL.setElaboratedKeywordLoc(TagLoc); 11704 TL.setQualifierLoc(QualifierLoc); 11705 TL.setNameLoc(NameLoc); 11706 } else { 11707 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 11708 TL.setElaboratedKeywordLoc(TagLoc); 11709 TL.setQualifierLoc(QualifierLoc); 11710 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 11711 } 11712 11713 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11714 TSI, FriendLoc, TempParamLists); 11715 Friend->setAccess(AS_public); 11716 CurContext->addDecl(Friend); 11717 return Friend; 11718 } 11719 11720 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 11721 11722 11723 11724 // Handle the case of a templated-scope friend class. e.g. 11725 // template <class T> class A<T>::B; 11726 // FIXME: we don't support these right now. 11727 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 11728 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 11729 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11730 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 11731 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11732 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11733 TL.setElaboratedKeywordLoc(TagLoc); 11734 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 11735 TL.setNameLoc(NameLoc); 11736 11737 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11738 TSI, FriendLoc, TempParamLists); 11739 Friend->setAccess(AS_public); 11740 Friend->setUnsupportedFriend(true); 11741 CurContext->addDecl(Friend); 11742 return Friend; 11743 } 11744 11745 11746 /// Handle a friend type declaration. This works in tandem with 11747 /// ActOnTag. 11748 /// 11749 /// Notes on friend class templates: 11750 /// 11751 /// We generally treat friend class declarations as if they were 11752 /// declaring a class. So, for example, the elaborated type specifier 11753 /// in a friend declaration is required to obey the restrictions of a 11754 /// class-head (i.e. no typedefs in the scope chain), template 11755 /// parameters are required to match up with simple template-ids, &c. 11756 /// However, unlike when declaring a template specialization, it's 11757 /// okay to refer to a template specialization without an empty 11758 /// template parameter declaration, e.g. 11759 /// friend class A<T>::B<unsigned>; 11760 /// We permit this as a special case; if there are any template 11761 /// parameters present at all, require proper matching, i.e. 11762 /// template <> template \<class T> friend class A<int>::B; 11763 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 11764 MultiTemplateParamsArg TempParams) { 11765 SourceLocation Loc = DS.getLocStart(); 11766 11767 assert(DS.isFriendSpecified()); 11768 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11769 11770 // Try to convert the decl specifier to a type. This works for 11771 // friend templates because ActOnTag never produces a ClassTemplateDecl 11772 // for a TUK_Friend. 11773 Declarator TheDeclarator(DS, Declarator::MemberContext); 11774 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 11775 QualType T = TSI->getType(); 11776 if (TheDeclarator.isInvalidType()) 11777 return nullptr; 11778 11779 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 11780 return nullptr; 11781 11782 // This is definitely an error in C++98. It's probably meant to 11783 // be forbidden in C++0x, too, but the specification is just 11784 // poorly written. 11785 // 11786 // The problem is with declarations like the following: 11787 // template <T> friend A<T>::foo; 11788 // where deciding whether a class C is a friend or not now hinges 11789 // on whether there exists an instantiation of A that causes 11790 // 'foo' to equal C. There are restrictions on class-heads 11791 // (which we declare (by fiat) elaborated friend declarations to 11792 // be) that makes this tractable. 11793 // 11794 // FIXME: handle "template <> friend class A<T>;", which 11795 // is possibly well-formed? Who even knows? 11796 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 11797 Diag(Loc, diag::err_tagless_friend_type_template) 11798 << DS.getSourceRange(); 11799 return nullptr; 11800 } 11801 11802 // C++98 [class.friend]p1: A friend of a class is a function 11803 // or class that is not a member of the class . . . 11804 // This is fixed in DR77, which just barely didn't make the C++03 11805 // deadline. It's also a very silly restriction that seriously 11806 // affects inner classes and which nobody else seems to implement; 11807 // thus we never diagnose it, not even in -pedantic. 11808 // 11809 // But note that we could warn about it: it's always useless to 11810 // friend one of your own members (it's not, however, worthless to 11811 // friend a member of an arbitrary specialization of your template). 11812 11813 Decl *D; 11814 if (unsigned NumTempParamLists = TempParams.size()) 11815 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 11816 NumTempParamLists, 11817 TempParams.data(), 11818 TSI, 11819 DS.getFriendSpecLoc()); 11820 else 11821 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 11822 11823 if (!D) 11824 return nullptr; 11825 11826 D->setAccess(AS_public); 11827 CurContext->addDecl(D); 11828 11829 return D; 11830 } 11831 11832 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 11833 MultiTemplateParamsArg TemplateParams) { 11834 const DeclSpec &DS = D.getDeclSpec(); 11835 11836 assert(DS.isFriendSpecified()); 11837 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11838 11839 SourceLocation Loc = D.getIdentifierLoc(); 11840 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11841 11842 // C++ [class.friend]p1 11843 // A friend of a class is a function or class.... 11844 // Note that this sees through typedefs, which is intended. 11845 // It *doesn't* see through dependent types, which is correct 11846 // according to [temp.arg.type]p3: 11847 // If a declaration acquires a function type through a 11848 // type dependent on a template-parameter and this causes 11849 // a declaration that does not use the syntactic form of a 11850 // function declarator to have a function type, the program 11851 // is ill-formed. 11852 if (!TInfo->getType()->isFunctionType()) { 11853 Diag(Loc, diag::err_unexpected_friend); 11854 11855 // It might be worthwhile to try to recover by creating an 11856 // appropriate declaration. 11857 return nullptr; 11858 } 11859 11860 // C++ [namespace.memdef]p3 11861 // - If a friend declaration in a non-local class first declares a 11862 // class or function, the friend class or function is a member 11863 // of the innermost enclosing namespace. 11864 // - The name of the friend is not found by simple name lookup 11865 // until a matching declaration is provided in that namespace 11866 // scope (either before or after the class declaration granting 11867 // friendship). 11868 // - If a friend function is called, its name may be found by the 11869 // name lookup that considers functions from namespaces and 11870 // classes associated with the types of the function arguments. 11871 // - When looking for a prior declaration of a class or a function 11872 // declared as a friend, scopes outside the innermost enclosing 11873 // namespace scope are not considered. 11874 11875 CXXScopeSpec &SS = D.getCXXScopeSpec(); 11876 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 11877 DeclarationName Name = NameInfo.getName(); 11878 assert(Name); 11879 11880 // Check for unexpanded parameter packs. 11881 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 11882 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 11883 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 11884 return nullptr; 11885 11886 // The context we found the declaration in, or in which we should 11887 // create the declaration. 11888 DeclContext *DC; 11889 Scope *DCScope = S; 11890 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 11891 ForRedeclaration); 11892 11893 // There are five cases here. 11894 // - There's no scope specifier and we're in a local class. Only look 11895 // for functions declared in the immediately-enclosing block scope. 11896 // We recover from invalid scope qualifiers as if they just weren't there. 11897 FunctionDecl *FunctionContainingLocalClass = nullptr; 11898 if ((SS.isInvalid() || !SS.isSet()) && 11899 (FunctionContainingLocalClass = 11900 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 11901 // C++11 [class.friend]p11: 11902 // If a friend declaration appears in a local class and the name 11903 // specified is an unqualified name, a prior declaration is 11904 // looked up without considering scopes that are outside the 11905 // innermost enclosing non-class scope. For a friend function 11906 // declaration, if there is no prior declaration, the program is 11907 // ill-formed. 11908 11909 // Find the innermost enclosing non-class scope. This is the block 11910 // scope containing the local class definition (or for a nested class, 11911 // the outer local class). 11912 DCScope = S->getFnParent(); 11913 11914 // Look up the function name in the scope. 11915 Previous.clear(LookupLocalFriendName); 11916 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 11917 11918 if (!Previous.empty()) { 11919 // All possible previous declarations must have the same context: 11920 // either they were declared at block scope or they are members of 11921 // one of the enclosing local classes. 11922 DC = Previous.getRepresentativeDecl()->getDeclContext(); 11923 } else { 11924 // This is ill-formed, but provide the context that we would have 11925 // declared the function in, if we were permitted to, for error recovery. 11926 DC = FunctionContainingLocalClass; 11927 } 11928 adjustContextForLocalExternDecl(DC); 11929 11930 // C++ [class.friend]p6: 11931 // A function can be defined in a friend declaration of a class if and 11932 // only if the class is a non-local class (9.8), the function name is 11933 // unqualified, and the function has namespace scope. 11934 if (D.isFunctionDefinition()) { 11935 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 11936 } 11937 11938 // - There's no scope specifier, in which case we just go to the 11939 // appropriate scope and look for a function or function template 11940 // there as appropriate. 11941 } else if (SS.isInvalid() || !SS.isSet()) { 11942 // C++11 [namespace.memdef]p3: 11943 // If the name in a friend declaration is neither qualified nor 11944 // a template-id and the declaration is a function or an 11945 // elaborated-type-specifier, the lookup to determine whether 11946 // the entity has been previously declared shall not consider 11947 // any scopes outside the innermost enclosing namespace. 11948 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 11949 11950 // Find the appropriate context according to the above. 11951 DC = CurContext; 11952 11953 // Skip class contexts. If someone can cite chapter and verse 11954 // for this behavior, that would be nice --- it's what GCC and 11955 // EDG do, and it seems like a reasonable intent, but the spec 11956 // really only says that checks for unqualified existing 11957 // declarations should stop at the nearest enclosing namespace, 11958 // not that they should only consider the nearest enclosing 11959 // namespace. 11960 while (DC->isRecord()) 11961 DC = DC->getParent(); 11962 11963 DeclContext *LookupDC = DC; 11964 while (LookupDC->isTransparentContext()) 11965 LookupDC = LookupDC->getParent(); 11966 11967 while (true) { 11968 LookupQualifiedName(Previous, LookupDC); 11969 11970 if (!Previous.empty()) { 11971 DC = LookupDC; 11972 break; 11973 } 11974 11975 if (isTemplateId) { 11976 if (isa<TranslationUnitDecl>(LookupDC)) break; 11977 } else { 11978 if (LookupDC->isFileContext()) break; 11979 } 11980 LookupDC = LookupDC->getParent(); 11981 } 11982 11983 DCScope = getScopeForDeclContext(S, DC); 11984 11985 // - There's a non-dependent scope specifier, in which case we 11986 // compute it and do a previous lookup there for a function 11987 // or function template. 11988 } else if (!SS.getScopeRep()->isDependent()) { 11989 DC = computeDeclContext(SS); 11990 if (!DC) return nullptr; 11991 11992 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 11993 11994 LookupQualifiedName(Previous, DC); 11995 11996 // Ignore things found implicitly in the wrong scope. 11997 // TODO: better diagnostics for this case. Suggesting the right 11998 // qualified scope would be nice... 11999 LookupResult::Filter F = Previous.makeFilter(); 12000 while (F.hasNext()) { 12001 NamedDecl *D = F.next(); 12002 if (!DC->InEnclosingNamespaceSetOf( 12003 D->getDeclContext()->getRedeclContext())) 12004 F.erase(); 12005 } 12006 F.done(); 12007 12008 if (Previous.empty()) { 12009 D.setInvalidType(); 12010 Diag(Loc, diag::err_qualified_friend_not_found) 12011 << Name << TInfo->getType(); 12012 return nullptr; 12013 } 12014 12015 // C++ [class.friend]p1: A friend of a class is a function or 12016 // class that is not a member of the class . . . 12017 if (DC->Equals(CurContext)) 12018 Diag(DS.getFriendSpecLoc(), 12019 getLangOpts().CPlusPlus11 ? 12020 diag::warn_cxx98_compat_friend_is_member : 12021 diag::err_friend_is_member); 12022 12023 if (D.isFunctionDefinition()) { 12024 // C++ [class.friend]p6: 12025 // A function can be defined in a friend declaration of a class if and 12026 // only if the class is a non-local class (9.8), the function name is 12027 // unqualified, and the function has namespace scope. 12028 SemaDiagnosticBuilder DB 12029 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 12030 12031 DB << SS.getScopeRep(); 12032 if (DC->isFileContext()) 12033 DB << FixItHint::CreateRemoval(SS.getRange()); 12034 SS.clear(); 12035 } 12036 12037 // - There's a scope specifier that does not match any template 12038 // parameter lists, in which case we use some arbitrary context, 12039 // create a method or method template, and wait for instantiation. 12040 // - There's a scope specifier that does match some template 12041 // parameter lists, which we don't handle right now. 12042 } else { 12043 if (D.isFunctionDefinition()) { 12044 // C++ [class.friend]p6: 12045 // A function can be defined in a friend declaration of a class if and 12046 // only if the class is a non-local class (9.8), the function name is 12047 // unqualified, and the function has namespace scope. 12048 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 12049 << SS.getScopeRep(); 12050 } 12051 12052 DC = CurContext; 12053 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 12054 } 12055 12056 if (!DC->isRecord()) { 12057 // This implies that it has to be an operator or function. 12058 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 12059 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 12060 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 12061 Diag(Loc, diag::err_introducing_special_friend) << 12062 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 12063 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 12064 return nullptr; 12065 } 12066 } 12067 12068 // FIXME: This is an egregious hack to cope with cases where the scope stack 12069 // does not contain the declaration context, i.e., in an out-of-line 12070 // definition of a class. 12071 Scope FakeDCScope(S, Scope::DeclScope, Diags); 12072 if (!DCScope) { 12073 FakeDCScope.setEntity(DC); 12074 DCScope = &FakeDCScope; 12075 } 12076 12077 bool AddToScope = true; 12078 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 12079 TemplateParams, AddToScope); 12080 if (!ND) return nullptr; 12081 12082 assert(ND->getLexicalDeclContext() == CurContext); 12083 12084 // If we performed typo correction, we might have added a scope specifier 12085 // and changed the decl context. 12086 DC = ND->getDeclContext(); 12087 12088 // Add the function declaration to the appropriate lookup tables, 12089 // adjusting the redeclarations list as necessary. We don't 12090 // want to do this yet if the friending class is dependent. 12091 // 12092 // Also update the scope-based lookup if the target context's 12093 // lookup context is in lexical scope. 12094 if (!CurContext->isDependentContext()) { 12095 DC = DC->getRedeclContext(); 12096 DC->makeDeclVisibleInContext(ND); 12097 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12098 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 12099 } 12100 12101 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 12102 D.getIdentifierLoc(), ND, 12103 DS.getFriendSpecLoc()); 12104 FrD->setAccess(AS_public); 12105 CurContext->addDecl(FrD); 12106 12107 if (ND->isInvalidDecl()) { 12108 FrD->setInvalidDecl(); 12109 } else { 12110 if (DC->isRecord()) CheckFriendAccess(ND); 12111 12112 FunctionDecl *FD; 12113 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 12114 FD = FTD->getTemplatedDecl(); 12115 else 12116 FD = cast<FunctionDecl>(ND); 12117 12118 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 12119 // default argument expression, that declaration shall be a definition 12120 // and shall be the only declaration of the function or function 12121 // template in the translation unit. 12122 if (functionDeclHasDefaultArgument(FD)) { 12123 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 12124 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 12125 Diag(OldFD->getLocation(), diag::note_previous_declaration); 12126 } else if (!D.isFunctionDefinition()) 12127 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 12128 } 12129 12130 // Mark templated-scope function declarations as unsupported. 12131 if (FD->getNumTemplateParameterLists()) 12132 FrD->setUnsupportedFriend(true); 12133 } 12134 12135 return ND; 12136 } 12137 12138 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 12139 AdjustDeclIfTemplate(Dcl); 12140 12141 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 12142 if (!Fn) { 12143 Diag(DelLoc, diag::err_deleted_non_function); 12144 return; 12145 } 12146 12147 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 12148 // Don't consider the implicit declaration we generate for explicit 12149 // specializations. FIXME: Do not generate these implicit declarations. 12150 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 12151 Prev->getPreviousDecl()) && 12152 !Prev->isDefined()) { 12153 Diag(DelLoc, diag::err_deleted_decl_not_first); 12154 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 12155 Prev->isImplicit() ? diag::note_previous_implicit_declaration 12156 : diag::note_previous_declaration); 12157 } 12158 // If the declaration wasn't the first, we delete the function anyway for 12159 // recovery. 12160 Fn = Fn->getCanonicalDecl(); 12161 } 12162 12163 // dllimport/dllexport cannot be deleted. 12164 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 12165 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 12166 Fn->setInvalidDecl(); 12167 } 12168 12169 if (Fn->isDeleted()) 12170 return; 12171 12172 // See if we're deleting a function which is already known to override a 12173 // non-deleted virtual function. 12174 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 12175 bool IssuedDiagnostic = false; 12176 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 12177 E = MD->end_overridden_methods(); 12178 I != E; ++I) { 12179 if (!(*MD->begin_overridden_methods())->isDeleted()) { 12180 if (!IssuedDiagnostic) { 12181 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 12182 IssuedDiagnostic = true; 12183 } 12184 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 12185 } 12186 } 12187 } 12188 12189 // C++11 [basic.start.main]p3: 12190 // A program that defines main as deleted [...] is ill-formed. 12191 if (Fn->isMain()) 12192 Diag(DelLoc, diag::err_deleted_main); 12193 12194 Fn->setDeletedAsWritten(); 12195 } 12196 12197 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 12198 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 12199 12200 if (MD) { 12201 if (MD->getParent()->isDependentType()) { 12202 MD->setDefaulted(); 12203 MD->setExplicitlyDefaulted(); 12204 return; 12205 } 12206 12207 CXXSpecialMember Member = getSpecialMember(MD); 12208 if (Member == CXXInvalid) { 12209 if (!MD->isInvalidDecl()) 12210 Diag(DefaultLoc, diag::err_default_special_members); 12211 return; 12212 } 12213 12214 MD->setDefaulted(); 12215 MD->setExplicitlyDefaulted(); 12216 12217 // If this definition appears within the record, do the checking when 12218 // the record is complete. 12219 const FunctionDecl *Primary = MD; 12220 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 12221 // Find the uninstantiated declaration that actually had the '= default' 12222 // on it. 12223 Pattern->isDefined(Primary); 12224 12225 // If the method was defaulted on its first declaration, we will have 12226 // already performed the checking in CheckCompletedCXXClass. Such a 12227 // declaration doesn't trigger an implicit definition. 12228 if (Primary == Primary->getCanonicalDecl()) 12229 return; 12230 12231 CheckExplicitlyDefaultedSpecialMember(MD); 12232 12233 // The exception specification is needed because we are defining the 12234 // function. 12235 ResolveExceptionSpec(DefaultLoc, 12236 MD->getType()->castAs<FunctionProtoType>()); 12237 12238 if (MD->isInvalidDecl()) 12239 return; 12240 12241 switch (Member) { 12242 case CXXDefaultConstructor: 12243 DefineImplicitDefaultConstructor(DefaultLoc, 12244 cast<CXXConstructorDecl>(MD)); 12245 break; 12246 case CXXCopyConstructor: 12247 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12248 break; 12249 case CXXCopyAssignment: 12250 DefineImplicitCopyAssignment(DefaultLoc, MD); 12251 break; 12252 case CXXDestructor: 12253 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12254 break; 12255 case CXXMoveConstructor: 12256 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12257 break; 12258 case CXXMoveAssignment: 12259 DefineImplicitMoveAssignment(DefaultLoc, MD); 12260 break; 12261 case CXXInvalid: 12262 llvm_unreachable("Invalid special member."); 12263 } 12264 } else { 12265 Diag(DefaultLoc, diag::err_default_special_members); 12266 } 12267 } 12268 12269 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12270 for (Stmt::child_range CI = S->children(); CI; ++CI) { 12271 Stmt *SubStmt = *CI; 12272 if (!SubStmt) 12273 continue; 12274 if (isa<ReturnStmt>(SubStmt)) 12275 Self.Diag(SubStmt->getLocStart(), 12276 diag::err_return_in_constructor_handler); 12277 if (!isa<Expr>(SubStmt)) 12278 SearchForReturnInStmt(Self, SubStmt); 12279 } 12280 } 12281 12282 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12283 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12284 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12285 SearchForReturnInStmt(*this, Handler); 12286 } 12287 } 12288 12289 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12290 const CXXMethodDecl *Old) { 12291 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12292 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12293 12294 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12295 12296 // If the calling conventions match, everything is fine 12297 if (NewCC == OldCC) 12298 return false; 12299 12300 // If the calling conventions mismatch because the new function is static, 12301 // suppress the calling convention mismatch error; the error about static 12302 // function override (err_static_overrides_virtual from 12303 // Sema::CheckFunctionDeclaration) is more clear. 12304 if (New->getStorageClass() == SC_Static) 12305 return false; 12306 12307 Diag(New->getLocation(), 12308 diag::err_conflicting_overriding_cc_attributes) 12309 << New->getDeclName() << New->getType() << Old->getType(); 12310 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12311 return true; 12312 } 12313 12314 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12315 const CXXMethodDecl *Old) { 12316 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12317 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12318 12319 if (Context.hasSameType(NewTy, OldTy) || 12320 NewTy->isDependentType() || OldTy->isDependentType()) 12321 return false; 12322 12323 // Check if the return types are covariant 12324 QualType NewClassTy, OldClassTy; 12325 12326 /// Both types must be pointers or references to classes. 12327 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12328 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12329 NewClassTy = NewPT->getPointeeType(); 12330 OldClassTy = OldPT->getPointeeType(); 12331 } 12332 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12333 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12334 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12335 NewClassTy = NewRT->getPointeeType(); 12336 OldClassTy = OldRT->getPointeeType(); 12337 } 12338 } 12339 } 12340 12341 // The return types aren't either both pointers or references to a class type. 12342 if (NewClassTy.isNull()) { 12343 Diag(New->getLocation(), 12344 diag::err_different_return_type_for_overriding_virtual_function) 12345 << New->getDeclName() << NewTy << OldTy 12346 << New->getReturnTypeSourceRange(); 12347 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12348 << Old->getReturnTypeSourceRange(); 12349 12350 return true; 12351 } 12352 12353 // C++ [class.virtual]p6: 12354 // If the return type of D::f differs from the return type of B::f, the 12355 // class type in the return type of D::f shall be complete at the point of 12356 // declaration of D::f or shall be the class type D. 12357 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12358 if (!RT->isBeingDefined() && 12359 RequireCompleteType(New->getLocation(), NewClassTy, 12360 diag::err_covariant_return_incomplete, 12361 New->getDeclName())) 12362 return true; 12363 } 12364 12365 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12366 // Check if the new class derives from the old class. 12367 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12368 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 12369 << New->getDeclName() << NewTy << OldTy 12370 << New->getReturnTypeSourceRange(); 12371 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12372 << Old->getReturnTypeSourceRange(); 12373 return true; 12374 } 12375 12376 // Check if we the conversion from derived to base is valid. 12377 if (CheckDerivedToBaseConversion( 12378 NewClassTy, OldClassTy, 12379 diag::err_covariant_return_inaccessible_base, 12380 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12381 New->getLocation(), New->getReturnTypeSourceRange(), 12382 New->getDeclName(), nullptr)) { 12383 // FIXME: this note won't trigger for delayed access control 12384 // diagnostics, and it's impossible to get an undelayed error 12385 // here from access control during the original parse because 12386 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 12387 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12388 << Old->getReturnTypeSourceRange(); 12389 return true; 12390 } 12391 } 12392 12393 // The qualifiers of the return types must be the same. 12394 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 12395 Diag(New->getLocation(), 12396 diag::err_covariant_return_type_different_qualifications) 12397 << New->getDeclName() << NewTy << OldTy 12398 << New->getReturnTypeSourceRange(); 12399 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12400 << Old->getReturnTypeSourceRange(); 12401 return true; 12402 }; 12403 12404 12405 // The new class type must have the same or less qualifiers as the old type. 12406 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 12407 Diag(New->getLocation(), 12408 diag::err_covariant_return_type_class_type_more_qualified) 12409 << New->getDeclName() << NewTy << OldTy 12410 << New->getReturnTypeSourceRange(); 12411 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12412 << Old->getReturnTypeSourceRange(); 12413 return true; 12414 }; 12415 12416 return false; 12417 } 12418 12419 /// \brief Mark the given method pure. 12420 /// 12421 /// \param Method the method to be marked pure. 12422 /// 12423 /// \param InitRange the source range that covers the "0" initializer. 12424 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 12425 SourceLocation EndLoc = InitRange.getEnd(); 12426 if (EndLoc.isValid()) 12427 Method->setRangeEnd(EndLoc); 12428 12429 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 12430 Method->setPure(); 12431 return false; 12432 } 12433 12434 if (!Method->isInvalidDecl()) 12435 Diag(Method->getLocation(), diag::err_non_virtual_pure) 12436 << Method->getDeclName() << InitRange; 12437 return true; 12438 } 12439 12440 /// \brief Determine whether the given declaration is a static data member. 12441 static bool isStaticDataMember(const Decl *D) { 12442 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 12443 return Var->isStaticDataMember(); 12444 12445 return false; 12446 } 12447 12448 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 12449 /// an initializer for the out-of-line declaration 'Dcl'. The scope 12450 /// is a fresh scope pushed for just this purpose. 12451 /// 12452 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 12453 /// static data member of class X, names should be looked up in the scope of 12454 /// class X. 12455 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 12456 // If there is no declaration, there was an error parsing it. 12457 if (!D || D->isInvalidDecl()) 12458 return; 12459 12460 // We will always have a nested name specifier here, but this declaration 12461 // might not be out of line if the specifier names the current namespace: 12462 // extern int n; 12463 // int ::n = 0; 12464 if (D->isOutOfLine()) 12465 EnterDeclaratorContext(S, D->getDeclContext()); 12466 12467 // If we are parsing the initializer for a static data member, push a 12468 // new expression evaluation context that is associated with this static 12469 // data member. 12470 if (isStaticDataMember(D)) 12471 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 12472 } 12473 12474 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 12475 /// initializer for the out-of-line declaration 'D'. 12476 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 12477 // If there is no declaration, there was an error parsing it. 12478 if (!D || D->isInvalidDecl()) 12479 return; 12480 12481 if (isStaticDataMember(D)) 12482 PopExpressionEvaluationContext(); 12483 12484 if (D->isOutOfLine()) 12485 ExitDeclaratorContext(S); 12486 } 12487 12488 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 12489 /// C++ if/switch/while/for statement. 12490 /// e.g: "if (int x = f()) {...}" 12491 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 12492 // C++ 6.4p2: 12493 // The declarator shall not specify a function or an array. 12494 // The type-specifier-seq shall not contain typedef and shall not declare a 12495 // new class or enumeration. 12496 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 12497 "Parser allowed 'typedef' as storage class of condition decl."); 12498 12499 Decl *Dcl = ActOnDeclarator(S, D); 12500 if (!Dcl) 12501 return true; 12502 12503 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 12504 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 12505 << D.getSourceRange(); 12506 return true; 12507 } 12508 12509 return Dcl; 12510 } 12511 12512 void Sema::LoadExternalVTableUses() { 12513 if (!ExternalSource) 12514 return; 12515 12516 SmallVector<ExternalVTableUse, 4> VTables; 12517 ExternalSource->ReadUsedVTables(VTables); 12518 SmallVector<VTableUse, 4> NewUses; 12519 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 12520 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 12521 = VTablesUsed.find(VTables[I].Record); 12522 // Even if a definition wasn't required before, it may be required now. 12523 if (Pos != VTablesUsed.end()) { 12524 if (!Pos->second && VTables[I].DefinitionRequired) 12525 Pos->second = true; 12526 continue; 12527 } 12528 12529 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 12530 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 12531 } 12532 12533 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 12534 } 12535 12536 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 12537 bool DefinitionRequired) { 12538 // Ignore any vtable uses in unevaluated operands or for classes that do 12539 // not have a vtable. 12540 if (!Class->isDynamicClass() || Class->isDependentContext() || 12541 CurContext->isDependentContext() || isUnevaluatedContext()) 12542 return; 12543 12544 // Try to insert this class into the map. 12545 LoadExternalVTableUses(); 12546 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12547 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 12548 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 12549 if (!Pos.second) { 12550 // If we already had an entry, check to see if we are promoting this vtable 12551 // to required a definition. If so, we need to reappend to the VTableUses 12552 // list, since we may have already processed the first entry. 12553 if (DefinitionRequired && !Pos.first->second) { 12554 Pos.first->second = true; 12555 } else { 12556 // Otherwise, we can early exit. 12557 return; 12558 } 12559 } else { 12560 // The Microsoft ABI requires that we perform the destructor body 12561 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 12562 // the deleting destructor is emitted with the vtable, not with the 12563 // destructor definition as in the Itanium ABI. 12564 // If it has a definition, we do the check at that point instead. 12565 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12566 Class->hasUserDeclaredDestructor() && 12567 !Class->getDestructor()->isDefined() && 12568 !Class->getDestructor()->isDeleted()) { 12569 CXXDestructorDecl *DD = Class->getDestructor(); 12570 ContextRAII SavedContext(*this, DD); 12571 CheckDestructor(DD); 12572 } 12573 } 12574 12575 // Local classes need to have their virtual members marked 12576 // immediately. For all other classes, we mark their virtual members 12577 // at the end of the translation unit. 12578 if (Class->isLocalClass()) 12579 MarkVirtualMembersReferenced(Loc, Class); 12580 else 12581 VTableUses.push_back(std::make_pair(Class, Loc)); 12582 } 12583 12584 bool Sema::DefineUsedVTables() { 12585 LoadExternalVTableUses(); 12586 if (VTableUses.empty()) 12587 return false; 12588 12589 // Note: The VTableUses vector could grow as a result of marking 12590 // the members of a class as "used", so we check the size each 12591 // time through the loop and prefer indices (which are stable) to 12592 // iterators (which are not). 12593 bool DefinedAnything = false; 12594 for (unsigned I = 0; I != VTableUses.size(); ++I) { 12595 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 12596 if (!Class) 12597 continue; 12598 12599 SourceLocation Loc = VTableUses[I].second; 12600 12601 bool DefineVTable = true; 12602 12603 // If this class has a key function, but that key function is 12604 // defined in another translation unit, we don't need to emit the 12605 // vtable even though we're using it. 12606 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 12607 if (KeyFunction && !KeyFunction->hasBody()) { 12608 // The key function is in another translation unit. 12609 DefineVTable = false; 12610 TemplateSpecializationKind TSK = 12611 KeyFunction->getTemplateSpecializationKind(); 12612 assert(TSK != TSK_ExplicitInstantiationDefinition && 12613 TSK != TSK_ImplicitInstantiation && 12614 "Instantiations don't have key functions"); 12615 (void)TSK; 12616 } else if (!KeyFunction) { 12617 // If we have a class with no key function that is the subject 12618 // of an explicit instantiation declaration, suppress the 12619 // vtable; it will live with the explicit instantiation 12620 // definition. 12621 bool IsExplicitInstantiationDeclaration 12622 = Class->getTemplateSpecializationKind() 12623 == TSK_ExplicitInstantiationDeclaration; 12624 for (auto R : Class->redecls()) { 12625 TemplateSpecializationKind TSK 12626 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 12627 if (TSK == TSK_ExplicitInstantiationDeclaration) 12628 IsExplicitInstantiationDeclaration = true; 12629 else if (TSK == TSK_ExplicitInstantiationDefinition) { 12630 IsExplicitInstantiationDeclaration = false; 12631 break; 12632 } 12633 } 12634 12635 if (IsExplicitInstantiationDeclaration) 12636 DefineVTable = false; 12637 } 12638 12639 // The exception specifications for all virtual members may be needed even 12640 // if we are not providing an authoritative form of the vtable in this TU. 12641 // We may choose to emit it available_externally anyway. 12642 if (!DefineVTable) { 12643 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 12644 continue; 12645 } 12646 12647 // Mark all of the virtual members of this class as referenced, so 12648 // that we can build a vtable. Then, tell the AST consumer that a 12649 // vtable for this class is required. 12650 DefinedAnything = true; 12651 MarkVirtualMembersReferenced(Loc, Class); 12652 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12653 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 12654 12655 // Optionally warn if we're emitting a weak vtable. 12656 if (Class->isExternallyVisible() && 12657 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 12658 const FunctionDecl *KeyFunctionDef = nullptr; 12659 if (!KeyFunction || 12660 (KeyFunction->hasBody(KeyFunctionDef) && 12661 KeyFunctionDef->isInlined())) 12662 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 12663 TSK_ExplicitInstantiationDefinition 12664 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 12665 << Class; 12666 } 12667 } 12668 VTableUses.clear(); 12669 12670 return DefinedAnything; 12671 } 12672 12673 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 12674 const CXXRecordDecl *RD) { 12675 for (const auto *I : RD->methods()) 12676 if (I->isVirtual() && !I->isPure()) 12677 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 12678 } 12679 12680 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 12681 const CXXRecordDecl *RD) { 12682 // Mark all functions which will appear in RD's vtable as used. 12683 CXXFinalOverriderMap FinalOverriders; 12684 RD->getFinalOverriders(FinalOverriders); 12685 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 12686 E = FinalOverriders.end(); 12687 I != E; ++I) { 12688 for (OverridingMethods::const_iterator OI = I->second.begin(), 12689 OE = I->second.end(); 12690 OI != OE; ++OI) { 12691 assert(OI->second.size() > 0 && "no final overrider"); 12692 CXXMethodDecl *Overrider = OI->second.front().Method; 12693 12694 // C++ [basic.def.odr]p2: 12695 // [...] A virtual member function is used if it is not pure. [...] 12696 if (!Overrider->isPure()) 12697 MarkFunctionReferenced(Loc, Overrider); 12698 } 12699 } 12700 12701 // Only classes that have virtual bases need a VTT. 12702 if (RD->getNumVBases() == 0) 12703 return; 12704 12705 for (const auto &I : RD->bases()) { 12706 const CXXRecordDecl *Base = 12707 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 12708 if (Base->getNumVBases() == 0) 12709 continue; 12710 MarkVirtualMembersReferenced(Loc, Base); 12711 } 12712 } 12713 12714 /// SetIvarInitializers - This routine builds initialization ASTs for the 12715 /// Objective-C implementation whose ivars need be initialized. 12716 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 12717 if (!getLangOpts().CPlusPlus) 12718 return; 12719 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 12720 SmallVector<ObjCIvarDecl*, 8> ivars; 12721 CollectIvarsToConstructOrDestruct(OID, ivars); 12722 if (ivars.empty()) 12723 return; 12724 SmallVector<CXXCtorInitializer*, 32> AllToInit; 12725 for (unsigned i = 0; i < ivars.size(); i++) { 12726 FieldDecl *Field = ivars[i]; 12727 if (Field->isInvalidDecl()) 12728 continue; 12729 12730 CXXCtorInitializer *Member; 12731 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 12732 InitializationKind InitKind = 12733 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 12734 12735 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 12736 ExprResult MemberInit = 12737 InitSeq.Perform(*this, InitEntity, InitKind, None); 12738 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 12739 // Note, MemberInit could actually come back empty if no initialization 12740 // is required (e.g., because it would call a trivial default constructor) 12741 if (!MemberInit.get() || MemberInit.isInvalid()) 12742 continue; 12743 12744 Member = 12745 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 12746 SourceLocation(), 12747 MemberInit.getAs<Expr>(), 12748 SourceLocation()); 12749 AllToInit.push_back(Member); 12750 12751 // Be sure that the destructor is accessible and is marked as referenced. 12752 if (const RecordType *RecordTy 12753 = Context.getBaseElementType(Field->getType()) 12754 ->getAs<RecordType>()) { 12755 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 12756 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 12757 MarkFunctionReferenced(Field->getLocation(), Destructor); 12758 CheckDestructorAccess(Field->getLocation(), Destructor, 12759 PDiag(diag::err_access_dtor_ivar) 12760 << Context.getBaseElementType(Field->getType())); 12761 } 12762 } 12763 } 12764 ObjCImplementation->setIvarInitializers(Context, 12765 AllToInit.data(), AllToInit.size()); 12766 } 12767 } 12768 12769 static 12770 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 12771 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 12772 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 12773 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 12774 Sema &S) { 12775 if (Ctor->isInvalidDecl()) 12776 return; 12777 12778 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 12779 12780 // Target may not be determinable yet, for instance if this is a dependent 12781 // call in an uninstantiated template. 12782 if (Target) { 12783 const FunctionDecl *FNTarget = nullptr; 12784 (void)Target->hasBody(FNTarget); 12785 Target = const_cast<CXXConstructorDecl*>( 12786 cast_or_null<CXXConstructorDecl>(FNTarget)); 12787 } 12788 12789 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 12790 // Avoid dereferencing a null pointer here. 12791 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 12792 12793 if (!Current.insert(Canonical)) 12794 return; 12795 12796 // We know that beyond here, we aren't chaining into a cycle. 12797 if (!Target || !Target->isDelegatingConstructor() || 12798 Target->isInvalidDecl() || Valid.count(TCanonical)) { 12799 Valid.insert(Current.begin(), Current.end()); 12800 Current.clear(); 12801 // We've hit a cycle. 12802 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 12803 Current.count(TCanonical)) { 12804 // If we haven't diagnosed this cycle yet, do so now. 12805 if (!Invalid.count(TCanonical)) { 12806 S.Diag((*Ctor->init_begin())->getSourceLocation(), 12807 diag::warn_delegating_ctor_cycle) 12808 << Ctor; 12809 12810 // Don't add a note for a function delegating directly to itself. 12811 if (TCanonical != Canonical) 12812 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 12813 12814 CXXConstructorDecl *C = Target; 12815 while (C->getCanonicalDecl() != Canonical) { 12816 const FunctionDecl *FNTarget = nullptr; 12817 (void)C->getTargetConstructor()->hasBody(FNTarget); 12818 assert(FNTarget && "Ctor cycle through bodiless function"); 12819 12820 C = const_cast<CXXConstructorDecl*>( 12821 cast<CXXConstructorDecl>(FNTarget)); 12822 S.Diag(C->getLocation(), diag::note_which_delegates_to); 12823 } 12824 } 12825 12826 Invalid.insert(Current.begin(), Current.end()); 12827 Current.clear(); 12828 } else { 12829 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 12830 } 12831 } 12832 12833 12834 void Sema::CheckDelegatingCtorCycles() { 12835 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 12836 12837 for (DelegatingCtorDeclsType::iterator 12838 I = DelegatingCtorDecls.begin(ExternalSource), 12839 E = DelegatingCtorDecls.end(); 12840 I != E; ++I) 12841 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 12842 12843 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 12844 CE = Invalid.end(); 12845 CI != CE; ++CI) 12846 (*CI)->setInvalidDecl(); 12847 } 12848 12849 namespace { 12850 /// \brief AST visitor that finds references to the 'this' expression. 12851 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 12852 Sema &S; 12853 12854 public: 12855 explicit FindCXXThisExpr(Sema &S) : S(S) { } 12856 12857 bool VisitCXXThisExpr(CXXThisExpr *E) { 12858 S.Diag(E->getLocation(), diag::err_this_static_member_func) 12859 << E->isImplicit(); 12860 return false; 12861 } 12862 }; 12863 } 12864 12865 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 12866 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12867 if (!TSInfo) 12868 return false; 12869 12870 TypeLoc TL = TSInfo->getTypeLoc(); 12871 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12872 if (!ProtoTL) 12873 return false; 12874 12875 // C++11 [expr.prim.general]p3: 12876 // [The expression this] shall not appear before the optional 12877 // cv-qualifier-seq and it shall not appear within the declaration of a 12878 // static member function (although its type and value category are defined 12879 // within a static member function as they are within a non-static member 12880 // function). [ Note: this is because declaration matching does not occur 12881 // until the complete declarator is known. - end note ] 12882 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12883 FindCXXThisExpr Finder(*this); 12884 12885 // If the return type came after the cv-qualifier-seq, check it now. 12886 if (Proto->hasTrailingReturn() && 12887 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 12888 return true; 12889 12890 // Check the exception specification. 12891 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 12892 return true; 12893 12894 return checkThisInStaticMemberFunctionAttributes(Method); 12895 } 12896 12897 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 12898 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12899 if (!TSInfo) 12900 return false; 12901 12902 TypeLoc TL = TSInfo->getTypeLoc(); 12903 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12904 if (!ProtoTL) 12905 return false; 12906 12907 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12908 FindCXXThisExpr Finder(*this); 12909 12910 switch (Proto->getExceptionSpecType()) { 12911 case EST_Uninstantiated: 12912 case EST_Unevaluated: 12913 case EST_BasicNoexcept: 12914 case EST_DynamicNone: 12915 case EST_MSAny: 12916 case EST_None: 12917 break; 12918 12919 case EST_ComputedNoexcept: 12920 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 12921 return true; 12922 12923 case EST_Dynamic: 12924 for (const auto &E : Proto->exceptions()) { 12925 if (!Finder.TraverseType(E)) 12926 return true; 12927 } 12928 break; 12929 } 12930 12931 return false; 12932 } 12933 12934 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 12935 FindCXXThisExpr Finder(*this); 12936 12937 // Check attributes. 12938 for (const auto *A : Method->attrs()) { 12939 // FIXME: This should be emitted by tblgen. 12940 Expr *Arg = nullptr; 12941 ArrayRef<Expr *> Args; 12942 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 12943 Arg = G->getArg(); 12944 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 12945 Arg = G->getArg(); 12946 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 12947 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 12948 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 12949 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 12950 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 12951 Arg = ETLF->getSuccessValue(); 12952 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 12953 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 12954 Arg = STLF->getSuccessValue(); 12955 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 12956 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 12957 Arg = LR->getArg(); 12958 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 12959 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 12960 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 12961 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size()); 12962 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 12963 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size()); 12964 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 12965 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size()); 12966 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 12967 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size()); 12968 12969 if (Arg && !Finder.TraverseStmt(Arg)) 12970 return true; 12971 12972 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 12973 if (!Finder.TraverseStmt(Args[I])) 12974 return true; 12975 } 12976 } 12977 12978 return false; 12979 } 12980 12981 void 12982 Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 12983 ArrayRef<ParsedType> DynamicExceptions, 12984 ArrayRef<SourceRange> DynamicExceptionRanges, 12985 Expr *NoexceptExpr, 12986 SmallVectorImpl<QualType> &Exceptions, 12987 FunctionProtoType::ExceptionSpecInfo &ESI) { 12988 Exceptions.clear(); 12989 ESI.Type = EST; 12990 if (EST == EST_Dynamic) { 12991 Exceptions.reserve(DynamicExceptions.size()); 12992 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 12993 // FIXME: Preserve type source info. 12994 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 12995 12996 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 12997 collectUnexpandedParameterPacks(ET, Unexpanded); 12998 if (!Unexpanded.empty()) { 12999 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 13000 UPPC_ExceptionType, 13001 Unexpanded); 13002 continue; 13003 } 13004 13005 // Check that the type is valid for an exception spec, and 13006 // drop it if not. 13007 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 13008 Exceptions.push_back(ET); 13009 } 13010 ESI.Exceptions = Exceptions; 13011 return; 13012 } 13013 13014 if (EST == EST_ComputedNoexcept) { 13015 // If an error occurred, there's no expression here. 13016 if (NoexceptExpr) { 13017 assert((NoexceptExpr->isTypeDependent() || 13018 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 13019 Context.BoolTy) && 13020 "Parser should have made sure that the expression is boolean"); 13021 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 13022 ESI.Type = EST_BasicNoexcept; 13023 return; 13024 } 13025 13026 if (!NoexceptExpr->isValueDependent()) 13027 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 13028 diag::err_noexcept_needs_constant_expression, 13029 /*AllowFold*/ false).get(); 13030 ESI.NoexceptExpr = NoexceptExpr; 13031 } 13032 return; 13033 } 13034 } 13035 13036 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function 13037 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 13038 // Implicitly declared functions (e.g. copy constructors) are 13039 // __host__ __device__ 13040 if (D->isImplicit()) 13041 return CFT_HostDevice; 13042 13043 if (D->hasAttr<CUDAGlobalAttr>()) 13044 return CFT_Global; 13045 13046 if (D->hasAttr<CUDADeviceAttr>()) { 13047 if (D->hasAttr<CUDAHostAttr>()) 13048 return CFT_HostDevice; 13049 return CFT_Device; 13050 } 13051 13052 return CFT_Host; 13053 } 13054 13055 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 13056 CUDAFunctionTarget CalleeTarget) { 13057 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 13058 // Callable from the device only." 13059 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 13060 return true; 13061 13062 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 13063 // Callable from the host only." 13064 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 13065 // Callable from the host only." 13066 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 13067 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 13068 return true; 13069 13070 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 13071 return true; 13072 13073 return false; 13074 } 13075 13076 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 13077 /// 13078 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 13079 SourceLocation DeclStart, 13080 Declarator &D, Expr *BitWidth, 13081 InClassInitStyle InitStyle, 13082 AccessSpecifier AS, 13083 AttributeList *MSPropertyAttr) { 13084 IdentifierInfo *II = D.getIdentifier(); 13085 if (!II) { 13086 Diag(DeclStart, diag::err_anonymous_property); 13087 return nullptr; 13088 } 13089 SourceLocation Loc = D.getIdentifierLoc(); 13090 13091 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13092 QualType T = TInfo->getType(); 13093 if (getLangOpts().CPlusPlus) { 13094 CheckExtraCXXDefaultArguments(D); 13095 13096 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13097 UPPC_DataMemberType)) { 13098 D.setInvalidType(); 13099 T = Context.IntTy; 13100 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13101 } 13102 } 13103 13104 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13105 13106 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13107 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13108 diag::err_invalid_thread) 13109 << DeclSpec::getSpecifierName(TSCS); 13110 13111 // Check to see if this name was declared as a member previously 13112 NamedDecl *PrevDecl = nullptr; 13113 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13114 LookupName(Previous, S); 13115 switch (Previous.getResultKind()) { 13116 case LookupResult::Found: 13117 case LookupResult::FoundUnresolvedValue: 13118 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13119 break; 13120 13121 case LookupResult::FoundOverloaded: 13122 PrevDecl = Previous.getRepresentativeDecl(); 13123 break; 13124 13125 case LookupResult::NotFound: 13126 case LookupResult::NotFoundInCurrentInstantiation: 13127 case LookupResult::Ambiguous: 13128 break; 13129 } 13130 13131 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13132 // Maybe we will complain about the shadowed template parameter. 13133 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13134 // Just pretend that we didn't see the previous declaration. 13135 PrevDecl = nullptr; 13136 } 13137 13138 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13139 PrevDecl = nullptr; 13140 13141 SourceLocation TSSL = D.getLocStart(); 13142 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 13143 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 13144 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 13145 ProcessDeclAttributes(TUScope, NewPD, D); 13146 NewPD->setAccess(AS); 13147 13148 if (NewPD->isInvalidDecl()) 13149 Record->setInvalidDecl(); 13150 13151 if (D.getDeclSpec().isModulePrivateSpecified()) 13152 NewPD->setModulePrivate(); 13153 13154 if (NewPD->isInvalidDecl() && PrevDecl) { 13155 // Don't introduce NewFD into scope; there's already something 13156 // with the same name in the same scope. 13157 } else if (II) { 13158 PushOnScopeChains(NewPD, S); 13159 } else 13160 Record->addDecl(NewPD); 13161 13162 return NewPD; 13163 } 13164