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 "clang/Sema/Template.h" 40 #include "llvm/ADT/STLExtras.h" 41 #include "llvm/ADT/SmallString.h" 42 #include <map> 43 #include <set> 44 45 using namespace clang; 46 47 //===----------------------------------------------------------------------===// 48 // CheckDefaultArgumentVisitor 49 //===----------------------------------------------------------------------===// 50 51 namespace { 52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 53 /// the default argument of a parameter to determine whether it 54 /// contains any ill-formed subexpressions. For example, this will 55 /// diagnose the use of local variables or parameters within the 56 /// default argument expression. 57 class CheckDefaultArgumentVisitor 58 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 59 Expr *DefaultArg; 60 Sema *S; 61 62 public: 63 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 64 : DefaultArg(defarg), S(s) {} 65 66 bool VisitExpr(Expr *Node); 67 bool VisitDeclRefExpr(DeclRefExpr *DRE); 68 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 69 bool VisitLambdaExpr(LambdaExpr *Lambda); 70 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 71 }; 72 73 /// VisitExpr - Visit all of the children of this expression. 74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 75 bool IsInvalid = false; 76 for (Stmt *SubStmt : Node->children()) 77 IsInvalid |= Visit(SubStmt); 78 return IsInvalid; 79 } 80 81 /// VisitDeclRefExpr - Visit a reference to a declaration, to 82 /// determine whether this declaration can be used in the default 83 /// argument expression. 84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 85 NamedDecl *Decl = DRE->getDecl(); 86 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 87 // C++ [dcl.fct.default]p9 88 // Default arguments are evaluated each time the function is 89 // called. The order of evaluation of function arguments is 90 // unspecified. Consequently, parameters of a function shall not 91 // be used in default argument expressions, even if they are not 92 // evaluated. Parameters of a function declared before a default 93 // argument expression are in scope and can hide namespace and 94 // class member names. 95 return S->Diag(DRE->getLocStart(), 96 diag::err_param_default_argument_references_param) 97 << Param->getDeclName() << DefaultArg->getSourceRange(); 98 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 99 // C++ [dcl.fct.default]p7 100 // Local variables shall not be used in default argument 101 // expressions. 102 if (VDecl->isLocalVarDecl()) 103 return S->Diag(DRE->getLocStart(), 104 diag::err_param_default_argument_references_local) 105 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 106 } 107 108 return false; 109 } 110 111 /// VisitCXXThisExpr - Visit a C++ "this" expression. 112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 113 // C++ [dcl.fct.default]p8: 114 // The keyword this shall not be used in a default argument of a 115 // member function. 116 return S->Diag(ThisE->getLocStart(), 117 diag::err_param_default_argument_references_this) 118 << ThisE->getSourceRange(); 119 } 120 121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 122 bool Invalid = false; 123 for (PseudoObjectExpr::semantics_iterator 124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 125 Expr *E = *i; 126 127 // Look through bindings. 128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 129 E = OVE->getSourceExpr(); 130 assert(E && "pseudo-object binding without source expression?"); 131 } 132 133 Invalid |= Visit(E); 134 } 135 return Invalid; 136 } 137 138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 139 // C++11 [expr.lambda.prim]p13: 140 // A lambda-expression appearing in a default argument shall not 141 // implicitly or explicitly capture any entity. 142 if (Lambda->capture_begin() == Lambda->capture_end()) 143 return false; 144 145 return S->Diag(Lambda->getLocStart(), 146 diag::err_lambda_capture_default_arg); 147 } 148 } 149 150 void 151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 152 const CXXMethodDecl *Method) { 153 // If we have an MSAny spec already, don't bother. 154 if (!Method || ComputedEST == EST_MSAny) 155 return; 156 157 const FunctionProtoType *Proto 158 = Method->getType()->getAs<FunctionProtoType>(); 159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 160 if (!Proto) 161 return; 162 163 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 164 165 // If we have a throw-all spec at this point, ignore the function. 166 if (ComputedEST == EST_None) 167 return; 168 169 switch(EST) { 170 // If this function can throw any exceptions, make a note of that. 171 case EST_MSAny: 172 case EST_None: 173 ClearExceptions(); 174 ComputedEST = EST; 175 return; 176 // FIXME: If the call to this decl is using any of its default arguments, we 177 // need to search them for potentially-throwing calls. 178 // If this function has a basic noexcept, it doesn't affect the outcome. 179 case EST_BasicNoexcept: 180 return; 181 // If we're still at noexcept(true) and there's a nothrow() callee, 182 // change to that specification. 183 case EST_DynamicNone: 184 if (ComputedEST == EST_BasicNoexcept) 185 ComputedEST = EST_DynamicNone; 186 return; 187 // Check out noexcept specs. 188 case EST_ComputedNoexcept: 189 { 190 FunctionProtoType::NoexceptResult NR = 191 Proto->getNoexceptSpec(Self->Context); 192 assert(NR != FunctionProtoType::NR_NoNoexcept && 193 "Must have noexcept result for EST_ComputedNoexcept."); 194 assert(NR != FunctionProtoType::NR_Dependent && 195 "Should not generate implicit declarations for dependent cases, " 196 "and don't know how to handle them anyway."); 197 // noexcept(false) -> no spec on the new function 198 if (NR == FunctionProtoType::NR_Throw) { 199 ClearExceptions(); 200 ComputedEST = EST_None; 201 } 202 // noexcept(true) won't change anything either. 203 return; 204 } 205 default: 206 break; 207 } 208 assert(EST == EST_Dynamic && "EST case not considered earlier."); 209 assert(ComputedEST != EST_None && 210 "Shouldn't collect exceptions when throw-all is guaranteed."); 211 ComputedEST = EST_Dynamic; 212 // Record the exceptions in this function's exception specification. 213 for (const auto &E : Proto->exceptions()) 214 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 215 Exceptions.push_back(E); 216 } 217 218 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 219 if (!E || ComputedEST == EST_MSAny) 220 return; 221 222 // FIXME: 223 // 224 // C++0x [except.spec]p14: 225 // [An] implicit exception-specification specifies the type-id T if and 226 // only if T is allowed by the exception-specification of a function directly 227 // invoked by f's implicit definition; f shall allow all exceptions if any 228 // function it directly invokes allows all exceptions, and f shall allow no 229 // exceptions if every function it directly invokes allows no exceptions. 230 // 231 // Note in particular that if an implicit exception-specification is generated 232 // for a function containing a throw-expression, that specification can still 233 // be noexcept(true). 234 // 235 // Note also that 'directly invoked' is not defined in the standard, and there 236 // is no indication that we should only consider potentially-evaluated calls. 237 // 238 // Ultimately we should implement the intent of the standard: the exception 239 // specification should be the set of exceptions which can be thrown by the 240 // implicit definition. For now, we assume that any non-nothrow expression can 241 // throw any exception. 242 243 if (Self->canThrow(E)) 244 ComputedEST = EST_None; 245 } 246 247 bool 248 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 249 SourceLocation EqualLoc) { 250 if (RequireCompleteType(Param->getLocation(), Param->getType(), 251 diag::err_typecheck_decl_incomplete_type)) { 252 Param->setInvalidDecl(); 253 return true; 254 } 255 256 // C++ [dcl.fct.default]p5 257 // A default argument expression is implicitly converted (clause 258 // 4) to the parameter type. The default argument expression has 259 // the same semantic constraints as the initializer expression in 260 // a declaration of a variable of the parameter type, using the 261 // copy-initialization semantics (8.5). 262 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 263 Param); 264 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 265 EqualLoc); 266 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 267 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 268 if (Result.isInvalid()) 269 return true; 270 Arg = Result.getAs<Expr>(); 271 272 CheckCompletedExpr(Arg, EqualLoc); 273 Arg = MaybeCreateExprWithCleanups(Arg); 274 275 // Okay: add the default argument to the parameter 276 Param->setDefaultArg(Arg); 277 278 // We have already instantiated this parameter; provide each of the 279 // instantiations with the uninstantiated default argument. 280 UnparsedDefaultArgInstantiationsMap::iterator InstPos 281 = UnparsedDefaultArgInstantiations.find(Param); 282 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 283 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 284 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 285 286 // We're done tracking this parameter's instantiations. 287 UnparsedDefaultArgInstantiations.erase(InstPos); 288 } 289 290 return false; 291 } 292 293 /// ActOnParamDefaultArgument - Check whether the default argument 294 /// provided for a function parameter is well-formed. If so, attach it 295 /// to the parameter declaration. 296 void 297 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 298 Expr *DefaultArg) { 299 if (!param || !DefaultArg) 300 return; 301 302 ParmVarDecl *Param = cast<ParmVarDecl>(param); 303 UnparsedDefaultArgLocs.erase(Param); 304 305 // Default arguments are only permitted in C++ 306 if (!getLangOpts().CPlusPlus) { 307 Diag(EqualLoc, diag::err_param_default_argument) 308 << DefaultArg->getSourceRange(); 309 Param->setInvalidDecl(); 310 return; 311 } 312 313 // Check for unexpanded parameter packs. 314 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 315 Param->setInvalidDecl(); 316 return; 317 } 318 319 // C++11 [dcl.fct.default]p3 320 // A default argument expression [...] shall not be specified for a 321 // parameter pack. 322 if (Param->isParameterPack()) { 323 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 324 << DefaultArg->getSourceRange(); 325 return; 326 } 327 328 // Check that the default argument is well-formed 329 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 330 if (DefaultArgChecker.Visit(DefaultArg)) { 331 Param->setInvalidDecl(); 332 return; 333 } 334 335 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 336 } 337 338 /// ActOnParamUnparsedDefaultArgument - We've seen a default 339 /// argument for a function parameter, but we can't parse it yet 340 /// because we're inside a class definition. Note that this default 341 /// argument will be parsed later. 342 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 343 SourceLocation EqualLoc, 344 SourceLocation ArgLoc) { 345 if (!param) 346 return; 347 348 ParmVarDecl *Param = cast<ParmVarDecl>(param); 349 Param->setUnparsedDefaultArg(); 350 UnparsedDefaultArgLocs[Param] = ArgLoc; 351 } 352 353 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 354 /// the default argument for the parameter param failed. 355 void Sema::ActOnParamDefaultArgumentError(Decl *param, 356 SourceLocation EqualLoc) { 357 if (!param) 358 return; 359 360 ParmVarDecl *Param = cast<ParmVarDecl>(param); 361 Param->setInvalidDecl(); 362 UnparsedDefaultArgLocs.erase(Param); 363 Param->setDefaultArg(new(Context) 364 OpaqueValueExpr(EqualLoc, 365 Param->getType().getNonReferenceType(), 366 VK_RValue)); 367 } 368 369 /// CheckExtraCXXDefaultArguments - Check for any extra default 370 /// arguments in the declarator, which is not a function declaration 371 /// or definition and therefore is not permitted to have default 372 /// arguments. This routine should be invoked for every declarator 373 /// that is not a function declaration or definition. 374 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 375 // C++ [dcl.fct.default]p3 376 // A default argument expression shall be specified only in the 377 // parameter-declaration-clause of a function declaration or in a 378 // template-parameter (14.1). It shall not be specified for a 379 // parameter pack. If it is specified in a 380 // parameter-declaration-clause, it shall not occur within a 381 // declarator or abstract-declarator of a parameter-declaration. 382 bool MightBeFunction = D.isFunctionDeclarationContext(); 383 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 384 DeclaratorChunk &chunk = D.getTypeObject(i); 385 if (chunk.Kind == DeclaratorChunk::Function) { 386 if (MightBeFunction) { 387 // This is a function declaration. It can have default arguments, but 388 // keep looking in case its return type is a function type with default 389 // arguments. 390 MightBeFunction = false; 391 continue; 392 } 393 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 394 ++argIdx) { 395 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 396 if (Param->hasUnparsedDefaultArg()) { 397 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens; 398 SourceRange SR; 399 if (Toks->size() > 1) 400 SR = SourceRange((*Toks)[1].getLocation(), 401 Toks->back().getLocation()); 402 else 403 SR = UnparsedDefaultArgLocs[Param]; 404 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 405 << SR; 406 delete Toks; 407 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr; 408 } else if (Param->getDefaultArg()) { 409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 410 << Param->getDefaultArg()->getSourceRange(); 411 Param->setDefaultArg(nullptr); 412 } 413 } 414 } else if (chunk.Kind != DeclaratorChunk::Paren) { 415 MightBeFunction = false; 416 } 417 } 418 } 419 420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 421 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 422 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 423 if (!PVD->hasDefaultArg()) 424 return false; 425 if (!PVD->hasInheritedDefaultArg()) 426 return true; 427 } 428 return false; 429 } 430 431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 432 /// function, once we already know that they have the same 433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 434 /// error, false otherwise. 435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 436 Scope *S) { 437 bool Invalid = false; 438 439 // The declaration context corresponding to the scope is the semantic 440 // parent, unless this is a local function declaration, in which case 441 // it is that surrounding function. 442 DeclContext *ScopeDC = New->isLocalExternDecl() 443 ? New->getLexicalDeclContext() 444 : New->getDeclContext(); 445 446 // Find the previous declaration for the purpose of default arguments. 447 FunctionDecl *PrevForDefaultArgs = Old; 448 for (/**/; PrevForDefaultArgs; 449 // Don't bother looking back past the latest decl if this is a local 450 // extern declaration; nothing else could work. 451 PrevForDefaultArgs = New->isLocalExternDecl() 452 ? nullptr 453 : PrevForDefaultArgs->getPreviousDecl()) { 454 // Ignore hidden declarations. 455 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 456 continue; 457 458 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 459 !New->isCXXClassMember()) { 460 // Ignore default arguments of old decl if they are not in 461 // the same scope and this is not an out-of-line definition of 462 // a member function. 463 continue; 464 } 465 466 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 467 // If only one of these is a local function declaration, then they are 468 // declared in different scopes, even though isDeclInScope may think 469 // they're in the same scope. (If both are local, the scope check is 470 // sufficent, and if neither is local, then they are in the same scope.) 471 continue; 472 } 473 474 // We found our guy. 475 break; 476 } 477 478 // C++ [dcl.fct.default]p4: 479 // For non-template functions, default arguments can be added in 480 // later declarations of a function in the same 481 // scope. Declarations in different scopes have completely 482 // distinct sets of default arguments. That is, declarations in 483 // inner scopes do not acquire default arguments from 484 // declarations in outer scopes, and vice versa. In a given 485 // function declaration, all parameters subsequent to a 486 // parameter with a default argument shall have default 487 // arguments supplied in this or previous declarations. A 488 // default argument shall not be redefined by a later 489 // declaration (not even to the same value). 490 // 491 // C++ [dcl.fct.default]p6: 492 // Except for member functions of class templates, the default arguments 493 // in a member function definition that appears outside of the class 494 // definition are added to the set of default arguments provided by the 495 // member function declaration in the class definition. 496 for (unsigned p = 0, NumParams = PrevForDefaultArgs 497 ? PrevForDefaultArgs->getNumParams() 498 : 0; 499 p < NumParams; ++p) { 500 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 501 ParmVarDecl *NewParam = New->getParamDecl(p); 502 503 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 504 bool NewParamHasDfl = NewParam->hasDefaultArg(); 505 506 if (OldParamHasDfl && NewParamHasDfl) { 507 unsigned DiagDefaultParamID = 508 diag::err_param_default_argument_redefinition; 509 510 // MSVC accepts that default parameters be redefined for member functions 511 // of template class. The new default parameter's value is ignored. 512 Invalid = true; 513 if (getLangOpts().MicrosoftExt) { 514 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 515 if (MD && MD->getParent()->getDescribedClassTemplate()) { 516 // Merge the old default argument into the new parameter. 517 NewParam->setHasInheritedDefaultArg(); 518 if (OldParam->hasUninstantiatedDefaultArg()) 519 NewParam->setUninstantiatedDefaultArg( 520 OldParam->getUninstantiatedDefaultArg()); 521 else 522 NewParam->setDefaultArg(OldParam->getInit()); 523 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 524 Invalid = false; 525 } 526 } 527 528 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 529 // hint here. Alternatively, we could walk the type-source information 530 // for NewParam to find the last source location in the type... but it 531 // isn't worth the effort right now. This is the kind of test case that 532 // is hard to get right: 533 // int f(int); 534 // void g(int (*fp)(int) = f); 535 // void g(int (*fp)(int) = &f); 536 Diag(NewParam->getLocation(), DiagDefaultParamID) 537 << NewParam->getDefaultArgRange(); 538 539 // Look for the function declaration where the default argument was 540 // actually written, which may be a declaration prior to Old. 541 for (auto Older = PrevForDefaultArgs; 542 OldParam->hasInheritedDefaultArg(); /**/) { 543 Older = Older->getPreviousDecl(); 544 OldParam = Older->getParamDecl(p); 545 } 546 547 Diag(OldParam->getLocation(), diag::note_previous_definition) 548 << OldParam->getDefaultArgRange(); 549 } else if (OldParamHasDfl) { 550 // Merge the old default argument into the new parameter. 551 // It's important to use getInit() here; getDefaultArg() 552 // strips off any top-level ExprWithCleanups. 553 NewParam->setHasInheritedDefaultArg(); 554 if (OldParam->hasUnparsedDefaultArg()) 555 NewParam->setUnparsedDefaultArg(); 556 else if (OldParam->hasUninstantiatedDefaultArg()) 557 NewParam->setUninstantiatedDefaultArg( 558 OldParam->getUninstantiatedDefaultArg()); 559 else 560 NewParam->setDefaultArg(OldParam->getInit()); 561 } else if (NewParamHasDfl) { 562 if (New->getDescribedFunctionTemplate()) { 563 // Paragraph 4, quoted above, only applies to non-template functions. 564 Diag(NewParam->getLocation(), 565 diag::err_param_default_argument_template_redecl) 566 << NewParam->getDefaultArgRange(); 567 Diag(PrevForDefaultArgs->getLocation(), 568 diag::note_template_prev_declaration) 569 << false; 570 } else if (New->getTemplateSpecializationKind() 571 != TSK_ImplicitInstantiation && 572 New->getTemplateSpecializationKind() != TSK_Undeclared) { 573 // C++ [temp.expr.spec]p21: 574 // Default function arguments shall not be specified in a declaration 575 // or a definition for one of the following explicit specializations: 576 // - the explicit specialization of a function template; 577 // - the explicit specialization of a member function template; 578 // - the explicit specialization of a member function of a class 579 // template where the class template specialization to which the 580 // member function specialization belongs is implicitly 581 // instantiated. 582 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 583 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 584 << New->getDeclName() 585 << NewParam->getDefaultArgRange(); 586 } else if (New->getDeclContext()->isDependentContext()) { 587 // C++ [dcl.fct.default]p6 (DR217): 588 // Default arguments for a member function of a class template shall 589 // be specified on the initial declaration of the member function 590 // within the class template. 591 // 592 // Reading the tea leaves a bit in DR217 and its reference to DR205 593 // leads me to the conclusion that one cannot add default function 594 // arguments for an out-of-line definition of a member function of a 595 // dependent type. 596 int WhichKind = 2; 597 if (CXXRecordDecl *Record 598 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 599 if (Record->getDescribedClassTemplate()) 600 WhichKind = 0; 601 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 602 WhichKind = 1; 603 else 604 WhichKind = 2; 605 } 606 607 Diag(NewParam->getLocation(), 608 diag::err_param_default_argument_member_template_redecl) 609 << WhichKind 610 << NewParam->getDefaultArgRange(); 611 } 612 } 613 } 614 615 // DR1344: If a default argument is added outside a class definition and that 616 // default argument makes the function a special member function, the program 617 // is ill-formed. This can only happen for constructors. 618 if (isa<CXXConstructorDecl>(New) && 619 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 620 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 621 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 622 if (NewSM != OldSM) { 623 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 624 assert(NewParam->hasDefaultArg()); 625 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 626 << NewParam->getDefaultArgRange() << NewSM; 627 Diag(Old->getLocation(), diag::note_previous_declaration); 628 } 629 } 630 631 const FunctionDecl *Def; 632 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 633 // template has a constexpr specifier then all its declarations shall 634 // contain the constexpr specifier. 635 if (New->isConstexpr() != Old->isConstexpr()) { 636 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 637 << New << New->isConstexpr(); 638 Diag(Old->getLocation(), diag::note_previous_declaration); 639 Invalid = true; 640 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 641 Old->isDefined(Def)) { 642 // C++11 [dcl.fcn.spec]p4: 643 // If the definition of a function appears in a translation unit before its 644 // first declaration as inline, the program is ill-formed. 645 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 646 Diag(Def->getLocation(), diag::note_previous_definition); 647 Invalid = true; 648 } 649 650 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 651 // argument expression, that declaration shall be a definition and shall be 652 // the only declaration of the function or function template in the 653 // translation unit. 654 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 655 functionDeclHasDefaultArgument(Old)) { 656 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 657 Diag(Old->getLocation(), diag::note_previous_declaration); 658 Invalid = true; 659 } 660 661 if (CheckEquivalentExceptionSpec(Old, New)) 662 Invalid = true; 663 664 return Invalid; 665 } 666 667 /// \brief Merge the exception specifications of two variable declarations. 668 /// 669 /// This is called when there's a redeclaration of a VarDecl. The function 670 /// checks if the redeclaration might have an exception specification and 671 /// validates compatibility and merges the specs if necessary. 672 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 673 // Shortcut if exceptions are disabled. 674 if (!getLangOpts().CXXExceptions) 675 return; 676 677 assert(Context.hasSameType(New->getType(), Old->getType()) && 678 "Should only be called if types are otherwise the same."); 679 680 QualType NewType = New->getType(); 681 QualType OldType = Old->getType(); 682 683 // We're only interested in pointers and references to functions, as well 684 // as pointers to member functions. 685 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 686 NewType = R->getPointeeType(); 687 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 688 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 689 NewType = P->getPointeeType(); 690 OldType = OldType->getAs<PointerType>()->getPointeeType(); 691 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 692 NewType = M->getPointeeType(); 693 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 694 } 695 696 if (!NewType->isFunctionProtoType()) 697 return; 698 699 // There's lots of special cases for functions. For function pointers, system 700 // libraries are hopefully not as broken so that we don't need these 701 // workarounds. 702 if (CheckEquivalentExceptionSpec( 703 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 704 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 705 New->setInvalidDecl(); 706 } 707 } 708 709 /// CheckCXXDefaultArguments - Verify that the default arguments for a 710 /// function declaration are well-formed according to C++ 711 /// [dcl.fct.default]. 712 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 713 unsigned NumParams = FD->getNumParams(); 714 unsigned p; 715 716 // Find first parameter with a default argument 717 for (p = 0; p < NumParams; ++p) { 718 ParmVarDecl *Param = FD->getParamDecl(p); 719 if (Param->hasDefaultArg()) 720 break; 721 } 722 723 // C++11 [dcl.fct.default]p4: 724 // In a given function declaration, each parameter subsequent to a parameter 725 // with a default argument shall have a default argument supplied in this or 726 // a previous declaration or shall be a function parameter pack. A default 727 // argument shall not be redefined by a later declaration (not even to the 728 // same value). 729 unsigned LastMissingDefaultArg = 0; 730 for (; p < NumParams; ++p) { 731 ParmVarDecl *Param = FD->getParamDecl(p); 732 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 733 if (Param->isInvalidDecl()) 734 /* We already complained about this parameter. */; 735 else if (Param->getIdentifier()) 736 Diag(Param->getLocation(), 737 diag::err_param_default_argument_missing_name) 738 << Param->getIdentifier(); 739 else 740 Diag(Param->getLocation(), 741 diag::err_param_default_argument_missing); 742 743 LastMissingDefaultArg = p; 744 } 745 } 746 747 if (LastMissingDefaultArg > 0) { 748 // Some default arguments were missing. Clear out all of the 749 // default arguments up to (and including) the last missing 750 // default argument, so that we leave the function parameters 751 // in a semantically valid state. 752 for (p = 0; p <= LastMissingDefaultArg; ++p) { 753 ParmVarDecl *Param = FD->getParamDecl(p); 754 if (Param->hasDefaultArg()) { 755 Param->setDefaultArg(nullptr); 756 } 757 } 758 } 759 } 760 761 // CheckConstexprParameterTypes - Check whether a function's parameter types 762 // are all literal types. If so, return true. If not, produce a suitable 763 // diagnostic and return false. 764 static bool CheckConstexprParameterTypes(Sema &SemaRef, 765 const FunctionDecl *FD) { 766 unsigned ArgIndex = 0; 767 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 768 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 769 e = FT->param_type_end(); 770 i != e; ++i, ++ArgIndex) { 771 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 772 SourceLocation ParamLoc = PD->getLocation(); 773 if (!(*i)->isDependentType() && 774 SemaRef.RequireLiteralType(ParamLoc, *i, 775 diag::err_constexpr_non_literal_param, 776 ArgIndex+1, PD->getSourceRange(), 777 isa<CXXConstructorDecl>(FD))) 778 return false; 779 } 780 return true; 781 } 782 783 /// \brief Get diagnostic %select index for tag kind for 784 /// record diagnostic message. 785 /// WARNING: Indexes apply to particular diagnostics only! 786 /// 787 /// \returns diagnostic %select index. 788 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 789 switch (Tag) { 790 case TTK_Struct: return 0; 791 case TTK_Interface: return 1; 792 case TTK_Class: return 2; 793 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 794 } 795 } 796 797 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 798 // the requirements of a constexpr function definition or a constexpr 799 // constructor definition. If so, return true. If not, produce appropriate 800 // diagnostics and return false. 801 // 802 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 803 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 804 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 805 if (MD && MD->isInstance()) { 806 // C++11 [dcl.constexpr]p4: 807 // The definition of a constexpr constructor shall satisfy the following 808 // constraints: 809 // - the class shall not have any virtual base classes; 810 const CXXRecordDecl *RD = MD->getParent(); 811 if (RD->getNumVBases()) { 812 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 813 << isa<CXXConstructorDecl>(NewFD) 814 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 815 for (const auto &I : RD->vbases()) 816 Diag(I.getLocStart(), 817 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 818 return false; 819 } 820 } 821 822 if (!isa<CXXConstructorDecl>(NewFD)) { 823 // C++11 [dcl.constexpr]p3: 824 // The definition of a constexpr function shall satisfy the following 825 // constraints: 826 // - it shall not be virtual; 827 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 828 if (Method && Method->isVirtual()) { 829 Method = Method->getCanonicalDecl(); 830 Diag(Method->getLocation(), diag::err_constexpr_virtual); 831 832 // If it's not obvious why this function is virtual, find an overridden 833 // function which uses the 'virtual' keyword. 834 const CXXMethodDecl *WrittenVirtual = Method; 835 while (!WrittenVirtual->isVirtualAsWritten()) 836 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 837 if (WrittenVirtual != Method) 838 Diag(WrittenVirtual->getLocation(), 839 diag::note_overridden_virtual_function); 840 return false; 841 } 842 843 // - its return type shall be a literal type; 844 QualType RT = NewFD->getReturnType(); 845 if (!RT->isDependentType() && 846 RequireLiteralType(NewFD->getLocation(), RT, 847 diag::err_constexpr_non_literal_return)) 848 return false; 849 } 850 851 // - each of its parameter types shall be a literal type; 852 if (!CheckConstexprParameterTypes(*this, NewFD)) 853 return false; 854 855 return true; 856 } 857 858 /// Check the given declaration statement is legal within a constexpr function 859 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 860 /// 861 /// \return true if the body is OK (maybe only as an extension), false if we 862 /// have diagnosed a problem. 863 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 864 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 865 // C++11 [dcl.constexpr]p3 and p4: 866 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 867 // contain only 868 for (const auto *DclIt : DS->decls()) { 869 switch (DclIt->getKind()) { 870 case Decl::StaticAssert: 871 case Decl::Using: 872 case Decl::UsingShadow: 873 case Decl::UsingDirective: 874 case Decl::UnresolvedUsingTypename: 875 case Decl::UnresolvedUsingValue: 876 // - static_assert-declarations 877 // - using-declarations, 878 // - using-directives, 879 continue; 880 881 case Decl::Typedef: 882 case Decl::TypeAlias: { 883 // - typedef declarations and alias-declarations that do not define 884 // classes or enumerations, 885 const auto *TN = cast<TypedefNameDecl>(DclIt); 886 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 887 // Don't allow variably-modified types in constexpr functions. 888 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 889 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 890 << TL.getSourceRange() << TL.getType() 891 << isa<CXXConstructorDecl>(Dcl); 892 return false; 893 } 894 continue; 895 } 896 897 case Decl::Enum: 898 case Decl::CXXRecord: 899 // C++1y allows types to be defined, not just declared. 900 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 901 SemaRef.Diag(DS->getLocStart(), 902 SemaRef.getLangOpts().CPlusPlus14 903 ? diag::warn_cxx11_compat_constexpr_type_definition 904 : diag::ext_constexpr_type_definition) 905 << isa<CXXConstructorDecl>(Dcl); 906 continue; 907 908 case Decl::EnumConstant: 909 case Decl::IndirectField: 910 case Decl::ParmVar: 911 // These can only appear with other declarations which are banned in 912 // C++11 and permitted in C++1y, so ignore them. 913 continue; 914 915 case Decl::Var: { 916 // C++1y [dcl.constexpr]p3 allows anything except: 917 // a definition of a variable of non-literal type or of static or 918 // thread storage duration or for which no initialization is performed. 919 const auto *VD = cast<VarDecl>(DclIt); 920 if (VD->isThisDeclarationADefinition()) { 921 if (VD->isStaticLocal()) { 922 SemaRef.Diag(VD->getLocation(), 923 diag::err_constexpr_local_var_static) 924 << isa<CXXConstructorDecl>(Dcl) 925 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 926 return false; 927 } 928 if (!VD->getType()->isDependentType() && 929 SemaRef.RequireLiteralType( 930 VD->getLocation(), VD->getType(), 931 diag::err_constexpr_local_var_non_literal_type, 932 isa<CXXConstructorDecl>(Dcl))) 933 return false; 934 if (!VD->getType()->isDependentType() && 935 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 936 SemaRef.Diag(VD->getLocation(), 937 diag::err_constexpr_local_var_no_init) 938 << isa<CXXConstructorDecl>(Dcl); 939 return false; 940 } 941 } 942 SemaRef.Diag(VD->getLocation(), 943 SemaRef.getLangOpts().CPlusPlus14 944 ? diag::warn_cxx11_compat_constexpr_local_var 945 : diag::ext_constexpr_local_var) 946 << isa<CXXConstructorDecl>(Dcl); 947 continue; 948 } 949 950 case Decl::NamespaceAlias: 951 case Decl::Function: 952 // These are disallowed in C++11 and permitted in C++1y. Allow them 953 // everywhere as an extension. 954 if (!Cxx1yLoc.isValid()) 955 Cxx1yLoc = DS->getLocStart(); 956 continue; 957 958 default: 959 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 960 << isa<CXXConstructorDecl>(Dcl); 961 return false; 962 } 963 } 964 965 return true; 966 } 967 968 /// Check that the given field is initialized within a constexpr constructor. 969 /// 970 /// \param Dcl The constexpr constructor being checked. 971 /// \param Field The field being checked. This may be a member of an anonymous 972 /// struct or union nested within the class being checked. 973 /// \param Inits All declarations, including anonymous struct/union members and 974 /// indirect members, for which any initialization was provided. 975 /// \param Diagnosed Set to true if an error is produced. 976 static void CheckConstexprCtorInitializer(Sema &SemaRef, 977 const FunctionDecl *Dcl, 978 FieldDecl *Field, 979 llvm::SmallSet<Decl*, 16> &Inits, 980 bool &Diagnosed) { 981 if (Field->isInvalidDecl()) 982 return; 983 984 if (Field->isUnnamedBitfield()) 985 return; 986 987 // Anonymous unions with no variant members and empty anonymous structs do not 988 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 989 // indirect fields don't need initializing. 990 if (Field->isAnonymousStructOrUnion() && 991 (Field->getType()->isUnionType() 992 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 993 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 994 return; 995 996 if (!Inits.count(Field)) { 997 if (!Diagnosed) { 998 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 999 Diagnosed = true; 1000 } 1001 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 1002 } else if (Field->isAnonymousStructOrUnion()) { 1003 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1004 for (auto *I : RD->fields()) 1005 // If an anonymous union contains an anonymous struct of which any member 1006 // is initialized, all members must be initialized. 1007 if (!RD->isUnion() || Inits.count(I)) 1008 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 1009 } 1010 } 1011 1012 /// Check the provided statement is allowed in a constexpr function 1013 /// definition. 1014 static bool 1015 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1016 SmallVectorImpl<SourceLocation> &ReturnStmts, 1017 SourceLocation &Cxx1yLoc) { 1018 // - its function-body shall be [...] a compound-statement that contains only 1019 switch (S->getStmtClass()) { 1020 case Stmt::NullStmtClass: 1021 // - null statements, 1022 return true; 1023 1024 case Stmt::DeclStmtClass: 1025 // - static_assert-declarations 1026 // - using-declarations, 1027 // - using-directives, 1028 // - typedef declarations and alias-declarations that do not define 1029 // classes or enumerations, 1030 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 1031 return false; 1032 return true; 1033 1034 case Stmt::ReturnStmtClass: 1035 // - and exactly one return statement; 1036 if (isa<CXXConstructorDecl>(Dcl)) { 1037 // C++1y allows return statements in constexpr constructors. 1038 if (!Cxx1yLoc.isValid()) 1039 Cxx1yLoc = S->getLocStart(); 1040 return true; 1041 } 1042 1043 ReturnStmts.push_back(S->getLocStart()); 1044 return true; 1045 1046 case Stmt::CompoundStmtClass: { 1047 // C++1y allows compound-statements. 1048 if (!Cxx1yLoc.isValid()) 1049 Cxx1yLoc = S->getLocStart(); 1050 1051 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1052 for (auto *BodyIt : CompStmt->body()) { 1053 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1054 Cxx1yLoc)) 1055 return false; 1056 } 1057 return true; 1058 } 1059 1060 case Stmt::AttributedStmtClass: 1061 if (!Cxx1yLoc.isValid()) 1062 Cxx1yLoc = S->getLocStart(); 1063 return true; 1064 1065 case Stmt::IfStmtClass: { 1066 // C++1y allows if-statements. 1067 if (!Cxx1yLoc.isValid()) 1068 Cxx1yLoc = S->getLocStart(); 1069 1070 IfStmt *If = cast<IfStmt>(S); 1071 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1072 Cxx1yLoc)) 1073 return false; 1074 if (If->getElse() && 1075 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1076 Cxx1yLoc)) 1077 return false; 1078 return true; 1079 } 1080 1081 case Stmt::WhileStmtClass: 1082 case Stmt::DoStmtClass: 1083 case Stmt::ForStmtClass: 1084 case Stmt::CXXForRangeStmtClass: 1085 case Stmt::ContinueStmtClass: 1086 // C++1y allows all of these. We don't allow them as extensions in C++11, 1087 // because they don't make sense without variable mutation. 1088 if (!SemaRef.getLangOpts().CPlusPlus14) 1089 break; 1090 if (!Cxx1yLoc.isValid()) 1091 Cxx1yLoc = S->getLocStart(); 1092 for (Stmt *SubStmt : S->children()) 1093 if (SubStmt && 1094 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1095 Cxx1yLoc)) 1096 return false; 1097 return true; 1098 1099 case Stmt::SwitchStmtClass: 1100 case Stmt::CaseStmtClass: 1101 case Stmt::DefaultStmtClass: 1102 case Stmt::BreakStmtClass: 1103 // C++1y allows switch-statements, and since they don't need variable 1104 // mutation, we can reasonably allow them in C++11 as an extension. 1105 if (!Cxx1yLoc.isValid()) 1106 Cxx1yLoc = S->getLocStart(); 1107 for (Stmt *SubStmt : S->children()) 1108 if (SubStmt && 1109 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1110 Cxx1yLoc)) 1111 return false; 1112 return true; 1113 1114 default: 1115 if (!isa<Expr>(S)) 1116 break; 1117 1118 // C++1y allows expression-statements. 1119 if (!Cxx1yLoc.isValid()) 1120 Cxx1yLoc = S->getLocStart(); 1121 return true; 1122 } 1123 1124 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1125 << isa<CXXConstructorDecl>(Dcl); 1126 return false; 1127 } 1128 1129 /// Check the body for the given constexpr function declaration only contains 1130 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1131 /// 1132 /// \return true if the body is OK, false if we have diagnosed a problem. 1133 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1134 if (isa<CXXTryStmt>(Body)) { 1135 // C++11 [dcl.constexpr]p3: 1136 // The definition of a constexpr function shall satisfy the following 1137 // constraints: [...] 1138 // - its function-body shall be = delete, = default, or a 1139 // compound-statement 1140 // 1141 // C++11 [dcl.constexpr]p4: 1142 // In the definition of a constexpr constructor, [...] 1143 // - its function-body shall not be a function-try-block; 1144 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1145 << isa<CXXConstructorDecl>(Dcl); 1146 return false; 1147 } 1148 1149 SmallVector<SourceLocation, 4> ReturnStmts; 1150 1151 // - its function-body shall be [...] a compound-statement that contains only 1152 // [... list of cases ...] 1153 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1154 SourceLocation Cxx1yLoc; 1155 for (auto *BodyIt : CompBody->body()) { 1156 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1157 return false; 1158 } 1159 1160 if (Cxx1yLoc.isValid()) 1161 Diag(Cxx1yLoc, 1162 getLangOpts().CPlusPlus14 1163 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1164 : diag::ext_constexpr_body_invalid_stmt) 1165 << isa<CXXConstructorDecl>(Dcl); 1166 1167 if (const CXXConstructorDecl *Constructor 1168 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1169 const CXXRecordDecl *RD = Constructor->getParent(); 1170 // DR1359: 1171 // - every non-variant non-static data member and base class sub-object 1172 // shall be initialized; 1173 // DR1460: 1174 // - if the class is a union having variant members, exactly one of them 1175 // shall be initialized; 1176 if (RD->isUnion()) { 1177 if (Constructor->getNumCtorInitializers() == 0 && 1178 RD->hasVariantMembers()) { 1179 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1180 return false; 1181 } 1182 } else if (!Constructor->isDependentContext() && 1183 !Constructor->isDelegatingConstructor()) { 1184 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1185 1186 // Skip detailed checking if we have enough initializers, and we would 1187 // allow at most one initializer per member. 1188 bool AnyAnonStructUnionMembers = false; 1189 unsigned Fields = 0; 1190 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1191 E = RD->field_end(); I != E; ++I, ++Fields) { 1192 if (I->isAnonymousStructOrUnion()) { 1193 AnyAnonStructUnionMembers = true; 1194 break; 1195 } 1196 } 1197 // DR1460: 1198 // - if the class is a union-like class, but is not a union, for each of 1199 // its anonymous union members having variant members, exactly one of 1200 // them shall be initialized; 1201 if (AnyAnonStructUnionMembers || 1202 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1203 // Check initialization of non-static data members. Base classes are 1204 // always initialized so do not need to be checked. Dependent bases 1205 // might not have initializers in the member initializer list. 1206 llvm::SmallSet<Decl*, 16> Inits; 1207 for (const auto *I: Constructor->inits()) { 1208 if (FieldDecl *FD = I->getMember()) 1209 Inits.insert(FD); 1210 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1211 Inits.insert(ID->chain_begin(), ID->chain_end()); 1212 } 1213 1214 bool Diagnosed = false; 1215 for (auto *I : RD->fields()) 1216 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1217 if (Diagnosed) 1218 return false; 1219 } 1220 } 1221 } else { 1222 if (ReturnStmts.empty()) { 1223 // C++1y doesn't require constexpr functions to contain a 'return' 1224 // statement. We still do, unless the return type might be void, because 1225 // otherwise if there's no return statement, the function cannot 1226 // be used in a core constant expression. 1227 bool OK = getLangOpts().CPlusPlus14 && 1228 (Dcl->getReturnType()->isVoidType() || 1229 Dcl->getReturnType()->isDependentType()); 1230 Diag(Dcl->getLocation(), 1231 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1232 : diag::err_constexpr_body_no_return); 1233 return OK; 1234 } 1235 if (ReturnStmts.size() > 1) { 1236 Diag(ReturnStmts.back(), 1237 getLangOpts().CPlusPlus14 1238 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1239 : diag::ext_constexpr_body_multiple_return); 1240 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1241 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1242 } 1243 } 1244 1245 // C++11 [dcl.constexpr]p5: 1246 // if no function argument values exist such that the function invocation 1247 // substitution would produce a constant expression, the program is 1248 // ill-formed; no diagnostic required. 1249 // C++11 [dcl.constexpr]p3: 1250 // - every constructor call and implicit conversion used in initializing the 1251 // return value shall be one of those allowed in a constant expression. 1252 // C++11 [dcl.constexpr]p4: 1253 // - every constructor involved in initializing non-static data members and 1254 // base class sub-objects shall be a constexpr constructor. 1255 SmallVector<PartialDiagnosticAt, 8> Diags; 1256 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1257 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1258 << isa<CXXConstructorDecl>(Dcl); 1259 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1260 Diag(Diags[I].first, Diags[I].second); 1261 // Don't return false here: we allow this for compatibility in 1262 // system headers. 1263 } 1264 1265 return true; 1266 } 1267 1268 /// isCurrentClassName - Determine whether the identifier II is the 1269 /// name of the class type currently being defined. In the case of 1270 /// nested classes, this will only return true if II is the name of 1271 /// the innermost class. 1272 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1273 const CXXScopeSpec *SS) { 1274 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1275 1276 CXXRecordDecl *CurDecl; 1277 if (SS && SS->isSet() && !SS->isInvalid()) { 1278 DeclContext *DC = computeDeclContext(*SS, true); 1279 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1280 } else 1281 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1282 1283 if (CurDecl && CurDecl->getIdentifier()) 1284 return &II == CurDecl->getIdentifier(); 1285 return false; 1286 } 1287 1288 /// \brief Determine whether the identifier II is a typo for the name of 1289 /// the class type currently being defined. If so, update it to the identifier 1290 /// that should have been used. 1291 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1292 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1293 1294 if (!getLangOpts().SpellChecking) 1295 return false; 1296 1297 CXXRecordDecl *CurDecl; 1298 if (SS && SS->isSet() && !SS->isInvalid()) { 1299 DeclContext *DC = computeDeclContext(*SS, true); 1300 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1301 } else 1302 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1303 1304 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1305 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1306 < II->getLength()) { 1307 II = CurDecl->getIdentifier(); 1308 return true; 1309 } 1310 1311 return false; 1312 } 1313 1314 /// \brief Determine whether the given class is a base class of the given 1315 /// class, including looking at dependent bases. 1316 static bool findCircularInheritance(const CXXRecordDecl *Class, 1317 const CXXRecordDecl *Current) { 1318 SmallVector<const CXXRecordDecl*, 8> Queue; 1319 1320 Class = Class->getCanonicalDecl(); 1321 while (true) { 1322 for (const auto &I : Current->bases()) { 1323 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 1324 if (!Base) 1325 continue; 1326 1327 Base = Base->getDefinition(); 1328 if (!Base) 1329 continue; 1330 1331 if (Base->getCanonicalDecl() == Class) 1332 return true; 1333 1334 Queue.push_back(Base); 1335 } 1336 1337 if (Queue.empty()) 1338 return false; 1339 1340 Current = Queue.pop_back_val(); 1341 } 1342 1343 return false; 1344 } 1345 1346 /// \brief Check the validity of a C++ base class specifier. 1347 /// 1348 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1349 /// and returns NULL otherwise. 1350 CXXBaseSpecifier * 1351 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1352 SourceRange SpecifierRange, 1353 bool Virtual, AccessSpecifier Access, 1354 TypeSourceInfo *TInfo, 1355 SourceLocation EllipsisLoc) { 1356 QualType BaseType = TInfo->getType(); 1357 1358 // C++ [class.union]p1: 1359 // A union shall not have base classes. 1360 if (Class->isUnion()) { 1361 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1362 << SpecifierRange; 1363 return nullptr; 1364 } 1365 1366 if (EllipsisLoc.isValid() && 1367 !TInfo->getType()->containsUnexpandedParameterPack()) { 1368 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1369 << TInfo->getTypeLoc().getSourceRange(); 1370 EllipsisLoc = SourceLocation(); 1371 } 1372 1373 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1374 1375 if (BaseType->isDependentType()) { 1376 // Make sure that we don't have circular inheritance among our dependent 1377 // bases. For non-dependent bases, the check for completeness below handles 1378 // this. 1379 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1380 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1381 ((BaseDecl = BaseDecl->getDefinition()) && 1382 findCircularInheritance(Class, BaseDecl))) { 1383 Diag(BaseLoc, diag::err_circular_inheritance) 1384 << BaseType << Context.getTypeDeclType(Class); 1385 1386 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1387 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1388 << BaseType; 1389 1390 return nullptr; 1391 } 1392 } 1393 1394 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1395 Class->getTagKind() == TTK_Class, 1396 Access, TInfo, EllipsisLoc); 1397 } 1398 1399 // Base specifiers must be record types. 1400 if (!BaseType->isRecordType()) { 1401 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1402 return nullptr; 1403 } 1404 1405 // C++ [class.union]p1: 1406 // A union shall not be used as a base class. 1407 if (BaseType->isUnionType()) { 1408 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1409 return nullptr; 1410 } 1411 1412 // For the MS ABI, propagate DLL attributes to base class templates. 1413 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1414 if (Attr *ClassAttr = getDLLAttr(Class)) { 1415 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 1416 BaseType->getAsCXXRecordDecl())) { 1417 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 1418 BaseLoc); 1419 } 1420 } 1421 } 1422 1423 // C++ [class.derived]p2: 1424 // The class-name in a base-specifier shall not be an incompletely 1425 // defined class. 1426 if (RequireCompleteType(BaseLoc, BaseType, 1427 diag::err_incomplete_base_class, SpecifierRange)) { 1428 Class->setInvalidDecl(); 1429 return nullptr; 1430 } 1431 1432 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1433 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1434 assert(BaseDecl && "Record type has no declaration"); 1435 BaseDecl = BaseDecl->getDefinition(); 1436 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1437 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1438 assert(CXXBaseDecl && "Base type is not a C++ type"); 1439 1440 // A class which contains a flexible array member is not suitable for use as a 1441 // base class: 1442 // - If the layout determines that a base comes before another base, 1443 // the flexible array member would index into the subsequent base. 1444 // - If the layout determines that base comes before the derived class, 1445 // the flexible array member would index into the derived class. 1446 if (CXXBaseDecl->hasFlexibleArrayMember()) { 1447 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 1448 << CXXBaseDecl->getDeclName(); 1449 return nullptr; 1450 } 1451 1452 // C++ [class]p3: 1453 // If a class is marked final and it appears as a base-type-specifier in 1454 // base-clause, the program is ill-formed. 1455 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1456 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1457 << CXXBaseDecl->getDeclName() 1458 << FA->isSpelledAsSealed(); 1459 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 1460 << CXXBaseDecl->getDeclName() << FA->getRange(); 1461 return nullptr; 1462 } 1463 1464 if (BaseDecl->isInvalidDecl()) 1465 Class->setInvalidDecl(); 1466 1467 // Create the base specifier. 1468 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1469 Class->getTagKind() == TTK_Class, 1470 Access, TInfo, EllipsisLoc); 1471 } 1472 1473 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1474 /// one entry in the base class list of a class specifier, for 1475 /// example: 1476 /// class foo : public bar, virtual private baz { 1477 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1478 BaseResult 1479 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1480 ParsedAttributes &Attributes, 1481 bool Virtual, AccessSpecifier Access, 1482 ParsedType basetype, SourceLocation BaseLoc, 1483 SourceLocation EllipsisLoc) { 1484 if (!classdecl) 1485 return true; 1486 1487 AdjustDeclIfTemplate(classdecl); 1488 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1489 if (!Class) 1490 return true; 1491 1492 // We haven't yet attached the base specifiers. 1493 Class->setIsParsingBaseSpecifiers(); 1494 1495 // We do not support any C++11 attributes on base-specifiers yet. 1496 // Diagnose any attributes we see. 1497 if (!Attributes.empty()) { 1498 for (AttributeList *Attr = Attributes.getList(); Attr; 1499 Attr = Attr->getNext()) { 1500 if (Attr->isInvalid() || 1501 Attr->getKind() == AttributeList::IgnoredAttribute) 1502 continue; 1503 Diag(Attr->getLoc(), 1504 Attr->getKind() == AttributeList::UnknownAttribute 1505 ? diag::warn_unknown_attribute_ignored 1506 : diag::err_base_specifier_attribute) 1507 << Attr->getName(); 1508 } 1509 } 1510 1511 TypeSourceInfo *TInfo = nullptr; 1512 GetTypeFromParser(basetype, &TInfo); 1513 1514 if (EllipsisLoc.isInvalid() && 1515 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1516 UPPC_BaseType)) 1517 return true; 1518 1519 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1520 Virtual, Access, TInfo, 1521 EllipsisLoc)) 1522 return BaseSpec; 1523 else 1524 Class->setInvalidDecl(); 1525 1526 return true; 1527 } 1528 1529 /// Use small set to collect indirect bases. As this is only used 1530 /// locally, there's no need to abstract the small size parameter. 1531 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 1532 1533 /// \brief Recursively add the bases of Type. Don't add Type itself. 1534 static void 1535 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 1536 const QualType &Type) 1537 { 1538 // Even though the incoming type is a base, it might not be 1539 // a class -- it could be a template parm, for instance. 1540 if (auto Rec = Type->getAs<RecordType>()) { 1541 auto Decl = Rec->getAsCXXRecordDecl(); 1542 1543 // Iterate over its bases. 1544 for (const auto &BaseSpec : Decl->bases()) { 1545 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 1546 .getUnqualifiedType(); 1547 if (Set.insert(Base).second) 1548 // If we've not already seen it, recurse. 1549 NoteIndirectBases(Context, Set, Base); 1550 } 1551 } 1552 } 1553 1554 /// \brief Performs the actual work of attaching the given base class 1555 /// specifiers to a C++ class. 1556 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1557 unsigned NumBases) { 1558 if (NumBases == 0) 1559 return false; 1560 1561 // Used to keep track of which base types we have already seen, so 1562 // that we can properly diagnose redundant direct base types. Note 1563 // that the key is always the unqualified canonical type of the base 1564 // class. 1565 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1566 1567 // Used to track indirect bases so we can see if a direct base is 1568 // ambiguous. 1569 IndirectBaseSet IndirectBaseTypes; 1570 1571 // Copy non-redundant base specifiers into permanent storage. 1572 unsigned NumGoodBases = 0; 1573 bool Invalid = false; 1574 for (unsigned idx = 0; idx < NumBases; ++idx) { 1575 QualType NewBaseType 1576 = Context.getCanonicalType(Bases[idx]->getType()); 1577 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1578 1579 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1580 if (KnownBase) { 1581 // C++ [class.mi]p3: 1582 // A class shall not be specified as a direct base class of a 1583 // derived class more than once. 1584 Diag(Bases[idx]->getLocStart(), 1585 diag::err_duplicate_base_class) 1586 << KnownBase->getType() 1587 << Bases[idx]->getSourceRange(); 1588 1589 // Delete the duplicate base class specifier; we're going to 1590 // overwrite its pointer later. 1591 Context.Deallocate(Bases[idx]); 1592 1593 Invalid = true; 1594 } else { 1595 // Okay, add this new base class. 1596 KnownBase = Bases[idx]; 1597 Bases[NumGoodBases++] = Bases[idx]; 1598 1599 // Note this base's direct & indirect bases, if there could be ambiguity. 1600 if (NumBases > 1) 1601 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 1602 1603 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1604 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1605 if (Class->isInterface() && 1606 (!RD->isInterface() || 1607 KnownBase->getAccessSpecifier() != AS_public)) { 1608 // The Microsoft extension __interface does not permit bases that 1609 // are not themselves public interfaces. 1610 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1611 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1612 << RD->getSourceRange(); 1613 Invalid = true; 1614 } 1615 if (RD->hasAttr<WeakAttr>()) 1616 Class->addAttr(WeakAttr::CreateImplicit(Context)); 1617 } 1618 } 1619 } 1620 1621 // Attach the remaining base class specifiers to the derived class. 1622 Class->setBases(Bases, NumGoodBases); 1623 1624 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 1625 // Check whether this direct base is inaccessible due to ambiguity. 1626 QualType BaseType = Bases[idx]->getType(); 1627 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 1628 .getUnqualifiedType(); 1629 1630 if (IndirectBaseTypes.count(CanonicalBase)) { 1631 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1632 /*DetectVirtual=*/true); 1633 bool found 1634 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 1635 assert(found); 1636 (void)found; 1637 1638 if (Paths.isAmbiguous(CanonicalBase)) 1639 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class) 1640 << BaseType << getAmbiguousPathsDisplayString(Paths) 1641 << Bases[idx]->getSourceRange(); 1642 else 1643 assert(Bases[idx]->isVirtual()); 1644 } 1645 1646 // Delete the base class specifier, since its data has been copied 1647 // into the CXXRecordDecl. 1648 Context.Deallocate(Bases[idx]); 1649 } 1650 1651 return Invalid; 1652 } 1653 1654 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1655 /// class, after checking whether there are any duplicate base 1656 /// classes. 1657 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1658 unsigned NumBases) { 1659 if (!ClassDecl || !Bases || !NumBases) 1660 return; 1661 1662 AdjustDeclIfTemplate(ClassDecl); 1663 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1664 } 1665 1666 /// \brief Determine whether the type \p Derived is a C++ class that is 1667 /// derived from the type \p Base. 1668 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1669 if (!getLangOpts().CPlusPlus) 1670 return false; 1671 1672 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1673 if (!DerivedRD) 1674 return false; 1675 1676 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1677 if (!BaseRD) 1678 return false; 1679 1680 // If either the base or the derived type is invalid, don't try to 1681 // check whether one is derived from the other. 1682 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1683 return false; 1684 1685 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1686 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1687 } 1688 1689 /// \brief Determine whether the type \p Derived is a C++ class that is 1690 /// derived from the type \p Base. 1691 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1692 if (!getLangOpts().CPlusPlus) 1693 return false; 1694 1695 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1696 if (!DerivedRD) 1697 return false; 1698 1699 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1700 if (!BaseRD) 1701 return false; 1702 1703 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1704 } 1705 1706 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1707 CXXCastPath &BasePathArray) { 1708 assert(BasePathArray.empty() && "Base path array must be empty!"); 1709 assert(Paths.isRecordingPaths() && "Must record paths!"); 1710 1711 const CXXBasePath &Path = Paths.front(); 1712 1713 // We first go backward and check if we have a virtual base. 1714 // FIXME: It would be better if CXXBasePath had the base specifier for 1715 // the nearest virtual base. 1716 unsigned Start = 0; 1717 for (unsigned I = Path.size(); I != 0; --I) { 1718 if (Path[I - 1].Base->isVirtual()) { 1719 Start = I - 1; 1720 break; 1721 } 1722 } 1723 1724 // Now add all bases. 1725 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1726 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1727 } 1728 1729 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1730 /// conversion (where Derived and Base are class types) is 1731 /// well-formed, meaning that the conversion is unambiguous (and 1732 /// that all of the base classes are accessible). Returns true 1733 /// and emits a diagnostic if the code is ill-formed, returns false 1734 /// otherwise. Loc is the location where this routine should point to 1735 /// if there is an error, and Range is the source range to highlight 1736 /// if there is an error. 1737 bool 1738 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1739 unsigned InaccessibleBaseID, 1740 unsigned AmbigiousBaseConvID, 1741 SourceLocation Loc, SourceRange Range, 1742 DeclarationName Name, 1743 CXXCastPath *BasePath) { 1744 // First, determine whether the path from Derived to Base is 1745 // ambiguous. This is slightly more expensive than checking whether 1746 // the Derived to Base conversion exists, because here we need to 1747 // explore multiple paths to determine if there is an ambiguity. 1748 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1749 /*DetectVirtual=*/false); 1750 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1751 assert(DerivationOkay && 1752 "Can only be used with a derived-to-base conversion"); 1753 (void)DerivationOkay; 1754 1755 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1756 if (InaccessibleBaseID) { 1757 // Check that the base class can be accessed. 1758 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1759 InaccessibleBaseID)) { 1760 case AR_inaccessible: 1761 return true; 1762 case AR_accessible: 1763 case AR_dependent: 1764 case AR_delayed: 1765 break; 1766 } 1767 } 1768 1769 // Build a base path if necessary. 1770 if (BasePath) 1771 BuildBasePathArray(Paths, *BasePath); 1772 return false; 1773 } 1774 1775 if (AmbigiousBaseConvID) { 1776 // We know that the derived-to-base conversion is ambiguous, and 1777 // we're going to produce a diagnostic. Perform the derived-to-base 1778 // search just one more time to compute all of the possible paths so 1779 // that we can print them out. This is more expensive than any of 1780 // the previous derived-to-base checks we've done, but at this point 1781 // performance isn't as much of an issue. 1782 Paths.clear(); 1783 Paths.setRecordingPaths(true); 1784 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1785 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1786 (void)StillOkay; 1787 1788 // Build up a textual representation of the ambiguous paths, e.g., 1789 // D -> B -> A, that will be used to illustrate the ambiguous 1790 // conversions in the diagnostic. We only print one of the paths 1791 // to each base class subobject. 1792 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1793 1794 Diag(Loc, AmbigiousBaseConvID) 1795 << Derived << Base << PathDisplayStr << Range << Name; 1796 } 1797 return true; 1798 } 1799 1800 bool 1801 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1802 SourceLocation Loc, SourceRange Range, 1803 CXXCastPath *BasePath, 1804 bool IgnoreAccess) { 1805 return CheckDerivedToBaseConversion(Derived, Base, 1806 IgnoreAccess ? 0 1807 : diag::err_upcast_to_inaccessible_base, 1808 diag::err_ambiguous_derived_to_base_conv, 1809 Loc, Range, DeclarationName(), 1810 BasePath); 1811 } 1812 1813 1814 /// @brief Builds a string representing ambiguous paths from a 1815 /// specific derived class to different subobjects of the same base 1816 /// class. 1817 /// 1818 /// This function builds a string that can be used in error messages 1819 /// to show the different paths that one can take through the 1820 /// inheritance hierarchy to go from the derived class to different 1821 /// subobjects of a base class. The result looks something like this: 1822 /// @code 1823 /// struct D -> struct B -> struct A 1824 /// struct D -> struct C -> struct A 1825 /// @endcode 1826 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1827 std::string PathDisplayStr; 1828 std::set<unsigned> DisplayedPaths; 1829 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1830 Path != Paths.end(); ++Path) { 1831 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1832 // We haven't displayed a path to this particular base 1833 // class subobject yet. 1834 PathDisplayStr += "\n "; 1835 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1836 for (CXXBasePath::const_iterator Element = Path->begin(); 1837 Element != Path->end(); ++Element) 1838 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1839 } 1840 } 1841 1842 return PathDisplayStr; 1843 } 1844 1845 //===----------------------------------------------------------------------===// 1846 // C++ class member Handling 1847 //===----------------------------------------------------------------------===// 1848 1849 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1850 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1851 SourceLocation ASLoc, 1852 SourceLocation ColonLoc, 1853 AttributeList *Attrs) { 1854 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1855 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1856 ASLoc, ColonLoc); 1857 CurContext->addHiddenDecl(ASDecl); 1858 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1859 } 1860 1861 /// CheckOverrideControl - Check C++11 override control semantics. 1862 void Sema::CheckOverrideControl(NamedDecl *D) { 1863 if (D->isInvalidDecl()) 1864 return; 1865 1866 // We only care about "override" and "final" declarations. 1867 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1868 return; 1869 1870 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1871 1872 // We can't check dependent instance methods. 1873 if (MD && MD->isInstance() && 1874 (MD->getParent()->hasAnyDependentBases() || 1875 MD->getType()->isDependentType())) 1876 return; 1877 1878 if (MD && !MD->isVirtual()) { 1879 // If we have a non-virtual method, check if if hides a virtual method. 1880 // (In that case, it's most likely the method has the wrong type.) 1881 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1882 FindHiddenVirtualMethods(MD, OverloadedMethods); 1883 1884 if (!OverloadedMethods.empty()) { 1885 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1886 Diag(OA->getLocation(), 1887 diag::override_keyword_hides_virtual_member_function) 1888 << "override" << (OverloadedMethods.size() > 1); 1889 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1890 Diag(FA->getLocation(), 1891 diag::override_keyword_hides_virtual_member_function) 1892 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1893 << (OverloadedMethods.size() > 1); 1894 } 1895 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1896 MD->setInvalidDecl(); 1897 return; 1898 } 1899 // Fall through into the general case diagnostic. 1900 // FIXME: We might want to attempt typo correction here. 1901 } 1902 1903 if (!MD || !MD->isVirtual()) { 1904 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1905 Diag(OA->getLocation(), 1906 diag::override_keyword_only_allowed_on_virtual_member_functions) 1907 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1908 D->dropAttr<OverrideAttr>(); 1909 } 1910 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1911 Diag(FA->getLocation(), 1912 diag::override_keyword_only_allowed_on_virtual_member_functions) 1913 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1914 << FixItHint::CreateRemoval(FA->getLocation()); 1915 D->dropAttr<FinalAttr>(); 1916 } 1917 return; 1918 } 1919 1920 // C++11 [class.virtual]p5: 1921 // If a function is marked with the virt-specifier override and 1922 // does not override a member function of a base class, the program is 1923 // ill-formed. 1924 bool HasOverriddenMethods = 1925 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1926 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1927 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1928 << MD->getDeclName(); 1929 } 1930 1931 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 1932 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 1933 return; 1934 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1935 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() || 1936 isa<CXXDestructorDecl>(MD)) 1937 return; 1938 1939 SourceLocation Loc = MD->getLocation(); 1940 SourceLocation SpellingLoc = Loc; 1941 if (getSourceManager().isMacroArgExpansion(Loc)) 1942 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first; 1943 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 1944 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 1945 return; 1946 1947 if (MD->size_overridden_methods() > 0) { 1948 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding) 1949 << MD->getDeclName(); 1950 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 1951 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 1952 } 1953 } 1954 1955 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1956 /// function overrides a virtual member function marked 'final', according to 1957 /// C++11 [class.virtual]p4. 1958 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1959 const CXXMethodDecl *Old) { 1960 FinalAttr *FA = Old->getAttr<FinalAttr>(); 1961 if (!FA) 1962 return false; 1963 1964 Diag(New->getLocation(), diag::err_final_function_overridden) 1965 << New->getDeclName() 1966 << FA->isSpelledAsSealed(); 1967 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1968 return true; 1969 } 1970 1971 static bool InitializationHasSideEffects(const FieldDecl &FD) { 1972 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1973 // FIXME: Destruction of ObjC lifetime types has side-effects. 1974 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1975 return !RD->isCompleteDefinition() || 1976 !RD->hasTrivialDefaultConstructor() || 1977 !RD->hasTrivialDestructor(); 1978 return false; 1979 } 1980 1981 static AttributeList *getMSPropertyAttr(AttributeList *list) { 1982 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 1983 if (it->isDeclspecPropertyAttribute()) 1984 return it; 1985 return nullptr; 1986 } 1987 1988 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1989 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1990 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 1991 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1992 /// present (but parsing it has been deferred). 1993 NamedDecl * 1994 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1995 MultiTemplateParamsArg TemplateParameterLists, 1996 Expr *BW, const VirtSpecifiers &VS, 1997 InClassInitStyle InitStyle) { 1998 const DeclSpec &DS = D.getDeclSpec(); 1999 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2000 DeclarationName Name = NameInfo.getName(); 2001 SourceLocation Loc = NameInfo.getLoc(); 2002 2003 // For anonymous bitfields, the location should point to the type. 2004 if (Loc.isInvalid()) 2005 Loc = D.getLocStart(); 2006 2007 Expr *BitWidth = static_cast<Expr*>(BW); 2008 2009 assert(isa<CXXRecordDecl>(CurContext)); 2010 assert(!DS.isFriendSpecified()); 2011 2012 bool isFunc = D.isDeclarationOfFunction(); 2013 2014 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2015 // The Microsoft extension __interface only permits public member functions 2016 // and prohibits constructors, destructors, operators, non-public member 2017 // functions, static methods and data members. 2018 unsigned InvalidDecl; 2019 bool ShowDeclName = true; 2020 if (!isFunc) 2021 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 2022 else if (AS != AS_public) 2023 InvalidDecl = 2; 2024 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2025 InvalidDecl = 3; 2026 else switch (Name.getNameKind()) { 2027 case DeclarationName::CXXConstructorName: 2028 InvalidDecl = 4; 2029 ShowDeclName = false; 2030 break; 2031 2032 case DeclarationName::CXXDestructorName: 2033 InvalidDecl = 5; 2034 ShowDeclName = false; 2035 break; 2036 2037 case DeclarationName::CXXOperatorName: 2038 case DeclarationName::CXXConversionFunctionName: 2039 InvalidDecl = 6; 2040 break; 2041 2042 default: 2043 InvalidDecl = 0; 2044 break; 2045 } 2046 2047 if (InvalidDecl) { 2048 if (ShowDeclName) 2049 Diag(Loc, diag::err_invalid_member_in_interface) 2050 << (InvalidDecl-1) << Name; 2051 else 2052 Diag(Loc, diag::err_invalid_member_in_interface) 2053 << (InvalidDecl-1) << ""; 2054 return nullptr; 2055 } 2056 } 2057 2058 // C++ 9.2p6: A member shall not be declared to have automatic storage 2059 // duration (auto, register) or with the extern storage-class-specifier. 2060 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2061 // data members and cannot be applied to names declared const or static, 2062 // and cannot be applied to reference members. 2063 switch (DS.getStorageClassSpec()) { 2064 case DeclSpec::SCS_unspecified: 2065 case DeclSpec::SCS_typedef: 2066 case DeclSpec::SCS_static: 2067 break; 2068 case DeclSpec::SCS_mutable: 2069 if (isFunc) { 2070 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2071 2072 // FIXME: It would be nicer if the keyword was ignored only for this 2073 // declarator. Otherwise we could get follow-up errors. 2074 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2075 } 2076 break; 2077 default: 2078 Diag(DS.getStorageClassSpecLoc(), 2079 diag::err_storageclass_invalid_for_member); 2080 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2081 break; 2082 } 2083 2084 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2085 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2086 !isFunc); 2087 2088 if (DS.isConstexprSpecified() && isInstField) { 2089 SemaDiagnosticBuilder B = 2090 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2091 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2092 if (InitStyle == ICIS_NoInit) { 2093 B << 0 << 0; 2094 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2095 B << FixItHint::CreateRemoval(ConstexprLoc); 2096 else { 2097 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2098 D.getMutableDeclSpec().ClearConstexprSpec(); 2099 const char *PrevSpec; 2100 unsigned DiagID; 2101 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2102 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2103 (void)Failed; 2104 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2105 } 2106 } else { 2107 B << 1; 2108 const char *PrevSpec; 2109 unsigned DiagID; 2110 if (D.getMutableDeclSpec().SetStorageClassSpec( 2111 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2112 Context.getPrintingPolicy())) { 2113 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2114 "This is the only DeclSpec that should fail to be applied"); 2115 B << 1; 2116 } else { 2117 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2118 isInstField = false; 2119 } 2120 } 2121 } 2122 2123 NamedDecl *Member; 2124 if (isInstField) { 2125 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2126 2127 // Data members must have identifiers for names. 2128 if (!Name.isIdentifier()) { 2129 Diag(Loc, diag::err_bad_variable_name) 2130 << Name; 2131 return nullptr; 2132 } 2133 2134 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2135 2136 // Member field could not be with "template" keyword. 2137 // So TemplateParameterLists should be empty in this case. 2138 if (TemplateParameterLists.size()) { 2139 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2140 if (TemplateParams->size()) { 2141 // There is no such thing as a member field template. 2142 Diag(D.getIdentifierLoc(), diag::err_template_member) 2143 << II 2144 << SourceRange(TemplateParams->getTemplateLoc(), 2145 TemplateParams->getRAngleLoc()); 2146 } else { 2147 // There is an extraneous 'template<>' for this member. 2148 Diag(TemplateParams->getTemplateLoc(), 2149 diag::err_template_member_noparams) 2150 << II 2151 << SourceRange(TemplateParams->getTemplateLoc(), 2152 TemplateParams->getRAngleLoc()); 2153 } 2154 return nullptr; 2155 } 2156 2157 if (SS.isSet() && !SS.isInvalid()) { 2158 // The user provided a superfluous scope specifier inside a class 2159 // definition: 2160 // 2161 // class X { 2162 // int X::member; 2163 // }; 2164 if (DeclContext *DC = computeDeclContext(SS, false)) 2165 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2166 else 2167 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2168 << Name << SS.getRange(); 2169 2170 SS.clear(); 2171 } 2172 2173 AttributeList *MSPropertyAttr = 2174 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2175 if (MSPropertyAttr) { 2176 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2177 BitWidth, InitStyle, AS, MSPropertyAttr); 2178 if (!Member) 2179 return nullptr; 2180 isInstField = false; 2181 } else { 2182 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2183 BitWidth, InitStyle, AS); 2184 assert(Member && "HandleField never returns null"); 2185 } 2186 } else { 2187 Member = HandleDeclarator(S, D, TemplateParameterLists); 2188 if (!Member) 2189 return nullptr; 2190 2191 // Non-instance-fields can't have a bitfield. 2192 if (BitWidth) { 2193 if (Member->isInvalidDecl()) { 2194 // don't emit another diagnostic. 2195 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 2196 // C++ 9.6p3: A bit-field shall not be a static member. 2197 // "static member 'A' cannot be a bit-field" 2198 Diag(Loc, diag::err_static_not_bitfield) 2199 << Name << BitWidth->getSourceRange(); 2200 } else if (isa<TypedefDecl>(Member)) { 2201 // "typedef member 'x' cannot be a bit-field" 2202 Diag(Loc, diag::err_typedef_not_bitfield) 2203 << Name << BitWidth->getSourceRange(); 2204 } else { 2205 // A function typedef ("typedef int f(); f a;"). 2206 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2207 Diag(Loc, diag::err_not_integral_type_bitfield) 2208 << Name << cast<ValueDecl>(Member)->getType() 2209 << BitWidth->getSourceRange(); 2210 } 2211 2212 BitWidth = nullptr; 2213 Member->setInvalidDecl(); 2214 } 2215 2216 Member->setAccess(AS); 2217 2218 // If we have declared a member function template or static data member 2219 // template, set the access of the templated declaration as well. 2220 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2221 FunTmpl->getTemplatedDecl()->setAccess(AS); 2222 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2223 VarTmpl->getTemplatedDecl()->setAccess(AS); 2224 } 2225 2226 if (VS.isOverrideSpecified()) 2227 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 2228 if (VS.isFinalSpecified()) 2229 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2230 VS.isFinalSpelledSealed())); 2231 2232 if (VS.getLastLocation().isValid()) { 2233 // Update the end location of a method that has a virt-specifiers. 2234 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2235 MD->setRangeEnd(VS.getLastLocation()); 2236 } 2237 2238 CheckOverrideControl(Member); 2239 2240 assert((Name || isInstField) && "No identifier for non-field ?"); 2241 2242 if (isInstField) { 2243 FieldDecl *FD = cast<FieldDecl>(Member); 2244 FieldCollector->Add(FD); 2245 2246 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 2247 // Remember all explicit private FieldDecls that have a name, no side 2248 // effects and are not part of a dependent type declaration. 2249 if (!FD->isImplicit() && FD->getDeclName() && 2250 FD->getAccess() == AS_private && 2251 !FD->hasAttr<UnusedAttr>() && 2252 !FD->getParent()->isDependentContext() && 2253 !InitializationHasSideEffects(*FD)) 2254 UnusedPrivateFields.insert(FD); 2255 } 2256 } 2257 2258 return Member; 2259 } 2260 2261 namespace { 2262 class UninitializedFieldVisitor 2263 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2264 Sema &S; 2265 // List of Decls to generate a warning on. Also remove Decls that become 2266 // initialized. 2267 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 2268 // List of base classes of the record. Classes are removed after their 2269 // initializers. 2270 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 2271 // Vector of decls to be removed from the Decl set prior to visiting the 2272 // nodes. These Decls may have been initialized in the prior initializer. 2273 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 2274 // If non-null, add a note to the warning pointing back to the constructor. 2275 const CXXConstructorDecl *Constructor; 2276 // Variables to hold state when processing an initializer list. When 2277 // InitList is true, special case initialization of FieldDecls matching 2278 // InitListFieldDecl. 2279 bool InitList; 2280 FieldDecl *InitListFieldDecl; 2281 llvm::SmallVector<unsigned, 4> InitFieldIndex; 2282 2283 public: 2284 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2285 UninitializedFieldVisitor(Sema &S, 2286 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 2287 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 2288 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 2289 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 2290 2291 // Returns true if the use of ME is not an uninitialized use. 2292 bool IsInitListMemberExprInitialized(MemberExpr *ME, 2293 bool CheckReferenceOnly) { 2294 llvm::SmallVector<FieldDecl*, 4> Fields; 2295 bool ReferenceField = false; 2296 while (ME) { 2297 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 2298 if (!FD) 2299 return false; 2300 Fields.push_back(FD); 2301 if (FD->getType()->isReferenceType()) 2302 ReferenceField = true; 2303 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 2304 } 2305 2306 // Binding a reference to an unintialized field is not an 2307 // uninitialized use. 2308 if (CheckReferenceOnly && !ReferenceField) 2309 return true; 2310 2311 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 2312 // Discard the first field since it is the field decl that is being 2313 // initialized. 2314 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 2315 UsedFieldIndex.push_back((*I)->getFieldIndex()); 2316 } 2317 2318 for (auto UsedIter = UsedFieldIndex.begin(), 2319 UsedEnd = UsedFieldIndex.end(), 2320 OrigIter = InitFieldIndex.begin(), 2321 OrigEnd = InitFieldIndex.end(); 2322 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 2323 if (*UsedIter < *OrigIter) 2324 return true; 2325 if (*UsedIter > *OrigIter) 2326 break; 2327 } 2328 2329 return false; 2330 } 2331 2332 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 2333 bool AddressOf) { 2334 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2335 return; 2336 2337 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2338 // or union. 2339 MemberExpr *FieldME = ME; 2340 2341 bool AllPODFields = FieldME->getType().isPODType(S.Context); 2342 2343 Expr *Base = ME; 2344 while (MemberExpr *SubME = 2345 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 2346 2347 if (isa<VarDecl>(SubME->getMemberDecl())) 2348 return; 2349 2350 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 2351 if (!FD->isAnonymousStructOrUnion()) 2352 FieldME = SubME; 2353 2354 if (!FieldME->getType().isPODType(S.Context)) 2355 AllPODFields = false; 2356 2357 Base = SubME->getBase(); 2358 } 2359 2360 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 2361 return; 2362 2363 if (AddressOf && AllPODFields) 2364 return; 2365 2366 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2367 2368 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 2369 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 2370 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 2371 } 2372 2373 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 2374 QualType T = BaseCast->getType(); 2375 if (T->isPointerType() && 2376 BaseClasses.count(T->getPointeeType())) { 2377 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 2378 << T->getPointeeType() << FoundVD; 2379 } 2380 } 2381 } 2382 2383 if (!Decls.count(FoundVD)) 2384 return; 2385 2386 const bool IsReference = FoundVD->getType()->isReferenceType(); 2387 2388 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 2389 // Special checking for initializer lists. 2390 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 2391 return; 2392 } 2393 } else { 2394 // Prevent double warnings on use of unbounded references. 2395 if (CheckReferenceOnly && !IsReference) 2396 return; 2397 } 2398 2399 unsigned diag = IsReference 2400 ? diag::warn_reference_field_is_uninit 2401 : diag::warn_field_is_uninit; 2402 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 2403 if (Constructor) 2404 S.Diag(Constructor->getLocation(), 2405 diag::note_uninit_in_this_constructor) 2406 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 2407 2408 } 2409 2410 void HandleValue(Expr *E, bool AddressOf) { 2411 E = E->IgnoreParens(); 2412 2413 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2414 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 2415 AddressOf /*AddressOf*/); 2416 return; 2417 } 2418 2419 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2420 Visit(CO->getCond()); 2421 HandleValue(CO->getTrueExpr(), AddressOf); 2422 HandleValue(CO->getFalseExpr(), AddressOf); 2423 return; 2424 } 2425 2426 if (BinaryConditionalOperator *BCO = 2427 dyn_cast<BinaryConditionalOperator>(E)) { 2428 Visit(BCO->getCond()); 2429 HandleValue(BCO->getFalseExpr(), AddressOf); 2430 return; 2431 } 2432 2433 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 2434 HandleValue(OVE->getSourceExpr(), AddressOf); 2435 return; 2436 } 2437 2438 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2439 switch (BO->getOpcode()) { 2440 default: 2441 break; 2442 case(BO_PtrMemD): 2443 case(BO_PtrMemI): 2444 HandleValue(BO->getLHS(), AddressOf); 2445 Visit(BO->getRHS()); 2446 return; 2447 case(BO_Comma): 2448 Visit(BO->getLHS()); 2449 HandleValue(BO->getRHS(), AddressOf); 2450 return; 2451 } 2452 } 2453 2454 Visit(E); 2455 } 2456 2457 void CheckInitListExpr(InitListExpr *ILE) { 2458 InitFieldIndex.push_back(0); 2459 for (auto Child : ILE->children()) { 2460 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 2461 CheckInitListExpr(SubList); 2462 } else { 2463 Visit(Child); 2464 } 2465 ++InitFieldIndex.back(); 2466 } 2467 InitFieldIndex.pop_back(); 2468 } 2469 2470 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 2471 FieldDecl *Field, const Type *BaseClass) { 2472 // Remove Decls that may have been initialized in the previous 2473 // initializer. 2474 for (ValueDecl* VD : DeclsToRemove) 2475 Decls.erase(VD); 2476 DeclsToRemove.clear(); 2477 2478 Constructor = FieldConstructor; 2479 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 2480 2481 if (ILE && Field) { 2482 InitList = true; 2483 InitListFieldDecl = Field; 2484 InitFieldIndex.clear(); 2485 CheckInitListExpr(ILE); 2486 } else { 2487 InitList = false; 2488 Visit(E); 2489 } 2490 2491 if (Field) 2492 Decls.erase(Field); 2493 if (BaseClass) 2494 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 2495 } 2496 2497 void VisitMemberExpr(MemberExpr *ME) { 2498 // All uses of unbounded reference fields will warn. 2499 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 2500 } 2501 2502 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2503 if (E->getCastKind() == CK_LValueToRValue) { 2504 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2505 return; 2506 } 2507 2508 Inherited::VisitImplicitCastExpr(E); 2509 } 2510 2511 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2512 if (E->getConstructor()->isCopyConstructor()) { 2513 Expr *ArgExpr = E->getArg(0); 2514 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 2515 if (ILE->getNumInits() == 1) 2516 ArgExpr = ILE->getInit(0); 2517 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 2518 if (ICE->getCastKind() == CK_NoOp) 2519 ArgExpr = ICE->getSubExpr(); 2520 HandleValue(ArgExpr, false /*AddressOf*/); 2521 return; 2522 } 2523 Inherited::VisitCXXConstructExpr(E); 2524 } 2525 2526 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2527 Expr *Callee = E->getCallee(); 2528 if (isa<MemberExpr>(Callee)) { 2529 HandleValue(Callee, false /*AddressOf*/); 2530 for (auto Arg : E->arguments()) 2531 Visit(Arg); 2532 return; 2533 } 2534 2535 Inherited::VisitCXXMemberCallExpr(E); 2536 } 2537 2538 void VisitCallExpr(CallExpr *E) { 2539 // Treat std::move as a use. 2540 if (E->getNumArgs() == 1) { 2541 if (FunctionDecl *FD = E->getDirectCallee()) { 2542 if (FD->isInStdNamespace() && FD->getIdentifier() && 2543 FD->getIdentifier()->isStr("move")) { 2544 HandleValue(E->getArg(0), false /*AddressOf*/); 2545 return; 2546 } 2547 } 2548 } 2549 2550 Inherited::VisitCallExpr(E); 2551 } 2552 2553 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 2554 Expr *Callee = E->getCallee(); 2555 2556 if (isa<UnresolvedLookupExpr>(Callee)) 2557 return Inherited::VisitCXXOperatorCallExpr(E); 2558 2559 Visit(Callee); 2560 for (auto Arg : E->arguments()) 2561 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 2562 } 2563 2564 void VisitBinaryOperator(BinaryOperator *E) { 2565 // If a field assignment is detected, remove the field from the 2566 // uninitiailized field set. 2567 if (E->getOpcode() == BO_Assign) 2568 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2569 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2570 if (!FD->getType()->isReferenceType()) 2571 DeclsToRemove.push_back(FD); 2572 2573 if (E->isCompoundAssignmentOp()) { 2574 HandleValue(E->getLHS(), false /*AddressOf*/); 2575 Visit(E->getRHS()); 2576 return; 2577 } 2578 2579 Inherited::VisitBinaryOperator(E); 2580 } 2581 2582 void VisitUnaryOperator(UnaryOperator *E) { 2583 if (E->isIncrementDecrementOp()) { 2584 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2585 return; 2586 } 2587 if (E->getOpcode() == UO_AddrOf) { 2588 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 2589 HandleValue(ME->getBase(), true /*AddressOf*/); 2590 return; 2591 } 2592 } 2593 2594 Inherited::VisitUnaryOperator(E); 2595 } 2596 }; 2597 2598 // Diagnose value-uses of fields to initialize themselves, e.g. 2599 // foo(foo) 2600 // where foo is not also a parameter to the constructor. 2601 // Also diagnose across field uninitialized use such as 2602 // x(y), y(x) 2603 // TODO: implement -Wuninitialized and fold this into that framework. 2604 static void DiagnoseUninitializedFields( 2605 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 2606 2607 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 2608 Constructor->getLocation())) { 2609 return; 2610 } 2611 2612 if (Constructor->isInvalidDecl()) 2613 return; 2614 2615 const CXXRecordDecl *RD = Constructor->getParent(); 2616 2617 if (RD->getDescribedClassTemplate()) 2618 return; 2619 2620 // Holds fields that are uninitialized. 2621 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 2622 2623 // At the beginning, all fields are uninitialized. 2624 for (auto *I : RD->decls()) { 2625 if (auto *FD = dyn_cast<FieldDecl>(I)) { 2626 UninitializedFields.insert(FD); 2627 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 2628 UninitializedFields.insert(IFD->getAnonField()); 2629 } 2630 } 2631 2632 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 2633 for (auto I : RD->bases()) 2634 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 2635 2636 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 2637 return; 2638 2639 UninitializedFieldVisitor UninitializedChecker(SemaRef, 2640 UninitializedFields, 2641 UninitializedBaseClasses); 2642 2643 for (const auto *FieldInit : Constructor->inits()) { 2644 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 2645 break; 2646 2647 Expr *InitExpr = FieldInit->getInit(); 2648 if (!InitExpr) 2649 continue; 2650 2651 if (CXXDefaultInitExpr *Default = 2652 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 2653 InitExpr = Default->getExpr(); 2654 if (!InitExpr) 2655 continue; 2656 // In class initializers will point to the constructor. 2657 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 2658 FieldInit->getAnyMember(), 2659 FieldInit->getBaseClass()); 2660 } else { 2661 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 2662 FieldInit->getAnyMember(), 2663 FieldInit->getBaseClass()); 2664 } 2665 } 2666 } 2667 } // namespace 2668 2669 /// \brief Enter a new C++ default initializer scope. After calling this, the 2670 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 2671 /// parsing or instantiating the initializer failed. 2672 void Sema::ActOnStartCXXInClassMemberInitializer() { 2673 // Create a synthetic function scope to represent the call to the constructor 2674 // that notionally surrounds a use of this initializer. 2675 PushFunctionScope(); 2676 } 2677 2678 /// \brief This is invoked after parsing an in-class initializer for a 2679 /// non-static C++ class member, and after instantiating an in-class initializer 2680 /// in a class template. Such actions are deferred until the class is complete. 2681 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 2682 SourceLocation InitLoc, 2683 Expr *InitExpr) { 2684 // Pop the notional constructor scope we created earlier. 2685 PopFunctionScopeInfo(nullptr, D); 2686 2687 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2688 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 2689 "must set init style when field is created"); 2690 2691 if (!InitExpr) { 2692 D->setInvalidDecl(); 2693 if (FD) 2694 FD->removeInClassInitializer(); 2695 return; 2696 } 2697 2698 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2699 FD->setInvalidDecl(); 2700 FD->removeInClassInitializer(); 2701 return; 2702 } 2703 2704 ExprResult Init = InitExpr; 2705 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2706 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2707 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2708 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2709 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2710 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2711 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2712 if (Init.isInvalid()) { 2713 FD->setInvalidDecl(); 2714 return; 2715 } 2716 } 2717 2718 // C++11 [class.base.init]p7: 2719 // The initialization of each base and member constitutes a 2720 // full-expression. 2721 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 2722 if (Init.isInvalid()) { 2723 FD->setInvalidDecl(); 2724 return; 2725 } 2726 2727 InitExpr = Init.get(); 2728 2729 FD->setInClassInitializer(InitExpr); 2730 } 2731 2732 /// \brief Find the direct and/or virtual base specifiers that 2733 /// correspond to the given base type, for use in base initialization 2734 /// within a constructor. 2735 static bool FindBaseInitializer(Sema &SemaRef, 2736 CXXRecordDecl *ClassDecl, 2737 QualType BaseType, 2738 const CXXBaseSpecifier *&DirectBaseSpec, 2739 const CXXBaseSpecifier *&VirtualBaseSpec) { 2740 // First, check for a direct base class. 2741 DirectBaseSpec = nullptr; 2742 for (const auto &Base : ClassDecl->bases()) { 2743 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 2744 // We found a direct base of this type. That's what we're 2745 // initializing. 2746 DirectBaseSpec = &Base; 2747 break; 2748 } 2749 } 2750 2751 // Check for a virtual base class. 2752 // FIXME: We might be able to short-circuit this if we know in advance that 2753 // there are no virtual bases. 2754 VirtualBaseSpec = nullptr; 2755 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2756 // We haven't found a base yet; search the class hierarchy for a 2757 // virtual base class. 2758 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2759 /*DetectVirtual=*/false); 2760 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2761 BaseType, Paths)) { 2762 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2763 Path != Paths.end(); ++Path) { 2764 if (Path->back().Base->isVirtual()) { 2765 VirtualBaseSpec = Path->back().Base; 2766 break; 2767 } 2768 } 2769 } 2770 } 2771 2772 return DirectBaseSpec || VirtualBaseSpec; 2773 } 2774 2775 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2776 MemInitResult 2777 Sema::ActOnMemInitializer(Decl *ConstructorD, 2778 Scope *S, 2779 CXXScopeSpec &SS, 2780 IdentifierInfo *MemberOrBase, 2781 ParsedType TemplateTypeTy, 2782 const DeclSpec &DS, 2783 SourceLocation IdLoc, 2784 Expr *InitList, 2785 SourceLocation EllipsisLoc) { 2786 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2787 DS, IdLoc, InitList, 2788 EllipsisLoc); 2789 } 2790 2791 /// \brief Handle a C++ member initializer using parentheses syntax. 2792 MemInitResult 2793 Sema::ActOnMemInitializer(Decl *ConstructorD, 2794 Scope *S, 2795 CXXScopeSpec &SS, 2796 IdentifierInfo *MemberOrBase, 2797 ParsedType TemplateTypeTy, 2798 const DeclSpec &DS, 2799 SourceLocation IdLoc, 2800 SourceLocation LParenLoc, 2801 ArrayRef<Expr *> Args, 2802 SourceLocation RParenLoc, 2803 SourceLocation EllipsisLoc) { 2804 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2805 Args, RParenLoc); 2806 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2807 DS, IdLoc, List, EllipsisLoc); 2808 } 2809 2810 namespace { 2811 2812 // Callback to only accept typo corrections that can be a valid C++ member 2813 // intializer: either a non-static field member or a base class. 2814 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2815 public: 2816 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2817 : ClassDecl(ClassDecl) {} 2818 2819 bool ValidateCandidate(const TypoCorrection &candidate) override { 2820 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2821 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2822 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2823 return isa<TypeDecl>(ND); 2824 } 2825 return false; 2826 } 2827 2828 private: 2829 CXXRecordDecl *ClassDecl; 2830 }; 2831 2832 } 2833 2834 /// \brief Handle a C++ member initializer. 2835 MemInitResult 2836 Sema::BuildMemInitializer(Decl *ConstructorD, 2837 Scope *S, 2838 CXXScopeSpec &SS, 2839 IdentifierInfo *MemberOrBase, 2840 ParsedType TemplateTypeTy, 2841 const DeclSpec &DS, 2842 SourceLocation IdLoc, 2843 Expr *Init, 2844 SourceLocation EllipsisLoc) { 2845 ExprResult Res = CorrectDelayedTyposInExpr(Init); 2846 if (!Res.isUsable()) 2847 return true; 2848 Init = Res.get(); 2849 2850 if (!ConstructorD) 2851 return true; 2852 2853 AdjustDeclIfTemplate(ConstructorD); 2854 2855 CXXConstructorDecl *Constructor 2856 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2857 if (!Constructor) { 2858 // The user wrote a constructor initializer on a function that is 2859 // not a C++ constructor. Ignore the error for now, because we may 2860 // have more member initializers coming; we'll diagnose it just 2861 // once in ActOnMemInitializers. 2862 return true; 2863 } 2864 2865 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2866 2867 // C++ [class.base.init]p2: 2868 // Names in a mem-initializer-id are looked up in the scope of the 2869 // constructor's class and, if not found in that scope, are looked 2870 // up in the scope containing the constructor's definition. 2871 // [Note: if the constructor's class contains a member with the 2872 // same name as a direct or virtual base class of the class, a 2873 // mem-initializer-id naming the member or base class and composed 2874 // of a single identifier refers to the class member. A 2875 // mem-initializer-id for the hidden base class may be specified 2876 // using a qualified name. ] 2877 if (!SS.getScopeRep() && !TemplateTypeTy) { 2878 // Look for a member, first. 2879 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 2880 if (!Result.empty()) { 2881 ValueDecl *Member; 2882 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2883 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2884 if (EllipsisLoc.isValid()) 2885 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2886 << MemberOrBase 2887 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2888 2889 return BuildMemberInitializer(Member, Init, IdLoc); 2890 } 2891 } 2892 } 2893 // It didn't name a member, so see if it names a class. 2894 QualType BaseType; 2895 TypeSourceInfo *TInfo = nullptr; 2896 2897 if (TemplateTypeTy) { 2898 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2899 } else if (DS.getTypeSpecType() == TST_decltype) { 2900 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2901 } else { 2902 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2903 LookupParsedName(R, S, &SS); 2904 2905 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2906 if (!TyD) { 2907 if (R.isAmbiguous()) return true; 2908 2909 // We don't want access-control diagnostics here. 2910 R.suppressDiagnostics(); 2911 2912 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2913 bool NotUnknownSpecialization = false; 2914 DeclContext *DC = computeDeclContext(SS, false); 2915 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2916 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2917 2918 if (!NotUnknownSpecialization) { 2919 // When the scope specifier can refer to a member of an unknown 2920 // specialization, we take it as a type name. 2921 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2922 SS.getWithLocInContext(Context), 2923 *MemberOrBase, IdLoc); 2924 if (BaseType.isNull()) 2925 return true; 2926 2927 R.clear(); 2928 R.setLookupName(MemberOrBase); 2929 } 2930 } 2931 2932 // If no results were found, try to correct typos. 2933 TypoCorrection Corr; 2934 if (R.empty() && BaseType.isNull() && 2935 (Corr = CorrectTypo( 2936 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2937 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 2938 CTK_ErrorRecovery, ClassDecl))) { 2939 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2940 // We have found a non-static data member with a similar 2941 // name to what was typed; complain and initialize that 2942 // member. 2943 diagnoseTypo(Corr, 2944 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2945 << MemberOrBase << true); 2946 return BuildMemberInitializer(Member, Init, IdLoc); 2947 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2948 const CXXBaseSpecifier *DirectBaseSpec; 2949 const CXXBaseSpecifier *VirtualBaseSpec; 2950 if (FindBaseInitializer(*this, ClassDecl, 2951 Context.getTypeDeclType(Type), 2952 DirectBaseSpec, VirtualBaseSpec)) { 2953 // We have found a direct or virtual base class with a 2954 // similar name to what was typed; complain and initialize 2955 // that base class. 2956 diagnoseTypo(Corr, 2957 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2958 << MemberOrBase << false, 2959 PDiag() /*Suppress note, we provide our own.*/); 2960 2961 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2962 : VirtualBaseSpec; 2963 Diag(BaseSpec->getLocStart(), 2964 diag::note_base_class_specified_here) 2965 << BaseSpec->getType() 2966 << BaseSpec->getSourceRange(); 2967 2968 TyD = Type; 2969 } 2970 } 2971 } 2972 2973 if (!TyD && BaseType.isNull()) { 2974 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2975 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2976 return true; 2977 } 2978 } 2979 2980 if (BaseType.isNull()) { 2981 BaseType = Context.getTypeDeclType(TyD); 2982 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 2983 if (SS.isSet()) 2984 // FIXME: preserve source range information 2985 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 2986 BaseType); 2987 } 2988 } 2989 2990 if (!TInfo) 2991 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2992 2993 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2994 } 2995 2996 /// Checks a member initializer expression for cases where reference (or 2997 /// pointer) members are bound to by-value parameters (or their addresses). 2998 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2999 Expr *Init, 3000 SourceLocation IdLoc) { 3001 QualType MemberTy = Member->getType(); 3002 3003 // We only handle pointers and references currently. 3004 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 3005 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 3006 return; 3007 3008 const bool IsPointer = MemberTy->isPointerType(); 3009 if (IsPointer) { 3010 if (const UnaryOperator *Op 3011 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 3012 // The only case we're worried about with pointers requires taking the 3013 // address. 3014 if (Op->getOpcode() != UO_AddrOf) 3015 return; 3016 3017 Init = Op->getSubExpr(); 3018 } else { 3019 // We only handle address-of expression initializers for pointers. 3020 return; 3021 } 3022 } 3023 3024 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 3025 // We only warn when referring to a non-reference parameter declaration. 3026 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 3027 if (!Parameter || Parameter->getType()->isReferenceType()) 3028 return; 3029 3030 S.Diag(Init->getExprLoc(), 3031 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 3032 : diag::warn_bind_ref_member_to_parameter) 3033 << Member << Parameter << Init->getSourceRange(); 3034 } else { 3035 // Other initializers are fine. 3036 return; 3037 } 3038 3039 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3040 << (unsigned)IsPointer; 3041 } 3042 3043 MemInitResult 3044 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3045 SourceLocation IdLoc) { 3046 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3047 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3048 assert((DirectMember || IndirectMember) && 3049 "Member must be a FieldDecl or IndirectFieldDecl"); 3050 3051 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3052 return true; 3053 3054 if (Member->isInvalidDecl()) 3055 return true; 3056 3057 MultiExprArg Args; 3058 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3059 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3060 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3061 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3062 } else { 3063 // Template instantiation doesn't reconstruct ParenListExprs for us. 3064 Args = Init; 3065 } 3066 3067 SourceRange InitRange = Init->getSourceRange(); 3068 3069 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3070 // Can't check initialization for a member of dependent type or when 3071 // any of the arguments are type-dependent expressions. 3072 DiscardCleanupsInEvaluationContext(); 3073 } else { 3074 bool InitList = false; 3075 if (isa<InitListExpr>(Init)) { 3076 InitList = true; 3077 Args = Init; 3078 } 3079 3080 // Initialize the member. 3081 InitializedEntity MemberEntity = 3082 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3083 : InitializedEntity::InitializeMember(IndirectMember, 3084 nullptr); 3085 InitializationKind Kind = 3086 InitList ? InitializationKind::CreateDirectList(IdLoc) 3087 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3088 InitRange.getEnd()); 3089 3090 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 3091 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 3092 nullptr); 3093 if (MemberInit.isInvalid()) 3094 return true; 3095 3096 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 3097 3098 // C++11 [class.base.init]p7: 3099 // The initialization of each base and member constitutes a 3100 // full-expression. 3101 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 3102 if (MemberInit.isInvalid()) 3103 return true; 3104 3105 Init = MemberInit.get(); 3106 } 3107 3108 if (DirectMember) { 3109 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 3110 InitRange.getBegin(), Init, 3111 InitRange.getEnd()); 3112 } else { 3113 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 3114 InitRange.getBegin(), Init, 3115 InitRange.getEnd()); 3116 } 3117 } 3118 3119 MemInitResult 3120 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 3121 CXXRecordDecl *ClassDecl) { 3122 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3123 if (!LangOpts.CPlusPlus11) 3124 return Diag(NameLoc, diag::err_delegating_ctor) 3125 << TInfo->getTypeLoc().getLocalSourceRange(); 3126 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 3127 3128 bool InitList = true; 3129 MultiExprArg Args = Init; 3130 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3131 InitList = false; 3132 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3133 } 3134 3135 SourceRange InitRange = Init->getSourceRange(); 3136 // Initialize the object. 3137 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 3138 QualType(ClassDecl->getTypeForDecl(), 0)); 3139 InitializationKind Kind = 3140 InitList ? InitializationKind::CreateDirectList(NameLoc) 3141 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 3142 InitRange.getEnd()); 3143 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 3144 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 3145 Args, nullptr); 3146 if (DelegationInit.isInvalid()) 3147 return true; 3148 3149 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 3150 "Delegating constructor with no target?"); 3151 3152 // C++11 [class.base.init]p7: 3153 // The initialization of each base and member constitutes a 3154 // full-expression. 3155 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 3156 InitRange.getBegin()); 3157 if (DelegationInit.isInvalid()) 3158 return true; 3159 3160 // If we are in a dependent context, template instantiation will 3161 // perform this type-checking again. Just save the arguments that we 3162 // received in a ParenListExpr. 3163 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3164 // of the information that we have about the base 3165 // initializer. However, deconstructing the ASTs is a dicey process, 3166 // and this approach is far more likely to get the corner cases right. 3167 if (CurContext->isDependentContext()) 3168 DelegationInit = Init; 3169 3170 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 3171 DelegationInit.getAs<Expr>(), 3172 InitRange.getEnd()); 3173 } 3174 3175 MemInitResult 3176 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 3177 Expr *Init, CXXRecordDecl *ClassDecl, 3178 SourceLocation EllipsisLoc) { 3179 SourceLocation BaseLoc 3180 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3181 3182 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 3183 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 3184 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3185 3186 // C++ [class.base.init]p2: 3187 // [...] Unless the mem-initializer-id names a nonstatic data 3188 // member of the constructor's class or a direct or virtual base 3189 // of that class, the mem-initializer is ill-formed. A 3190 // mem-initializer-list can initialize a base class using any 3191 // name that denotes that base class type. 3192 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 3193 3194 SourceRange InitRange = Init->getSourceRange(); 3195 if (EllipsisLoc.isValid()) { 3196 // This is a pack expansion. 3197 if (!BaseType->containsUnexpandedParameterPack()) { 3198 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 3199 << SourceRange(BaseLoc, InitRange.getEnd()); 3200 3201 EllipsisLoc = SourceLocation(); 3202 } 3203 } else { 3204 // Check for any unexpanded parameter packs. 3205 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 3206 return true; 3207 3208 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3209 return true; 3210 } 3211 3212 // Check for direct and virtual base classes. 3213 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 3214 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 3215 if (!Dependent) { 3216 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 3217 BaseType)) 3218 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 3219 3220 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 3221 VirtualBaseSpec); 3222 3223 // C++ [base.class.init]p2: 3224 // Unless the mem-initializer-id names a nonstatic data member of the 3225 // constructor's class or a direct or virtual base of that class, the 3226 // mem-initializer is ill-formed. 3227 if (!DirectBaseSpec && !VirtualBaseSpec) { 3228 // If the class has any dependent bases, then it's possible that 3229 // one of those types will resolve to the same type as 3230 // BaseType. Therefore, just treat this as a dependent base 3231 // class initialization. FIXME: Should we try to check the 3232 // initialization anyway? It seems odd. 3233 if (ClassDecl->hasAnyDependentBases()) 3234 Dependent = true; 3235 else 3236 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 3237 << BaseType << Context.getTypeDeclType(ClassDecl) 3238 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3239 } 3240 } 3241 3242 if (Dependent) { 3243 DiscardCleanupsInEvaluationContext(); 3244 3245 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3246 /*IsVirtual=*/false, 3247 InitRange.getBegin(), Init, 3248 InitRange.getEnd(), EllipsisLoc); 3249 } 3250 3251 // C++ [base.class.init]p2: 3252 // If a mem-initializer-id is ambiguous because it designates both 3253 // a direct non-virtual base class and an inherited virtual base 3254 // class, the mem-initializer is ill-formed. 3255 if (DirectBaseSpec && VirtualBaseSpec) 3256 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 3257 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3258 3259 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 3260 if (!BaseSpec) 3261 BaseSpec = VirtualBaseSpec; 3262 3263 // Initialize the base. 3264 bool InitList = true; 3265 MultiExprArg Args = Init; 3266 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3267 InitList = false; 3268 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3269 } 3270 3271 InitializedEntity BaseEntity = 3272 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 3273 InitializationKind Kind = 3274 InitList ? InitializationKind::CreateDirectList(BaseLoc) 3275 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 3276 InitRange.getEnd()); 3277 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 3278 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 3279 if (BaseInit.isInvalid()) 3280 return true; 3281 3282 // C++11 [class.base.init]p7: 3283 // The initialization of each base and member constitutes a 3284 // full-expression. 3285 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 3286 if (BaseInit.isInvalid()) 3287 return true; 3288 3289 // If we are in a dependent context, template instantiation will 3290 // perform this type-checking again. Just save the arguments that we 3291 // received in a ParenListExpr. 3292 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3293 // of the information that we have about the base 3294 // initializer. However, deconstructing the ASTs is a dicey process, 3295 // and this approach is far more likely to get the corner cases right. 3296 if (CurContext->isDependentContext()) 3297 BaseInit = Init; 3298 3299 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3300 BaseSpec->isVirtual(), 3301 InitRange.getBegin(), 3302 BaseInit.getAs<Expr>(), 3303 InitRange.getEnd(), EllipsisLoc); 3304 } 3305 3306 // Create a static_cast\<T&&>(expr). 3307 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 3308 if (T.isNull()) T = E->getType(); 3309 QualType TargetType = SemaRef.BuildReferenceType( 3310 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 3311 SourceLocation ExprLoc = E->getLocStart(); 3312 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 3313 TargetType, ExprLoc); 3314 3315 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 3316 SourceRange(ExprLoc, ExprLoc), 3317 E->getSourceRange()).get(); 3318 } 3319 3320 /// ImplicitInitializerKind - How an implicit base or member initializer should 3321 /// initialize its base or member. 3322 enum ImplicitInitializerKind { 3323 IIK_Default, 3324 IIK_Copy, 3325 IIK_Move, 3326 IIK_Inherit 3327 }; 3328 3329 static bool 3330 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3331 ImplicitInitializerKind ImplicitInitKind, 3332 CXXBaseSpecifier *BaseSpec, 3333 bool IsInheritedVirtualBase, 3334 CXXCtorInitializer *&CXXBaseInit) { 3335 InitializedEntity InitEntity 3336 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 3337 IsInheritedVirtualBase); 3338 3339 ExprResult BaseInit; 3340 3341 switch (ImplicitInitKind) { 3342 case IIK_Inherit: { 3343 const CXXRecordDecl *Inherited = 3344 Constructor->getInheritedConstructor()->getParent(); 3345 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 3346 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 3347 // C++11 [class.inhctor]p8: 3348 // Each expression in the expression-list is of the form 3349 // static_cast<T&&>(p), where p is the name of the corresponding 3350 // constructor parameter and T is the declared type of p. 3351 SmallVector<Expr*, 16> Args; 3352 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 3353 ParmVarDecl *PD = Constructor->getParamDecl(I); 3354 ExprResult ArgExpr = 3355 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 3356 VK_LValue, SourceLocation()); 3357 if (ArgExpr.isInvalid()) 3358 return true; 3359 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType())); 3360 } 3361 3362 InitializationKind InitKind = InitializationKind::CreateDirect( 3363 Constructor->getLocation(), SourceLocation(), SourceLocation()); 3364 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 3365 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 3366 break; 3367 } 3368 } 3369 // Fall through. 3370 case IIK_Default: { 3371 InitializationKind InitKind 3372 = InitializationKind::CreateDefault(Constructor->getLocation()); 3373 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3374 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3375 break; 3376 } 3377 3378 case IIK_Move: 3379 case IIK_Copy: { 3380 bool Moving = ImplicitInitKind == IIK_Move; 3381 ParmVarDecl *Param = Constructor->getParamDecl(0); 3382 QualType ParamType = Param->getType().getNonReferenceType(); 3383 3384 Expr *CopyCtorArg = 3385 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3386 SourceLocation(), Param, false, 3387 Constructor->getLocation(), ParamType, 3388 VK_LValue, nullptr); 3389 3390 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 3391 3392 // Cast to the base class to avoid ambiguities. 3393 QualType ArgTy = 3394 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3395 ParamType.getQualifiers()); 3396 3397 if (Moving) { 3398 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3399 } 3400 3401 CXXCastPath BasePath; 3402 BasePath.push_back(BaseSpec); 3403 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3404 CK_UncheckedDerivedToBase, 3405 Moving ? VK_XValue : VK_LValue, 3406 &BasePath).get(); 3407 3408 InitializationKind InitKind 3409 = InitializationKind::CreateDirect(Constructor->getLocation(), 3410 SourceLocation(), SourceLocation()); 3411 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3412 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3413 break; 3414 } 3415 } 3416 3417 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3418 if (BaseInit.isInvalid()) 3419 return true; 3420 3421 CXXBaseInit = 3422 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3423 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3424 SourceLocation()), 3425 BaseSpec->isVirtual(), 3426 SourceLocation(), 3427 BaseInit.getAs<Expr>(), 3428 SourceLocation(), 3429 SourceLocation()); 3430 3431 return false; 3432 } 3433 3434 static bool RefersToRValueRef(Expr *MemRef) { 3435 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3436 return Referenced->getType()->isRValueReferenceType(); 3437 } 3438 3439 static bool 3440 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3441 ImplicitInitializerKind ImplicitInitKind, 3442 FieldDecl *Field, IndirectFieldDecl *Indirect, 3443 CXXCtorInitializer *&CXXMemberInit) { 3444 if (Field->isInvalidDecl()) 3445 return true; 3446 3447 SourceLocation Loc = Constructor->getLocation(); 3448 3449 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3450 bool Moving = ImplicitInitKind == IIK_Move; 3451 ParmVarDecl *Param = Constructor->getParamDecl(0); 3452 QualType ParamType = Param->getType().getNonReferenceType(); 3453 3454 // Suppress copying zero-width bitfields. 3455 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3456 return false; 3457 3458 Expr *MemberExprBase = 3459 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3460 SourceLocation(), Param, false, 3461 Loc, ParamType, VK_LValue, nullptr); 3462 3463 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3464 3465 if (Moving) { 3466 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3467 } 3468 3469 // Build a reference to this field within the parameter. 3470 CXXScopeSpec SS; 3471 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3472 Sema::LookupMemberName); 3473 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3474 : cast<ValueDecl>(Field), AS_public); 3475 MemberLookup.resolveKind(); 3476 ExprResult CtorArg 3477 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3478 ParamType, Loc, 3479 /*IsArrow=*/false, 3480 SS, 3481 /*TemplateKWLoc=*/SourceLocation(), 3482 /*FirstQualifierInScope=*/nullptr, 3483 MemberLookup, 3484 /*TemplateArgs=*/nullptr); 3485 if (CtorArg.isInvalid()) 3486 return true; 3487 3488 // C++11 [class.copy]p15: 3489 // - if a member m has rvalue reference type T&&, it is direct-initialized 3490 // with static_cast<T&&>(x.m); 3491 if (RefersToRValueRef(CtorArg.get())) { 3492 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3493 } 3494 3495 // When the field we are copying is an array, create index variables for 3496 // each dimension of the array. We use these index variables to subscript 3497 // the source array, and other clients (e.g., CodeGen) will perform the 3498 // necessary iteration with these index variables. 3499 SmallVector<VarDecl *, 4> IndexVariables; 3500 QualType BaseType = Field->getType(); 3501 QualType SizeType = SemaRef.Context.getSizeType(); 3502 bool InitializingArray = false; 3503 while (const ConstantArrayType *Array 3504 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3505 InitializingArray = true; 3506 // Create the iteration variable for this array index. 3507 IdentifierInfo *IterationVarName = nullptr; 3508 { 3509 SmallString<8> Str; 3510 llvm::raw_svector_ostream OS(Str); 3511 OS << "__i" << IndexVariables.size(); 3512 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3513 } 3514 VarDecl *IterationVar 3515 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3516 IterationVarName, SizeType, 3517 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3518 SC_None); 3519 IndexVariables.push_back(IterationVar); 3520 3521 // Create a reference to the iteration variable. 3522 ExprResult IterationVarRef 3523 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3524 assert(!IterationVarRef.isInvalid() && 3525 "Reference to invented variable cannot fail!"); 3526 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get()); 3527 assert(!IterationVarRef.isInvalid() && 3528 "Conversion of invented variable cannot fail!"); 3529 3530 // Subscript the array with this iteration variable. 3531 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc, 3532 IterationVarRef.get(), 3533 Loc); 3534 if (CtorArg.isInvalid()) 3535 return true; 3536 3537 BaseType = Array->getElementType(); 3538 } 3539 3540 // The array subscript expression is an lvalue, which is wrong for moving. 3541 if (Moving && InitializingArray) 3542 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3543 3544 // Construct the entity that we will be initializing. For an array, this 3545 // will be first element in the array, which may require several levels 3546 // of array-subscript entities. 3547 SmallVector<InitializedEntity, 4> Entities; 3548 Entities.reserve(1 + IndexVariables.size()); 3549 if (Indirect) 3550 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3551 else 3552 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3553 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3554 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3555 0, 3556 Entities.back())); 3557 3558 // Direct-initialize to use the copy constructor. 3559 InitializationKind InitKind = 3560 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3561 3562 Expr *CtorArgE = CtorArg.getAs<Expr>(); 3563 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 3564 CtorArgE); 3565 3566 ExprResult MemberInit 3567 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3568 MultiExprArg(&CtorArgE, 1)); 3569 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3570 if (MemberInit.isInvalid()) 3571 return true; 3572 3573 if (Indirect) { 3574 assert(IndexVariables.size() == 0 && 3575 "Indirect field improperly initialized"); 3576 CXXMemberInit 3577 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3578 Loc, Loc, 3579 MemberInit.getAs<Expr>(), 3580 Loc); 3581 } else 3582 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3583 Loc, MemberInit.getAs<Expr>(), 3584 Loc, 3585 IndexVariables.data(), 3586 IndexVariables.size()); 3587 return false; 3588 } 3589 3590 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3591 "Unhandled implicit init kind!"); 3592 3593 QualType FieldBaseElementType = 3594 SemaRef.Context.getBaseElementType(Field->getType()); 3595 3596 if (FieldBaseElementType->isRecordType()) { 3597 InitializedEntity InitEntity 3598 = Indirect? InitializedEntity::InitializeMember(Indirect) 3599 : InitializedEntity::InitializeMember(Field); 3600 InitializationKind InitKind = 3601 InitializationKind::CreateDefault(Loc); 3602 3603 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3604 ExprResult MemberInit = 3605 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3606 3607 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3608 if (MemberInit.isInvalid()) 3609 return true; 3610 3611 if (Indirect) 3612 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3613 Indirect, Loc, 3614 Loc, 3615 MemberInit.get(), 3616 Loc); 3617 else 3618 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3619 Field, Loc, Loc, 3620 MemberInit.get(), 3621 Loc); 3622 return false; 3623 } 3624 3625 if (!Field->getParent()->isUnion()) { 3626 if (FieldBaseElementType->isReferenceType()) { 3627 SemaRef.Diag(Constructor->getLocation(), 3628 diag::err_uninitialized_member_in_ctor) 3629 << (int)Constructor->isImplicit() 3630 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3631 << 0 << Field->getDeclName(); 3632 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3633 return true; 3634 } 3635 3636 if (FieldBaseElementType.isConstQualified()) { 3637 SemaRef.Diag(Constructor->getLocation(), 3638 diag::err_uninitialized_member_in_ctor) 3639 << (int)Constructor->isImplicit() 3640 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3641 << 1 << Field->getDeclName(); 3642 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3643 return true; 3644 } 3645 } 3646 3647 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3648 FieldBaseElementType->isObjCRetainableType() && 3649 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3650 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3651 // ARC: 3652 // Default-initialize Objective-C pointers to NULL. 3653 CXXMemberInit 3654 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3655 Loc, Loc, 3656 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3657 Loc); 3658 return false; 3659 } 3660 3661 // Nothing to initialize. 3662 CXXMemberInit = nullptr; 3663 return false; 3664 } 3665 3666 namespace { 3667 struct BaseAndFieldInfo { 3668 Sema &S; 3669 CXXConstructorDecl *Ctor; 3670 bool AnyErrorsInInits; 3671 ImplicitInitializerKind IIK; 3672 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3673 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3674 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 3675 3676 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3677 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3678 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3679 if (Generated && Ctor->isCopyConstructor()) 3680 IIK = IIK_Copy; 3681 else if (Generated && Ctor->isMoveConstructor()) 3682 IIK = IIK_Move; 3683 else if (Ctor->getInheritedConstructor()) 3684 IIK = IIK_Inherit; 3685 else 3686 IIK = IIK_Default; 3687 } 3688 3689 bool isImplicitCopyOrMove() const { 3690 switch (IIK) { 3691 case IIK_Copy: 3692 case IIK_Move: 3693 return true; 3694 3695 case IIK_Default: 3696 case IIK_Inherit: 3697 return false; 3698 } 3699 3700 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3701 } 3702 3703 bool addFieldInitializer(CXXCtorInitializer *Init) { 3704 AllToInit.push_back(Init); 3705 3706 // Check whether this initializer makes the field "used". 3707 if (Init->getInit()->HasSideEffects(S.Context)) 3708 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3709 3710 return false; 3711 } 3712 3713 bool isInactiveUnionMember(FieldDecl *Field) { 3714 RecordDecl *Record = Field->getParent(); 3715 if (!Record->isUnion()) 3716 return false; 3717 3718 if (FieldDecl *Active = 3719 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 3720 return Active != Field->getCanonicalDecl(); 3721 3722 // In an implicit copy or move constructor, ignore any in-class initializer. 3723 if (isImplicitCopyOrMove()) 3724 return true; 3725 3726 // If there's no explicit initialization, the field is active only if it 3727 // has an in-class initializer... 3728 if (Field->hasInClassInitializer()) 3729 return false; 3730 // ... or it's an anonymous struct or union whose class has an in-class 3731 // initializer. 3732 if (!Field->isAnonymousStructOrUnion()) 3733 return true; 3734 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 3735 return !FieldRD->hasInClassInitializer(); 3736 } 3737 3738 /// \brief Determine whether the given field is, or is within, a union member 3739 /// that is inactive (because there was an initializer given for a different 3740 /// member of the union, or because the union was not initialized at all). 3741 bool isWithinInactiveUnionMember(FieldDecl *Field, 3742 IndirectFieldDecl *Indirect) { 3743 if (!Indirect) 3744 return isInactiveUnionMember(Field); 3745 3746 for (auto *C : Indirect->chain()) { 3747 FieldDecl *Field = dyn_cast<FieldDecl>(C); 3748 if (Field && isInactiveUnionMember(Field)) 3749 return true; 3750 } 3751 return false; 3752 } 3753 }; 3754 } 3755 3756 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3757 /// array type. 3758 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3759 if (T->isIncompleteArrayType()) 3760 return true; 3761 3762 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3763 if (!ArrayT->getSize()) 3764 return true; 3765 3766 T = ArrayT->getElementType(); 3767 } 3768 3769 return false; 3770 } 3771 3772 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3773 FieldDecl *Field, 3774 IndirectFieldDecl *Indirect = nullptr) { 3775 if (Field->isInvalidDecl()) 3776 return false; 3777 3778 // Overwhelmingly common case: we have a direct initializer for this field. 3779 if (CXXCtorInitializer *Init = 3780 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 3781 return Info.addFieldInitializer(Init); 3782 3783 // C++11 [class.base.init]p8: 3784 // if the entity is a non-static data member that has a 3785 // brace-or-equal-initializer and either 3786 // -- the constructor's class is a union and no other variant member of that 3787 // union is designated by a mem-initializer-id or 3788 // -- the constructor's class is not a union, and, if the entity is a member 3789 // of an anonymous union, no other member of that union is designated by 3790 // a mem-initializer-id, 3791 // the entity is initialized as specified in [dcl.init]. 3792 // 3793 // We also apply the same rules to handle anonymous structs within anonymous 3794 // unions. 3795 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 3796 return false; 3797 3798 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3799 ExprResult DIE = 3800 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 3801 if (DIE.isInvalid()) 3802 return true; 3803 CXXCtorInitializer *Init; 3804 if (Indirect) 3805 Init = new (SemaRef.Context) 3806 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 3807 SourceLocation(), DIE.get(), SourceLocation()); 3808 else 3809 Init = new (SemaRef.Context) 3810 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 3811 SourceLocation(), DIE.get(), SourceLocation()); 3812 return Info.addFieldInitializer(Init); 3813 } 3814 3815 // Don't initialize incomplete or zero-length arrays. 3816 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3817 return false; 3818 3819 // Don't try to build an implicit initializer if there were semantic 3820 // errors in any of the initializers (and therefore we might be 3821 // missing some that the user actually wrote). 3822 if (Info.AnyErrorsInInits) 3823 return false; 3824 3825 CXXCtorInitializer *Init = nullptr; 3826 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3827 Indirect, Init)) 3828 return true; 3829 3830 if (!Init) 3831 return false; 3832 3833 return Info.addFieldInitializer(Init); 3834 } 3835 3836 bool 3837 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3838 CXXCtorInitializer *Initializer) { 3839 assert(Initializer->isDelegatingInitializer()); 3840 Constructor->setNumCtorInitializers(1); 3841 CXXCtorInitializer **initializer = 3842 new (Context) CXXCtorInitializer*[1]; 3843 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3844 Constructor->setCtorInitializers(initializer); 3845 3846 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3847 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3848 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3849 } 3850 3851 DelegatingCtorDecls.push_back(Constructor); 3852 3853 DiagnoseUninitializedFields(*this, Constructor); 3854 3855 return false; 3856 } 3857 3858 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3859 ArrayRef<CXXCtorInitializer *> Initializers) { 3860 if (Constructor->isDependentContext()) { 3861 // Just store the initializers as written, they will be checked during 3862 // instantiation. 3863 if (!Initializers.empty()) { 3864 Constructor->setNumCtorInitializers(Initializers.size()); 3865 CXXCtorInitializer **baseOrMemberInitializers = 3866 new (Context) CXXCtorInitializer*[Initializers.size()]; 3867 memcpy(baseOrMemberInitializers, Initializers.data(), 3868 Initializers.size() * sizeof(CXXCtorInitializer*)); 3869 Constructor->setCtorInitializers(baseOrMemberInitializers); 3870 } 3871 3872 // Let template instantiation know whether we had errors. 3873 if (AnyErrors) 3874 Constructor->setInvalidDecl(); 3875 3876 return false; 3877 } 3878 3879 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3880 3881 // We need to build the initializer AST according to order of construction 3882 // and not what user specified in the Initializers list. 3883 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3884 if (!ClassDecl) 3885 return true; 3886 3887 bool HadError = false; 3888 3889 for (unsigned i = 0; i < Initializers.size(); i++) { 3890 CXXCtorInitializer *Member = Initializers[i]; 3891 3892 if (Member->isBaseInitializer()) 3893 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3894 else { 3895 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 3896 3897 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 3898 for (auto *C : F->chain()) { 3899 FieldDecl *FD = dyn_cast<FieldDecl>(C); 3900 if (FD && FD->getParent()->isUnion()) 3901 Info.ActiveUnionMember.insert(std::make_pair( 3902 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3903 } 3904 } else if (FieldDecl *FD = Member->getMember()) { 3905 if (FD->getParent()->isUnion()) 3906 Info.ActiveUnionMember.insert(std::make_pair( 3907 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3908 } 3909 } 3910 } 3911 3912 // Keep track of the direct virtual bases. 3913 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3914 for (auto &I : ClassDecl->bases()) { 3915 if (I.isVirtual()) 3916 DirectVBases.insert(&I); 3917 } 3918 3919 // Push virtual bases before others. 3920 for (auto &VBase : ClassDecl->vbases()) { 3921 if (CXXCtorInitializer *Value 3922 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 3923 // [class.base.init]p7, per DR257: 3924 // A mem-initializer where the mem-initializer-id names a virtual base 3925 // class is ignored during execution of a constructor of any class that 3926 // is not the most derived class. 3927 if (ClassDecl->isAbstract()) { 3928 // FIXME: Provide a fixit to remove the base specifier. This requires 3929 // tracking the location of the associated comma for a base specifier. 3930 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3931 << VBase.getType() << ClassDecl; 3932 DiagnoseAbstractType(ClassDecl); 3933 } 3934 3935 Info.AllToInit.push_back(Value); 3936 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3937 // [class.base.init]p8, per DR257: 3938 // If a given [...] base class is not named by a mem-initializer-id 3939 // [...] and the entity is not a virtual base class of an abstract 3940 // class, then [...] the entity is default-initialized. 3941 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 3942 CXXCtorInitializer *CXXBaseInit; 3943 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3944 &VBase, IsInheritedVirtualBase, 3945 CXXBaseInit)) { 3946 HadError = true; 3947 continue; 3948 } 3949 3950 Info.AllToInit.push_back(CXXBaseInit); 3951 } 3952 } 3953 3954 // Non-virtual bases. 3955 for (auto &Base : ClassDecl->bases()) { 3956 // Virtuals are in the virtual base list and already constructed. 3957 if (Base.isVirtual()) 3958 continue; 3959 3960 if (CXXCtorInitializer *Value 3961 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 3962 Info.AllToInit.push_back(Value); 3963 } else if (!AnyErrors) { 3964 CXXCtorInitializer *CXXBaseInit; 3965 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3966 &Base, /*IsInheritedVirtualBase=*/false, 3967 CXXBaseInit)) { 3968 HadError = true; 3969 continue; 3970 } 3971 3972 Info.AllToInit.push_back(CXXBaseInit); 3973 } 3974 } 3975 3976 // Fields. 3977 for (auto *Mem : ClassDecl->decls()) { 3978 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 3979 // C++ [class.bit]p2: 3980 // A declaration for a bit-field that omits the identifier declares an 3981 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3982 // initialized. 3983 if (F->isUnnamedBitfield()) 3984 continue; 3985 3986 // If we're not generating the implicit copy/move constructor, then we'll 3987 // handle anonymous struct/union fields based on their individual 3988 // indirect fields. 3989 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3990 continue; 3991 3992 if (CollectFieldInitializer(*this, Info, F)) 3993 HadError = true; 3994 continue; 3995 } 3996 3997 // Beyond this point, we only consider default initialization. 3998 if (Info.isImplicitCopyOrMove()) 3999 continue; 4000 4001 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4002 if (F->getType()->isIncompleteArrayType()) { 4003 assert(ClassDecl->hasFlexibleArrayMember() && 4004 "Incomplete array type is not valid"); 4005 continue; 4006 } 4007 4008 // Initialize each field of an anonymous struct individually. 4009 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4010 HadError = true; 4011 4012 continue; 4013 } 4014 } 4015 4016 unsigned NumInitializers = Info.AllToInit.size(); 4017 if (NumInitializers > 0) { 4018 Constructor->setNumCtorInitializers(NumInitializers); 4019 CXXCtorInitializer **baseOrMemberInitializers = 4020 new (Context) CXXCtorInitializer*[NumInitializers]; 4021 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4022 NumInitializers * sizeof(CXXCtorInitializer*)); 4023 Constructor->setCtorInitializers(baseOrMemberInitializers); 4024 4025 // Constructors implicitly reference the base and member 4026 // destructors. 4027 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4028 Constructor->getParent()); 4029 } 4030 4031 return HadError; 4032 } 4033 4034 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4035 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4036 const RecordDecl *RD = RT->getDecl(); 4037 if (RD->isAnonymousStructOrUnion()) { 4038 for (auto *Field : RD->fields()) 4039 PopulateKeysForFields(Field, IdealInits); 4040 return; 4041 } 4042 } 4043 IdealInits.push_back(Field->getCanonicalDecl()); 4044 } 4045 4046 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4047 return Context.getCanonicalType(BaseType).getTypePtr(); 4048 } 4049 4050 static const void *GetKeyForMember(ASTContext &Context, 4051 CXXCtorInitializer *Member) { 4052 if (!Member->isAnyMemberInitializer()) 4053 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4054 4055 return Member->getAnyMember()->getCanonicalDecl(); 4056 } 4057 4058 static void DiagnoseBaseOrMemInitializerOrder( 4059 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4060 ArrayRef<CXXCtorInitializer *> Inits) { 4061 if (Constructor->getDeclContext()->isDependentContext()) 4062 return; 4063 4064 // Don't check initializers order unless the warning is enabled at the 4065 // location of at least one initializer. 4066 bool ShouldCheckOrder = false; 4067 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4068 CXXCtorInitializer *Init = Inits[InitIndex]; 4069 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4070 Init->getSourceLocation())) { 4071 ShouldCheckOrder = true; 4072 break; 4073 } 4074 } 4075 if (!ShouldCheckOrder) 4076 return; 4077 4078 // Build the list of bases and members in the order that they'll 4079 // actually be initialized. The explicit initializers should be in 4080 // this same order but may be missing things. 4081 SmallVector<const void*, 32> IdealInitKeys; 4082 4083 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4084 4085 // 1. Virtual bases. 4086 for (const auto &VBase : ClassDecl->vbases()) 4087 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4088 4089 // 2. Non-virtual bases. 4090 for (const auto &Base : ClassDecl->bases()) { 4091 if (Base.isVirtual()) 4092 continue; 4093 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4094 } 4095 4096 // 3. Direct fields. 4097 for (auto *Field : ClassDecl->fields()) { 4098 if (Field->isUnnamedBitfield()) 4099 continue; 4100 4101 PopulateKeysForFields(Field, IdealInitKeys); 4102 } 4103 4104 unsigned NumIdealInits = IdealInitKeys.size(); 4105 unsigned IdealIndex = 0; 4106 4107 CXXCtorInitializer *PrevInit = nullptr; 4108 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4109 CXXCtorInitializer *Init = Inits[InitIndex]; 4110 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4111 4112 // Scan forward to try to find this initializer in the idealized 4113 // initializers list. 4114 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4115 if (InitKey == IdealInitKeys[IdealIndex]) 4116 break; 4117 4118 // If we didn't find this initializer, it must be because we 4119 // scanned past it on a previous iteration. That can only 4120 // happen if we're out of order; emit a warning. 4121 if (IdealIndex == NumIdealInits && PrevInit) { 4122 Sema::SemaDiagnosticBuilder D = 4123 SemaRef.Diag(PrevInit->getSourceLocation(), 4124 diag::warn_initializer_out_of_order); 4125 4126 if (PrevInit->isAnyMemberInitializer()) 4127 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4128 else 4129 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4130 4131 if (Init->isAnyMemberInitializer()) 4132 D << 0 << Init->getAnyMember()->getDeclName(); 4133 else 4134 D << 1 << Init->getTypeSourceInfo()->getType(); 4135 4136 // Move back to the initializer's location in the ideal list. 4137 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4138 if (InitKey == IdealInitKeys[IdealIndex]) 4139 break; 4140 4141 assert(IdealIndex < NumIdealInits && 4142 "initializer not found in initializer list"); 4143 } 4144 4145 PrevInit = Init; 4146 } 4147 } 4148 4149 namespace { 4150 bool CheckRedundantInit(Sema &S, 4151 CXXCtorInitializer *Init, 4152 CXXCtorInitializer *&PrevInit) { 4153 if (!PrevInit) { 4154 PrevInit = Init; 4155 return false; 4156 } 4157 4158 if (FieldDecl *Field = Init->getAnyMember()) 4159 S.Diag(Init->getSourceLocation(), 4160 diag::err_multiple_mem_initialization) 4161 << Field->getDeclName() 4162 << Init->getSourceRange(); 4163 else { 4164 const Type *BaseClass = Init->getBaseClass(); 4165 assert(BaseClass && "neither field nor base"); 4166 S.Diag(Init->getSourceLocation(), 4167 diag::err_multiple_base_initialization) 4168 << QualType(BaseClass, 0) 4169 << Init->getSourceRange(); 4170 } 4171 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4172 << 0 << PrevInit->getSourceRange(); 4173 4174 return true; 4175 } 4176 4177 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4178 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4179 4180 bool CheckRedundantUnionInit(Sema &S, 4181 CXXCtorInitializer *Init, 4182 RedundantUnionMap &Unions) { 4183 FieldDecl *Field = Init->getAnyMember(); 4184 RecordDecl *Parent = Field->getParent(); 4185 NamedDecl *Child = Field; 4186 4187 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 4188 if (Parent->isUnion()) { 4189 UnionEntry &En = Unions[Parent]; 4190 if (En.first && En.first != Child) { 4191 S.Diag(Init->getSourceLocation(), 4192 diag::err_multiple_mem_union_initialization) 4193 << Field->getDeclName() 4194 << Init->getSourceRange(); 4195 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 4196 << 0 << En.second->getSourceRange(); 4197 return true; 4198 } 4199 if (!En.first) { 4200 En.first = Child; 4201 En.second = Init; 4202 } 4203 if (!Parent->isAnonymousStructOrUnion()) 4204 return false; 4205 } 4206 4207 Child = Parent; 4208 Parent = cast<RecordDecl>(Parent->getDeclContext()); 4209 } 4210 4211 return false; 4212 } 4213 } 4214 4215 /// ActOnMemInitializers - Handle the member initializers for a constructor. 4216 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 4217 SourceLocation ColonLoc, 4218 ArrayRef<CXXCtorInitializer*> MemInits, 4219 bool AnyErrors) { 4220 if (!ConstructorDecl) 4221 return; 4222 4223 AdjustDeclIfTemplate(ConstructorDecl); 4224 4225 CXXConstructorDecl *Constructor 4226 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 4227 4228 if (!Constructor) { 4229 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 4230 return; 4231 } 4232 4233 // Mapping for the duplicate initializers check. 4234 // For member initializers, this is keyed with a FieldDecl*. 4235 // For base initializers, this is keyed with a Type*. 4236 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 4237 4238 // Mapping for the inconsistent anonymous-union initializers check. 4239 RedundantUnionMap MemberUnions; 4240 4241 bool HadError = false; 4242 for (unsigned i = 0; i < MemInits.size(); i++) { 4243 CXXCtorInitializer *Init = MemInits[i]; 4244 4245 // Set the source order index. 4246 Init->setSourceOrder(i); 4247 4248 if (Init->isAnyMemberInitializer()) { 4249 const void *Key = GetKeyForMember(Context, Init); 4250 if (CheckRedundantInit(*this, Init, Members[Key]) || 4251 CheckRedundantUnionInit(*this, Init, MemberUnions)) 4252 HadError = true; 4253 } else if (Init->isBaseInitializer()) { 4254 const void *Key = GetKeyForMember(Context, Init); 4255 if (CheckRedundantInit(*this, Init, Members[Key])) 4256 HadError = true; 4257 } else { 4258 assert(Init->isDelegatingInitializer()); 4259 // This must be the only initializer 4260 if (MemInits.size() != 1) { 4261 Diag(Init->getSourceLocation(), 4262 diag::err_delegating_initializer_alone) 4263 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 4264 // We will treat this as being the only initializer. 4265 } 4266 SetDelegatingInitializer(Constructor, MemInits[i]); 4267 // Return immediately as the initializer is set. 4268 return; 4269 } 4270 } 4271 4272 if (HadError) 4273 return; 4274 4275 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 4276 4277 SetCtorInitializers(Constructor, AnyErrors, MemInits); 4278 4279 DiagnoseUninitializedFields(*this, Constructor); 4280 } 4281 4282 void 4283 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 4284 CXXRecordDecl *ClassDecl) { 4285 // Ignore dependent contexts. Also ignore unions, since their members never 4286 // have destructors implicitly called. 4287 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 4288 return; 4289 4290 // FIXME: all the access-control diagnostics are positioned on the 4291 // field/base declaration. That's probably good; that said, the 4292 // user might reasonably want to know why the destructor is being 4293 // emitted, and we currently don't say. 4294 4295 // Non-static data members. 4296 for (auto *Field : ClassDecl->fields()) { 4297 if (Field->isInvalidDecl()) 4298 continue; 4299 4300 // Don't destroy incomplete or zero-length arrays. 4301 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 4302 continue; 4303 4304 QualType FieldType = Context.getBaseElementType(Field->getType()); 4305 4306 const RecordType* RT = FieldType->getAs<RecordType>(); 4307 if (!RT) 4308 continue; 4309 4310 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4311 if (FieldClassDecl->isInvalidDecl()) 4312 continue; 4313 if (FieldClassDecl->hasIrrelevantDestructor()) 4314 continue; 4315 // The destructor for an implicit anonymous union member is never invoked. 4316 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 4317 continue; 4318 4319 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 4320 assert(Dtor && "No dtor found for FieldClassDecl!"); 4321 CheckDestructorAccess(Field->getLocation(), Dtor, 4322 PDiag(diag::err_access_dtor_field) 4323 << Field->getDeclName() 4324 << FieldType); 4325 4326 MarkFunctionReferenced(Location, Dtor); 4327 DiagnoseUseOfDecl(Dtor, Location); 4328 } 4329 4330 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 4331 4332 // Bases. 4333 for (const auto &Base : ClassDecl->bases()) { 4334 // Bases are always records in a well-formed non-dependent class. 4335 const RecordType *RT = Base.getType()->getAs<RecordType>(); 4336 4337 // Remember direct virtual bases. 4338 if (Base.isVirtual()) 4339 DirectVirtualBases.insert(RT); 4340 4341 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4342 // If our base class is invalid, we probably can't get its dtor anyway. 4343 if (BaseClassDecl->isInvalidDecl()) 4344 continue; 4345 if (BaseClassDecl->hasIrrelevantDestructor()) 4346 continue; 4347 4348 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4349 assert(Dtor && "No dtor found for BaseClassDecl!"); 4350 4351 // FIXME: caret should be on the start of the class name 4352 CheckDestructorAccess(Base.getLocStart(), Dtor, 4353 PDiag(diag::err_access_dtor_base) 4354 << Base.getType() 4355 << Base.getSourceRange(), 4356 Context.getTypeDeclType(ClassDecl)); 4357 4358 MarkFunctionReferenced(Location, Dtor); 4359 DiagnoseUseOfDecl(Dtor, Location); 4360 } 4361 4362 // Virtual bases. 4363 for (const auto &VBase : ClassDecl->vbases()) { 4364 // Bases are always records in a well-formed non-dependent class. 4365 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 4366 4367 // Ignore direct virtual bases. 4368 if (DirectVirtualBases.count(RT)) 4369 continue; 4370 4371 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4372 // If our base class is invalid, we probably can't get its dtor anyway. 4373 if (BaseClassDecl->isInvalidDecl()) 4374 continue; 4375 if (BaseClassDecl->hasIrrelevantDestructor()) 4376 continue; 4377 4378 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4379 assert(Dtor && "No dtor found for BaseClassDecl!"); 4380 if (CheckDestructorAccess( 4381 ClassDecl->getLocation(), Dtor, 4382 PDiag(diag::err_access_dtor_vbase) 4383 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 4384 Context.getTypeDeclType(ClassDecl)) == 4385 AR_accessible) { 4386 CheckDerivedToBaseConversion( 4387 Context.getTypeDeclType(ClassDecl), VBase.getType(), 4388 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4389 SourceRange(), DeclarationName(), nullptr); 4390 } 4391 4392 MarkFunctionReferenced(Location, Dtor); 4393 DiagnoseUseOfDecl(Dtor, Location); 4394 } 4395 } 4396 4397 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4398 if (!CDtorDecl) 4399 return; 4400 4401 if (CXXConstructorDecl *Constructor 4402 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 4403 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4404 DiagnoseUninitializedFields(*this, Constructor); 4405 } 4406 } 4407 4408 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4409 unsigned DiagID, AbstractDiagSelID SelID) { 4410 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4411 unsigned DiagID; 4412 AbstractDiagSelID SelID; 4413 4414 public: 4415 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4416 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4417 4418 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 4419 if (Suppressed) return; 4420 if (SelID == -1) 4421 S.Diag(Loc, DiagID) << T; 4422 else 4423 S.Diag(Loc, DiagID) << SelID << T; 4424 } 4425 } Diagnoser(DiagID, SelID); 4426 4427 return RequireNonAbstractType(Loc, T, Diagnoser); 4428 } 4429 4430 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4431 TypeDiagnoser &Diagnoser) { 4432 if (!getLangOpts().CPlusPlus) 4433 return false; 4434 4435 if (const ArrayType *AT = Context.getAsArrayType(T)) 4436 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4437 4438 if (const PointerType *PT = T->getAs<PointerType>()) { 4439 // Find the innermost pointer type. 4440 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4441 PT = T; 4442 4443 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4444 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4445 } 4446 4447 const RecordType *RT = T->getAs<RecordType>(); 4448 if (!RT) 4449 return false; 4450 4451 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4452 4453 // We can't answer whether something is abstract until it has a 4454 // definition. If it's currently being defined, we'll walk back 4455 // over all the declarations when we have a full definition. 4456 const CXXRecordDecl *Def = RD->getDefinition(); 4457 if (!Def || Def->isBeingDefined()) 4458 return false; 4459 4460 if (!RD->isAbstract()) 4461 return false; 4462 4463 Diagnoser.diagnose(*this, Loc, T); 4464 DiagnoseAbstractType(RD); 4465 4466 return true; 4467 } 4468 4469 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4470 // Check if we've already emitted the list of pure virtual functions 4471 // for this class. 4472 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4473 return; 4474 4475 // If the diagnostic is suppressed, don't emit the notes. We're only 4476 // going to emit them once, so try to attach them to a diagnostic we're 4477 // actually going to show. 4478 if (Diags.isLastDiagnosticIgnored()) 4479 return; 4480 4481 CXXFinalOverriderMap FinalOverriders; 4482 RD->getFinalOverriders(FinalOverriders); 4483 4484 // Keep a set of seen pure methods so we won't diagnose the same method 4485 // more than once. 4486 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4487 4488 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4489 MEnd = FinalOverriders.end(); 4490 M != MEnd; 4491 ++M) { 4492 for (OverridingMethods::iterator SO = M->second.begin(), 4493 SOEnd = M->second.end(); 4494 SO != SOEnd; ++SO) { 4495 // C++ [class.abstract]p4: 4496 // A class is abstract if it contains or inherits at least one 4497 // pure virtual function for which the final overrider is pure 4498 // virtual. 4499 4500 // 4501 if (SO->second.size() != 1) 4502 continue; 4503 4504 if (!SO->second.front().Method->isPure()) 4505 continue; 4506 4507 if (!SeenPureMethods.insert(SO->second.front().Method).second) 4508 continue; 4509 4510 Diag(SO->second.front().Method->getLocation(), 4511 diag::note_pure_virtual_function) 4512 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4513 } 4514 } 4515 4516 if (!PureVirtualClassDiagSet) 4517 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4518 PureVirtualClassDiagSet->insert(RD); 4519 } 4520 4521 namespace { 4522 struct AbstractUsageInfo { 4523 Sema &S; 4524 CXXRecordDecl *Record; 4525 CanQualType AbstractType; 4526 bool Invalid; 4527 4528 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4529 : S(S), Record(Record), 4530 AbstractType(S.Context.getCanonicalType( 4531 S.Context.getTypeDeclType(Record))), 4532 Invalid(false) {} 4533 4534 void DiagnoseAbstractType() { 4535 if (Invalid) return; 4536 S.DiagnoseAbstractType(Record); 4537 Invalid = true; 4538 } 4539 4540 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4541 }; 4542 4543 struct CheckAbstractUsage { 4544 AbstractUsageInfo &Info; 4545 const NamedDecl *Ctx; 4546 4547 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4548 : Info(Info), Ctx(Ctx) {} 4549 4550 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4551 switch (TL.getTypeLocClass()) { 4552 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4553 #define TYPELOC(CLASS, PARENT) \ 4554 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4555 #include "clang/AST/TypeLocNodes.def" 4556 } 4557 } 4558 4559 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4560 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 4561 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 4562 if (!TL.getParam(I)) 4563 continue; 4564 4565 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 4566 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4567 } 4568 } 4569 4570 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4571 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4572 } 4573 4574 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4575 // Visit the type parameters from a permissive context. 4576 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4577 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4578 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4579 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4580 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4581 // TODO: other template argument types? 4582 } 4583 } 4584 4585 // Visit pointee types from a permissive context. 4586 #define CheckPolymorphic(Type) \ 4587 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4588 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4589 } 4590 CheckPolymorphic(PointerTypeLoc) 4591 CheckPolymorphic(ReferenceTypeLoc) 4592 CheckPolymorphic(MemberPointerTypeLoc) 4593 CheckPolymorphic(BlockPointerTypeLoc) 4594 CheckPolymorphic(AtomicTypeLoc) 4595 4596 /// Handle all the types we haven't given a more specific 4597 /// implementation for above. 4598 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4599 // Every other kind of type that we haven't called out already 4600 // that has an inner type is either (1) sugar or (2) contains that 4601 // inner type in some way as a subobject. 4602 if (TypeLoc Next = TL.getNextTypeLoc()) 4603 return Visit(Next, Sel); 4604 4605 // If there's no inner type and we're in a permissive context, 4606 // don't diagnose. 4607 if (Sel == Sema::AbstractNone) return; 4608 4609 // Check whether the type matches the abstract type. 4610 QualType T = TL.getType(); 4611 if (T->isArrayType()) { 4612 Sel = Sema::AbstractArrayType; 4613 T = Info.S.Context.getBaseElementType(T); 4614 } 4615 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4616 if (CT != Info.AbstractType) return; 4617 4618 // It matched; do some magic. 4619 if (Sel == Sema::AbstractArrayType) { 4620 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4621 << T << TL.getSourceRange(); 4622 } else { 4623 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4624 << Sel << T << TL.getSourceRange(); 4625 } 4626 Info.DiagnoseAbstractType(); 4627 } 4628 }; 4629 4630 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4631 Sema::AbstractDiagSelID Sel) { 4632 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4633 } 4634 4635 } 4636 4637 /// Check for invalid uses of an abstract type in a method declaration. 4638 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4639 CXXMethodDecl *MD) { 4640 // No need to do the check on definitions, which require that 4641 // the return/param types be complete. 4642 if (MD->doesThisDeclarationHaveABody()) 4643 return; 4644 4645 // For safety's sake, just ignore it if we don't have type source 4646 // information. This should never happen for non-implicit methods, 4647 // but... 4648 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4649 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4650 } 4651 4652 /// Check for invalid uses of an abstract type within a class definition. 4653 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4654 CXXRecordDecl *RD) { 4655 for (auto *D : RD->decls()) { 4656 if (D->isImplicit()) continue; 4657 4658 // Methods and method templates. 4659 if (isa<CXXMethodDecl>(D)) { 4660 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4661 } else if (isa<FunctionTemplateDecl>(D)) { 4662 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4663 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4664 4665 // Fields and static variables. 4666 } else if (isa<FieldDecl>(D)) { 4667 FieldDecl *FD = cast<FieldDecl>(D); 4668 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4669 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4670 } else if (isa<VarDecl>(D)) { 4671 VarDecl *VD = cast<VarDecl>(D); 4672 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4673 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4674 4675 // Nested classes and class templates. 4676 } else if (isa<CXXRecordDecl>(D)) { 4677 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4678 } else if (isa<ClassTemplateDecl>(D)) { 4679 CheckAbstractClassUsage(Info, 4680 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4681 } 4682 } 4683 } 4684 4685 /// \brief Check class-level dllimport/dllexport attribute. 4686 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 4687 Attr *ClassAttr = getDLLAttr(Class); 4688 4689 // MSVC inherits DLL attributes to partial class template specializations. 4690 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 4691 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 4692 if (Attr *TemplateAttr = 4693 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 4694 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 4695 A->setInherited(true); 4696 ClassAttr = A; 4697 } 4698 } 4699 } 4700 4701 if (!ClassAttr) 4702 return; 4703 4704 if (!Class->isExternallyVisible()) { 4705 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 4706 << Class << ClassAttr; 4707 return; 4708 } 4709 4710 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 4711 !ClassAttr->isInherited()) { 4712 // Diagnose dll attributes on members of class with dll attribute. 4713 for (Decl *Member : Class->decls()) { 4714 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 4715 continue; 4716 InheritableAttr *MemberAttr = getDLLAttr(Member); 4717 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 4718 continue; 4719 4720 Diag(MemberAttr->getLocation(), 4721 diag::err_attribute_dll_member_of_dll_class) 4722 << MemberAttr << ClassAttr; 4723 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 4724 Member->setInvalidDecl(); 4725 } 4726 } 4727 4728 if (Class->getDescribedClassTemplate()) 4729 // Don't inherit dll attribute until the template is instantiated. 4730 return; 4731 4732 // The class is either imported or exported. 4733 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 4734 const bool ClassImported = !ClassExported; 4735 4736 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 4737 4738 // Ignore explicit dllexport on explicit class template instantiation declarations. 4739 if (ClassExported && !ClassAttr->isInherited() && 4740 TSK == TSK_ExplicitInstantiationDeclaration) { 4741 Class->dropAttr<DLLExportAttr>(); 4742 return; 4743 } 4744 4745 // Force declaration of implicit members so they can inherit the attribute. 4746 ForceDeclarationOfImplicitMembers(Class); 4747 4748 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 4749 // seem to be true in practice? 4750 4751 for (Decl *Member : Class->decls()) { 4752 VarDecl *VD = dyn_cast<VarDecl>(Member); 4753 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 4754 4755 // Only methods and static fields inherit the attributes. 4756 if (!VD && !MD) 4757 continue; 4758 4759 if (MD) { 4760 // Don't process deleted methods. 4761 if (MD->isDeleted()) 4762 continue; 4763 4764 if (MD->isInlined()) { 4765 // MinGW does not import or export inline methods. 4766 if (!Context.getTargetInfo().getCXXABI().isMicrosoft()) 4767 continue; 4768 4769 // MSVC versions before 2015 don't export the move assignment operators, 4770 // so don't attempt to import them if we have a definition. 4771 if (ClassImported && MD->isMoveAssignmentOperator() && 4772 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 4773 continue; 4774 } 4775 } 4776 4777 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 4778 continue; 4779 4780 if (!getDLLAttr(Member)) { 4781 auto *NewAttr = 4782 cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 4783 NewAttr->setInherited(true); 4784 Member->addAttr(NewAttr); 4785 } 4786 4787 if (MD && ClassExported) { 4788 if (TSK == TSK_ExplicitInstantiationDeclaration) 4789 // Don't go any further if this is just an explicit instantiation 4790 // declaration. 4791 continue; 4792 4793 if (MD->isUserProvided()) { 4794 // Instantiate non-default class member functions ... 4795 4796 // .. except for certain kinds of template specializations. 4797 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 4798 continue; 4799 4800 MarkFunctionReferenced(Class->getLocation(), MD); 4801 4802 // The function will be passed to the consumer when its definition is 4803 // encountered. 4804 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 4805 MD->isCopyAssignmentOperator() || 4806 MD->isMoveAssignmentOperator()) { 4807 // Synthesize and instantiate non-trivial implicit methods, explicitly 4808 // defaulted methods, and the copy and move assignment operators. The 4809 // latter are exported even if they are trivial, because the address of 4810 // an operator can be taken and should compare equal accross libraries. 4811 DiagnosticErrorTrap Trap(Diags); 4812 MarkFunctionReferenced(Class->getLocation(), MD); 4813 if (Trap.hasErrorOccurred()) { 4814 Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 4815 << Class->getName() << !getLangOpts().CPlusPlus11; 4816 break; 4817 } 4818 4819 // There is no later point when we will see the definition of this 4820 // function, so pass it to the consumer now. 4821 Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 4822 } 4823 } 4824 } 4825 } 4826 4827 /// \brief Perform propagation of DLL attributes from a derived class to a 4828 /// templated base class for MS compatibility. 4829 void Sema::propagateDLLAttrToBaseClassTemplate( 4830 CXXRecordDecl *Class, Attr *ClassAttr, 4831 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 4832 if (getDLLAttr( 4833 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 4834 // If the base class template has a DLL attribute, don't try to change it. 4835 return; 4836 } 4837 4838 auto TSK = BaseTemplateSpec->getSpecializationKind(); 4839 if (!getDLLAttr(BaseTemplateSpec) && 4840 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 4841 TSK == TSK_ImplicitInstantiation)) { 4842 // The template hasn't been instantiated yet (or it has, but only as an 4843 // explicit instantiation declaration or implicit instantiation, which means 4844 // we haven't codegenned any members yet), so propagate the attribute. 4845 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 4846 NewAttr->setInherited(true); 4847 BaseTemplateSpec->addAttr(NewAttr); 4848 4849 // If the template is already instantiated, checkDLLAttributeRedeclaration() 4850 // needs to be run again to work see the new attribute. Otherwise this will 4851 // get run whenever the template is instantiated. 4852 if (TSK != TSK_Undeclared) 4853 checkClassLevelDLLAttribute(BaseTemplateSpec); 4854 4855 return; 4856 } 4857 4858 if (getDLLAttr(BaseTemplateSpec)) { 4859 // The template has already been specialized or instantiated with an 4860 // attribute, explicitly or through propagation. We should not try to change 4861 // it. 4862 return; 4863 } 4864 4865 // The template was previously instantiated or explicitly specialized without 4866 // a dll attribute, It's too late for us to add an attribute, so warn that 4867 // this is unsupported. 4868 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 4869 << BaseTemplateSpec->isExplicitSpecialization(); 4870 Diag(ClassAttr->getLocation(), diag::note_attribute); 4871 if (BaseTemplateSpec->isExplicitSpecialization()) { 4872 Diag(BaseTemplateSpec->getLocation(), 4873 diag::note_template_class_explicit_specialization_was_here) 4874 << BaseTemplateSpec; 4875 } else { 4876 Diag(BaseTemplateSpec->getPointOfInstantiation(), 4877 diag::note_template_class_instantiation_was_here) 4878 << BaseTemplateSpec; 4879 } 4880 } 4881 4882 /// \brief Perform semantic checks on a class definition that has been 4883 /// completing, introducing implicitly-declared members, checking for 4884 /// abstract types, etc. 4885 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4886 if (!Record) 4887 return; 4888 4889 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4890 AbstractUsageInfo Info(*this, Record); 4891 CheckAbstractClassUsage(Info, Record); 4892 } 4893 4894 // If this is not an aggregate type and has no user-declared constructor, 4895 // complain about any non-static data members of reference or const scalar 4896 // type, since they will never get initializers. 4897 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4898 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4899 !Record->isLambda()) { 4900 bool Complained = false; 4901 for (const auto *F : Record->fields()) { 4902 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4903 continue; 4904 4905 if (F->getType()->isReferenceType() || 4906 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4907 if (!Complained) { 4908 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4909 << Record->getTagKind() << Record; 4910 Complained = true; 4911 } 4912 4913 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4914 << F->getType()->isReferenceType() 4915 << F->getDeclName(); 4916 } 4917 } 4918 } 4919 4920 if (Record->getIdentifier()) { 4921 // C++ [class.mem]p13: 4922 // If T is the name of a class, then each of the following shall have a 4923 // name different from T: 4924 // - every member of every anonymous union that is a member of class T. 4925 // 4926 // C++ [class.mem]p14: 4927 // In addition, if class T has a user-declared constructor (12.1), every 4928 // non-static data member of class T shall have a name different from T. 4929 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4930 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4931 ++I) { 4932 NamedDecl *D = *I; 4933 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4934 isa<IndirectFieldDecl>(D)) { 4935 Diag(D->getLocation(), diag::err_member_name_of_class) 4936 << D->getDeclName(); 4937 break; 4938 } 4939 } 4940 } 4941 4942 // Warn if the class has virtual methods but non-virtual public destructor. 4943 if (Record->isPolymorphic() && !Record->isDependentType()) { 4944 CXXDestructorDecl *dtor = Record->getDestructor(); 4945 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 4946 !Record->hasAttr<FinalAttr>()) 4947 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4948 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4949 } 4950 4951 if (Record->isAbstract()) { 4952 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4953 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4954 << FA->isSpelledAsSealed(); 4955 DiagnoseAbstractType(Record); 4956 } 4957 } 4958 4959 bool HasMethodWithOverrideControl = false, 4960 HasOverridingMethodWithoutOverrideControl = false; 4961 if (!Record->isDependentType()) { 4962 for (auto *M : Record->methods()) { 4963 // See if a method overloads virtual methods in a base 4964 // class without overriding any. 4965 if (!M->isStatic()) 4966 DiagnoseHiddenVirtualMethods(M); 4967 if (M->hasAttr<OverrideAttr>()) 4968 HasMethodWithOverrideControl = true; 4969 else if (M->size_overridden_methods() > 0) 4970 HasOverridingMethodWithoutOverrideControl = true; 4971 // Check whether the explicitly-defaulted special members are valid. 4972 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4973 CheckExplicitlyDefaultedSpecialMember(M); 4974 4975 // For an explicitly defaulted or deleted special member, we defer 4976 // determining triviality until the class is complete. That time is now! 4977 if (!M->isImplicit() && !M->isUserProvided()) { 4978 CXXSpecialMember CSM = getSpecialMember(M); 4979 if (CSM != CXXInvalid) { 4980 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 4981 4982 // Inform the class that we've finished declaring this member. 4983 Record->finishedDefaultedOrDeletedMember(M); 4984 } 4985 } 4986 } 4987 } 4988 4989 if (HasMethodWithOverrideControl && 4990 HasOverridingMethodWithoutOverrideControl) { 4991 // At least one method has the 'override' control declared. 4992 // Diagnose all other overridden methods which do not have 'override' specified on them. 4993 for (auto *M : Record->methods()) 4994 DiagnoseAbsenceOfOverrideControl(M); 4995 } 4996 4997 // ms_struct is a request to use the same ABI rules as MSVC. Check 4998 // whether this class uses any C++ features that are implemented 4999 // completely differently in MSVC, and if so, emit a diagnostic. 5000 // That diagnostic defaults to an error, but we allow projects to 5001 // map it down to a warning (or ignore it). It's a fairly common 5002 // practice among users of the ms_struct pragma to mass-annotate 5003 // headers, sweeping up a bunch of types that the project doesn't 5004 // really rely on MSVC-compatible layout for. We must therefore 5005 // support "ms_struct except for C++ stuff" as a secondary ABI. 5006 if (Record->isMsStruct(Context) && 5007 (Record->isPolymorphic() || Record->getNumBases())) { 5008 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 5009 } 5010 5011 // Declare inheriting constructors. We do this eagerly here because: 5012 // - The standard requires an eager diagnostic for conflicting inheriting 5013 // constructors from different classes. 5014 // - The lazy declaration of the other implicit constructors is so as to not 5015 // waste space and performance on classes that are not meant to be 5016 // instantiated (e.g. meta-functions). This doesn't apply to classes that 5017 // have inheriting constructors. 5018 DeclareInheritingConstructors(Record); 5019 5020 checkClassLevelDLLAttribute(Record); 5021 } 5022 5023 /// Look up the special member function that would be called by a special 5024 /// member function for a subobject of class type. 5025 /// 5026 /// \param Class The class type of the subobject. 5027 /// \param CSM The kind of special member function. 5028 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 5029 /// \param ConstRHS True if this is a copy operation with a const object 5030 /// on its RHS, that is, if the argument to the outer special member 5031 /// function is 'const' and this is not a field marked 'mutable'. 5032 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 5033 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 5034 unsigned FieldQuals, bool ConstRHS) { 5035 unsigned LHSQuals = 0; 5036 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 5037 LHSQuals = FieldQuals; 5038 5039 unsigned RHSQuals = FieldQuals; 5040 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 5041 RHSQuals = 0; 5042 else if (ConstRHS) 5043 RHSQuals |= Qualifiers::Const; 5044 5045 return S.LookupSpecialMember(Class, CSM, 5046 RHSQuals & Qualifiers::Const, 5047 RHSQuals & Qualifiers::Volatile, 5048 false, 5049 LHSQuals & Qualifiers::Const, 5050 LHSQuals & Qualifiers::Volatile); 5051 } 5052 5053 /// Is the special member function which would be selected to perform the 5054 /// specified operation on the specified class type a constexpr constructor? 5055 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 5056 Sema::CXXSpecialMember CSM, 5057 unsigned Quals, bool ConstRHS) { 5058 Sema::SpecialMemberOverloadResult *SMOR = 5059 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 5060 if (!SMOR || !SMOR->getMethod()) 5061 // A constructor we wouldn't select can't be "involved in initializing" 5062 // anything. 5063 return true; 5064 return SMOR->getMethod()->isConstexpr(); 5065 } 5066 5067 /// Determine whether the specified special member function would be constexpr 5068 /// if it were implicitly defined. 5069 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 5070 Sema::CXXSpecialMember CSM, 5071 bool ConstArg) { 5072 if (!S.getLangOpts().CPlusPlus11) 5073 return false; 5074 5075 // C++11 [dcl.constexpr]p4: 5076 // In the definition of a constexpr constructor [...] 5077 bool Ctor = true; 5078 switch (CSM) { 5079 case Sema::CXXDefaultConstructor: 5080 // Since default constructor lookup is essentially trivial (and cannot 5081 // involve, for instance, template instantiation), we compute whether a 5082 // defaulted default constructor is constexpr directly within CXXRecordDecl. 5083 // 5084 // This is important for performance; we need to know whether the default 5085 // constructor is constexpr to determine whether the type is a literal type. 5086 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 5087 5088 case Sema::CXXCopyConstructor: 5089 case Sema::CXXMoveConstructor: 5090 // For copy or move constructors, we need to perform overload resolution. 5091 break; 5092 5093 case Sema::CXXCopyAssignment: 5094 case Sema::CXXMoveAssignment: 5095 if (!S.getLangOpts().CPlusPlus14) 5096 return false; 5097 // In C++1y, we need to perform overload resolution. 5098 Ctor = false; 5099 break; 5100 5101 case Sema::CXXDestructor: 5102 case Sema::CXXInvalid: 5103 return false; 5104 } 5105 5106 // -- if the class is a non-empty union, or for each non-empty anonymous 5107 // union member of a non-union class, exactly one non-static data member 5108 // shall be initialized; [DR1359] 5109 // 5110 // If we squint, this is guaranteed, since exactly one non-static data member 5111 // will be initialized (if the constructor isn't deleted), we just don't know 5112 // which one. 5113 if (Ctor && ClassDecl->isUnion()) 5114 return true; 5115 5116 // -- the class shall not have any virtual base classes; 5117 if (Ctor && ClassDecl->getNumVBases()) 5118 return false; 5119 5120 // C++1y [class.copy]p26: 5121 // -- [the class] is a literal type, and 5122 if (!Ctor && !ClassDecl->isLiteral()) 5123 return false; 5124 5125 // -- every constructor involved in initializing [...] base class 5126 // sub-objects shall be a constexpr constructor; 5127 // -- the assignment operator selected to copy/move each direct base 5128 // class is a constexpr function, and 5129 for (const auto &B : ClassDecl->bases()) { 5130 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 5131 if (!BaseType) continue; 5132 5133 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 5134 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg)) 5135 return false; 5136 } 5137 5138 // -- every constructor involved in initializing non-static data members 5139 // [...] shall be a constexpr constructor; 5140 // -- every non-static data member and base class sub-object shall be 5141 // initialized 5142 // -- for each non-static data member of X that is of class type (or array 5143 // thereof), the assignment operator selected to copy/move that member is 5144 // a constexpr function 5145 for (const auto *F : ClassDecl->fields()) { 5146 if (F->isInvalidDecl()) 5147 continue; 5148 QualType BaseType = S.Context.getBaseElementType(F->getType()); 5149 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 5150 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 5151 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 5152 BaseType.getCVRQualifiers(), 5153 ConstArg && !F->isMutable())) 5154 return false; 5155 } 5156 } 5157 5158 // All OK, it's constexpr! 5159 return true; 5160 } 5161 5162 static Sema::ImplicitExceptionSpecification 5163 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 5164 switch (S.getSpecialMember(MD)) { 5165 case Sema::CXXDefaultConstructor: 5166 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 5167 case Sema::CXXCopyConstructor: 5168 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 5169 case Sema::CXXCopyAssignment: 5170 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 5171 case Sema::CXXMoveConstructor: 5172 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 5173 case Sema::CXXMoveAssignment: 5174 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 5175 case Sema::CXXDestructor: 5176 return S.ComputeDefaultedDtorExceptionSpec(MD); 5177 case Sema::CXXInvalid: 5178 break; 5179 } 5180 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 5181 "only special members have implicit exception specs"); 5182 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 5183 } 5184 5185 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 5186 CXXMethodDecl *MD) { 5187 FunctionProtoType::ExtProtoInfo EPI; 5188 5189 // Build an exception specification pointing back at this member. 5190 EPI.ExceptionSpec.Type = EST_Unevaluated; 5191 EPI.ExceptionSpec.SourceDecl = MD; 5192 5193 // Set the calling convention to the default for C++ instance methods. 5194 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 5195 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5196 /*IsCXXMethod=*/true)); 5197 return EPI; 5198 } 5199 5200 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 5201 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 5202 if (FPT->getExceptionSpecType() != EST_Unevaluated) 5203 return; 5204 5205 // Evaluate the exception specification. 5206 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec(); 5207 5208 // Update the type of the special member to use it. 5209 UpdateExceptionSpec(MD, ESI); 5210 5211 // A user-provided destructor can be defined outside the class. When that 5212 // happens, be sure to update the exception specification on both 5213 // declarations. 5214 const FunctionProtoType *CanonicalFPT = 5215 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 5216 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 5217 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 5218 } 5219 5220 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 5221 CXXRecordDecl *RD = MD->getParent(); 5222 CXXSpecialMember CSM = getSpecialMember(MD); 5223 5224 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 5225 "not an explicitly-defaulted special member"); 5226 5227 // Whether this was the first-declared instance of the constructor. 5228 // This affects whether we implicitly add an exception spec and constexpr. 5229 bool First = MD == MD->getCanonicalDecl(); 5230 5231 bool HadError = false; 5232 5233 // C++11 [dcl.fct.def.default]p1: 5234 // A function that is explicitly defaulted shall 5235 // -- be a special member function (checked elsewhere), 5236 // -- have the same type (except for ref-qualifiers, and except that a 5237 // copy operation can take a non-const reference) as an implicit 5238 // declaration, and 5239 // -- not have default arguments. 5240 unsigned ExpectedParams = 1; 5241 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 5242 ExpectedParams = 0; 5243 if (MD->getNumParams() != ExpectedParams) { 5244 // This also checks for default arguments: a copy or move constructor with a 5245 // default argument is classified as a default constructor, and assignment 5246 // operations and destructors can't have default arguments. 5247 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 5248 << CSM << MD->getSourceRange(); 5249 HadError = true; 5250 } else if (MD->isVariadic()) { 5251 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 5252 << CSM << MD->getSourceRange(); 5253 HadError = true; 5254 } 5255 5256 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 5257 5258 bool CanHaveConstParam = false; 5259 if (CSM == CXXCopyConstructor) 5260 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 5261 else if (CSM == CXXCopyAssignment) 5262 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 5263 5264 QualType ReturnType = Context.VoidTy; 5265 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 5266 // Check for return type matching. 5267 ReturnType = Type->getReturnType(); 5268 QualType ExpectedReturnType = 5269 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 5270 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 5271 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 5272 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 5273 HadError = true; 5274 } 5275 5276 // A defaulted special member cannot have cv-qualifiers. 5277 if (Type->getTypeQuals()) { 5278 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 5279 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 5280 HadError = true; 5281 } 5282 } 5283 5284 // Check for parameter type matching. 5285 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 5286 bool HasConstParam = false; 5287 if (ExpectedParams && ArgType->isReferenceType()) { 5288 // Argument must be reference to possibly-const T. 5289 QualType ReferentType = ArgType->getPointeeType(); 5290 HasConstParam = ReferentType.isConstQualified(); 5291 5292 if (ReferentType.isVolatileQualified()) { 5293 Diag(MD->getLocation(), 5294 diag::err_defaulted_special_member_volatile_param) << CSM; 5295 HadError = true; 5296 } 5297 5298 if (HasConstParam && !CanHaveConstParam) { 5299 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 5300 Diag(MD->getLocation(), 5301 diag::err_defaulted_special_member_copy_const_param) 5302 << (CSM == CXXCopyAssignment); 5303 // FIXME: Explain why this special member can't be const. 5304 } else { 5305 Diag(MD->getLocation(), 5306 diag::err_defaulted_special_member_move_const_param) 5307 << (CSM == CXXMoveAssignment); 5308 } 5309 HadError = true; 5310 } 5311 } else if (ExpectedParams) { 5312 // A copy assignment operator can take its argument by value, but a 5313 // defaulted one cannot. 5314 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 5315 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 5316 HadError = true; 5317 } 5318 5319 // C++11 [dcl.fct.def.default]p2: 5320 // An explicitly-defaulted function may be declared constexpr only if it 5321 // would have been implicitly declared as constexpr, 5322 // Do not apply this rule to members of class templates, since core issue 1358 5323 // makes such functions always instantiate to constexpr functions. For 5324 // functions which cannot be constexpr (for non-constructors in C++11 and for 5325 // destructors in C++1y), this is checked elsewhere. 5326 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 5327 HasConstParam); 5328 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 5329 : isa<CXXConstructorDecl>(MD)) && 5330 MD->isConstexpr() && !Constexpr && 5331 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 5332 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 5333 // FIXME: Explain why the special member can't be constexpr. 5334 HadError = true; 5335 } 5336 5337 // and may have an explicit exception-specification only if it is compatible 5338 // with the exception-specification on the implicit declaration. 5339 if (Type->hasExceptionSpec()) { 5340 // Delay the check if this is the first declaration of the special member, 5341 // since we may not have parsed some necessary in-class initializers yet. 5342 if (First) { 5343 // If the exception specification needs to be instantiated, do so now, 5344 // before we clobber it with an EST_Unevaluated specification below. 5345 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 5346 InstantiateExceptionSpec(MD->getLocStart(), MD); 5347 Type = MD->getType()->getAs<FunctionProtoType>(); 5348 } 5349 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 5350 } else 5351 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 5352 } 5353 5354 // If a function is explicitly defaulted on its first declaration, 5355 if (First) { 5356 // -- it is implicitly considered to be constexpr if the implicit 5357 // definition would be, 5358 MD->setConstexpr(Constexpr); 5359 5360 // -- it is implicitly considered to have the same exception-specification 5361 // as if it had been implicitly declared, 5362 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 5363 EPI.ExceptionSpec.Type = EST_Unevaluated; 5364 EPI.ExceptionSpec.SourceDecl = MD; 5365 MD->setType(Context.getFunctionType(ReturnType, 5366 llvm::makeArrayRef(&ArgType, 5367 ExpectedParams), 5368 EPI)); 5369 } 5370 5371 if (ShouldDeleteSpecialMember(MD, CSM)) { 5372 if (First) { 5373 SetDeclDeleted(MD, MD->getLocation()); 5374 } else { 5375 // C++11 [dcl.fct.def.default]p4: 5376 // [For a] user-provided explicitly-defaulted function [...] if such a 5377 // function is implicitly defined as deleted, the program is ill-formed. 5378 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 5379 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true); 5380 HadError = true; 5381 } 5382 } 5383 5384 if (HadError) 5385 MD->setInvalidDecl(); 5386 } 5387 5388 /// Check whether the exception specification provided for an 5389 /// explicitly-defaulted special member matches the exception specification 5390 /// that would have been generated for an implicit special member, per 5391 /// C++11 [dcl.fct.def.default]p2. 5392 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 5393 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 5394 // If the exception specification was explicitly specified but hadn't been 5395 // parsed when the method was defaulted, grab it now. 5396 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 5397 SpecifiedType = 5398 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 5399 5400 // Compute the implicit exception specification. 5401 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5402 /*IsCXXMethod=*/true); 5403 FunctionProtoType::ExtProtoInfo EPI(CC); 5404 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD) 5405 .getExceptionSpec(); 5406 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 5407 Context.getFunctionType(Context.VoidTy, None, EPI)); 5408 5409 // Ensure that it matches. 5410 CheckEquivalentExceptionSpec( 5411 PDiag(diag::err_incorrect_defaulted_exception_spec) 5412 << getSpecialMember(MD), PDiag(), 5413 ImplicitType, SourceLocation(), 5414 SpecifiedType, MD->getLocation()); 5415 } 5416 5417 void Sema::CheckDelayedMemberExceptionSpecs() { 5418 decltype(DelayedExceptionSpecChecks) Checks; 5419 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 5420 5421 std::swap(Checks, DelayedExceptionSpecChecks); 5422 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 5423 5424 // Perform any deferred checking of exception specifications for virtual 5425 // destructors. 5426 for (auto &Check : Checks) 5427 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 5428 5429 // Check that any explicitly-defaulted methods have exception specifications 5430 // compatible with their implicit exception specifications. 5431 for (auto &Spec : Specs) 5432 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 5433 } 5434 5435 namespace { 5436 struct SpecialMemberDeletionInfo { 5437 Sema &S; 5438 CXXMethodDecl *MD; 5439 Sema::CXXSpecialMember CSM; 5440 bool Diagnose; 5441 5442 // Properties of the special member, computed for convenience. 5443 bool IsConstructor, IsAssignment, IsMove, ConstArg; 5444 SourceLocation Loc; 5445 5446 bool AllFieldsAreConst; 5447 5448 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 5449 Sema::CXXSpecialMember CSM, bool Diagnose) 5450 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 5451 IsConstructor(false), IsAssignment(false), IsMove(false), 5452 ConstArg(false), Loc(MD->getLocation()), 5453 AllFieldsAreConst(true) { 5454 switch (CSM) { 5455 case Sema::CXXDefaultConstructor: 5456 case Sema::CXXCopyConstructor: 5457 IsConstructor = true; 5458 break; 5459 case Sema::CXXMoveConstructor: 5460 IsConstructor = true; 5461 IsMove = true; 5462 break; 5463 case Sema::CXXCopyAssignment: 5464 IsAssignment = true; 5465 break; 5466 case Sema::CXXMoveAssignment: 5467 IsAssignment = true; 5468 IsMove = true; 5469 break; 5470 case Sema::CXXDestructor: 5471 break; 5472 case Sema::CXXInvalid: 5473 llvm_unreachable("invalid special member kind"); 5474 } 5475 5476 if (MD->getNumParams()) { 5477 if (const ReferenceType *RT = 5478 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 5479 ConstArg = RT->getPointeeType().isConstQualified(); 5480 } 5481 } 5482 5483 bool inUnion() const { return MD->getParent()->isUnion(); } 5484 5485 /// Look up the corresponding special member in the given class. 5486 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 5487 unsigned Quals, bool IsMutable) { 5488 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 5489 ConstArg && !IsMutable); 5490 } 5491 5492 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 5493 5494 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 5495 bool shouldDeleteForField(FieldDecl *FD); 5496 bool shouldDeleteForAllConstMembers(); 5497 5498 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 5499 unsigned Quals); 5500 bool shouldDeleteForSubobjectCall(Subobject Subobj, 5501 Sema::SpecialMemberOverloadResult *SMOR, 5502 bool IsDtorCallInCtor); 5503 5504 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 5505 }; 5506 } 5507 5508 /// Is the given special member inaccessible when used on the given 5509 /// sub-object. 5510 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 5511 CXXMethodDecl *target) { 5512 /// If we're operating on a base class, the object type is the 5513 /// type of this special member. 5514 QualType objectTy; 5515 AccessSpecifier access = target->getAccess(); 5516 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 5517 objectTy = S.Context.getTypeDeclType(MD->getParent()); 5518 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 5519 5520 // If we're operating on a field, the object type is the type of the field. 5521 } else { 5522 objectTy = S.Context.getTypeDeclType(target->getParent()); 5523 } 5524 5525 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 5526 } 5527 5528 /// Check whether we should delete a special member due to the implicit 5529 /// definition containing a call to a special member of a subobject. 5530 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5531 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5532 bool IsDtorCallInCtor) { 5533 CXXMethodDecl *Decl = SMOR->getMethod(); 5534 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5535 5536 int DiagKind = -1; 5537 5538 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5539 DiagKind = !Decl ? 0 : 1; 5540 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5541 DiagKind = 2; 5542 else if (!isAccessible(Subobj, Decl)) 5543 DiagKind = 3; 5544 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5545 !Decl->isTrivial()) { 5546 // A member of a union must have a trivial corresponding special member. 5547 // As a weird special case, a destructor call from a union's constructor 5548 // must be accessible and non-deleted, but need not be trivial. Such a 5549 // destructor is never actually called, but is semantically checked as 5550 // if it were. 5551 DiagKind = 4; 5552 } 5553 5554 if (DiagKind == -1) 5555 return false; 5556 5557 if (Diagnose) { 5558 if (Field) { 5559 S.Diag(Field->getLocation(), 5560 diag::note_deleted_special_member_class_subobject) 5561 << CSM << MD->getParent() << /*IsField*/true 5562 << Field << DiagKind << IsDtorCallInCtor; 5563 } else { 5564 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5565 S.Diag(Base->getLocStart(), 5566 diag::note_deleted_special_member_class_subobject) 5567 << CSM << MD->getParent() << /*IsField*/false 5568 << Base->getType() << DiagKind << IsDtorCallInCtor; 5569 } 5570 5571 if (DiagKind == 1) 5572 S.NoteDeletedFunction(Decl); 5573 // FIXME: Explain inaccessibility if DiagKind == 3. 5574 } 5575 5576 return true; 5577 } 5578 5579 /// Check whether we should delete a special member function due to having a 5580 /// direct or virtual base class or non-static data member of class type M. 5581 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5582 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5583 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5584 bool IsMutable = Field && Field->isMutable(); 5585 5586 // C++11 [class.ctor]p5: 5587 // -- any direct or virtual base class, or non-static data member with no 5588 // brace-or-equal-initializer, has class type M (or array thereof) and 5589 // either M has no default constructor or overload resolution as applied 5590 // to M's default constructor results in an ambiguity or in a function 5591 // that is deleted or inaccessible 5592 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5593 // -- a direct or virtual base class B that cannot be copied/moved because 5594 // overload resolution, as applied to B's corresponding special member, 5595 // results in an ambiguity or a function that is deleted or inaccessible 5596 // from the defaulted special member 5597 // C++11 [class.dtor]p5: 5598 // -- any direct or virtual base class [...] has a type with a destructor 5599 // that is deleted or inaccessible 5600 if (!(CSM == Sema::CXXDefaultConstructor && 5601 Field && Field->hasInClassInitializer()) && 5602 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 5603 false)) 5604 return true; 5605 5606 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5607 // -- any direct or virtual base class or non-static data member has a 5608 // type with a destructor that is deleted or inaccessible 5609 if (IsConstructor) { 5610 Sema::SpecialMemberOverloadResult *SMOR = 5611 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5612 false, false, false, false, false); 5613 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5614 return true; 5615 } 5616 5617 return false; 5618 } 5619 5620 /// Check whether we should delete a special member function due to the class 5621 /// having a particular direct or virtual base class. 5622 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5623 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5624 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5625 } 5626 5627 /// Check whether we should delete a special member function due to the class 5628 /// having a particular non-static data member. 5629 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5630 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5631 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5632 5633 if (CSM == Sema::CXXDefaultConstructor) { 5634 // For a default constructor, all references must be initialized in-class 5635 // and, if a union, it must have a non-const member. 5636 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5637 if (Diagnose) 5638 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5639 << MD->getParent() << FD << FieldType << /*Reference*/0; 5640 return true; 5641 } 5642 // C++11 [class.ctor]p5: any non-variant non-static data member of 5643 // const-qualified type (or array thereof) with no 5644 // brace-or-equal-initializer does not have a user-provided default 5645 // constructor. 5646 if (!inUnion() && FieldType.isConstQualified() && 5647 !FD->hasInClassInitializer() && 5648 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5649 if (Diagnose) 5650 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5651 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5652 return true; 5653 } 5654 5655 if (inUnion() && !FieldType.isConstQualified()) 5656 AllFieldsAreConst = false; 5657 } else if (CSM == Sema::CXXCopyConstructor) { 5658 // For a copy constructor, data members must not be of rvalue reference 5659 // type. 5660 if (FieldType->isRValueReferenceType()) { 5661 if (Diagnose) 5662 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5663 << MD->getParent() << FD << FieldType; 5664 return true; 5665 } 5666 } else if (IsAssignment) { 5667 // For an assignment operator, data members must not be of reference type. 5668 if (FieldType->isReferenceType()) { 5669 if (Diagnose) 5670 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5671 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5672 return true; 5673 } 5674 if (!FieldRecord && FieldType.isConstQualified()) { 5675 // C++11 [class.copy]p23: 5676 // -- a non-static data member of const non-class type (or array thereof) 5677 if (Diagnose) 5678 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5679 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5680 return true; 5681 } 5682 } 5683 5684 if (FieldRecord) { 5685 // Some additional restrictions exist on the variant members. 5686 if (!inUnion() && FieldRecord->isUnion() && 5687 FieldRecord->isAnonymousStructOrUnion()) { 5688 bool AllVariantFieldsAreConst = true; 5689 5690 // FIXME: Handle anonymous unions declared within anonymous unions. 5691 for (auto *UI : FieldRecord->fields()) { 5692 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5693 5694 if (!UnionFieldType.isConstQualified()) 5695 AllVariantFieldsAreConst = false; 5696 5697 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5698 if (UnionFieldRecord && 5699 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 5700 UnionFieldType.getCVRQualifiers())) 5701 return true; 5702 } 5703 5704 // At least one member in each anonymous union must be non-const 5705 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5706 !FieldRecord->field_empty()) { 5707 if (Diagnose) 5708 S.Diag(FieldRecord->getLocation(), 5709 diag::note_deleted_default_ctor_all_const) 5710 << MD->getParent() << /*anonymous union*/1; 5711 return true; 5712 } 5713 5714 // Don't check the implicit member of the anonymous union type. 5715 // This is technically non-conformant, but sanity demands it. 5716 return false; 5717 } 5718 5719 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5720 FieldType.getCVRQualifiers())) 5721 return true; 5722 } 5723 5724 return false; 5725 } 5726 5727 /// C++11 [class.ctor] p5: 5728 /// A defaulted default constructor for a class X is defined as deleted if 5729 /// X is a union and all of its variant members are of const-qualified type. 5730 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5731 // This is a silly definition, because it gives an empty union a deleted 5732 // default constructor. Don't do that. 5733 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5734 !MD->getParent()->field_empty()) { 5735 if (Diagnose) 5736 S.Diag(MD->getParent()->getLocation(), 5737 diag::note_deleted_default_ctor_all_const) 5738 << MD->getParent() << /*not anonymous union*/0; 5739 return true; 5740 } 5741 return false; 5742 } 5743 5744 /// Determine whether a defaulted special member function should be defined as 5745 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5746 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5747 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5748 bool Diagnose) { 5749 if (MD->isInvalidDecl()) 5750 return false; 5751 CXXRecordDecl *RD = MD->getParent(); 5752 assert(!RD->isDependentType() && "do deletion after instantiation"); 5753 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5754 return false; 5755 5756 // C++11 [expr.lambda.prim]p19: 5757 // The closure type associated with a lambda-expression has a 5758 // deleted (8.4.3) default constructor and a deleted copy 5759 // assignment operator. 5760 if (RD->isLambda() && 5761 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5762 if (Diagnose) 5763 Diag(RD->getLocation(), diag::note_lambda_decl); 5764 return true; 5765 } 5766 5767 // For an anonymous struct or union, the copy and assignment special members 5768 // will never be used, so skip the check. For an anonymous union declared at 5769 // namespace scope, the constructor and destructor are used. 5770 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5771 RD->isAnonymousStructOrUnion()) 5772 return false; 5773 5774 // C++11 [class.copy]p7, p18: 5775 // If the class definition declares a move constructor or move assignment 5776 // operator, an implicitly declared copy constructor or copy assignment 5777 // operator is defined as deleted. 5778 if (MD->isImplicit() && 5779 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5780 CXXMethodDecl *UserDeclaredMove = nullptr; 5781 5782 // In Microsoft mode, a user-declared move only causes the deletion of the 5783 // corresponding copy operation, not both copy operations. 5784 if (RD->hasUserDeclaredMoveConstructor() && 5785 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 5786 if (!Diagnose) return true; 5787 5788 // Find any user-declared move constructor. 5789 for (auto *I : RD->ctors()) { 5790 if (I->isMoveConstructor()) { 5791 UserDeclaredMove = I; 5792 break; 5793 } 5794 } 5795 assert(UserDeclaredMove); 5796 } else if (RD->hasUserDeclaredMoveAssignment() && 5797 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 5798 if (!Diagnose) return true; 5799 5800 // Find any user-declared move assignment operator. 5801 for (auto *I : RD->methods()) { 5802 if (I->isMoveAssignmentOperator()) { 5803 UserDeclaredMove = I; 5804 break; 5805 } 5806 } 5807 assert(UserDeclaredMove); 5808 } 5809 5810 if (UserDeclaredMove) { 5811 Diag(UserDeclaredMove->getLocation(), 5812 diag::note_deleted_copy_user_declared_move) 5813 << (CSM == CXXCopyAssignment) << RD 5814 << UserDeclaredMove->isMoveAssignmentOperator(); 5815 return true; 5816 } 5817 } 5818 5819 // Do access control from the special member function 5820 ContextRAII MethodContext(*this, MD); 5821 5822 // C++11 [class.dtor]p5: 5823 // -- for a virtual destructor, lookup of the non-array deallocation function 5824 // results in an ambiguity or in a function that is deleted or inaccessible 5825 if (CSM == CXXDestructor && MD->isVirtual()) { 5826 FunctionDecl *OperatorDelete = nullptr; 5827 DeclarationName Name = 5828 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5829 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5830 OperatorDelete, false)) { 5831 if (Diagnose) 5832 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5833 return true; 5834 } 5835 } 5836 5837 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5838 5839 for (auto &BI : RD->bases()) 5840 if (!BI.isVirtual() && 5841 SMI.shouldDeleteForBase(&BI)) 5842 return true; 5843 5844 // Per DR1611, do not consider virtual bases of constructors of abstract 5845 // classes, since we are not going to construct them. 5846 if (!RD->isAbstract() || !SMI.IsConstructor) { 5847 for (auto &BI : RD->vbases()) 5848 if (SMI.shouldDeleteForBase(&BI)) 5849 return true; 5850 } 5851 5852 for (auto *FI : RD->fields()) 5853 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5854 SMI.shouldDeleteForField(FI)) 5855 return true; 5856 5857 if (SMI.shouldDeleteForAllConstMembers()) 5858 return true; 5859 5860 if (getLangOpts().CUDA) { 5861 // We should delete the special member in CUDA mode if target inference 5862 // failed. 5863 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 5864 Diagnose); 5865 } 5866 5867 return false; 5868 } 5869 5870 /// Perform lookup for a special member of the specified kind, and determine 5871 /// whether it is trivial. If the triviality can be determined without the 5872 /// lookup, skip it. This is intended for use when determining whether a 5873 /// special member of a containing object is trivial, and thus does not ever 5874 /// perform overload resolution for default constructors. 5875 /// 5876 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5877 /// member that was most likely to be intended to be trivial, if any. 5878 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5879 Sema::CXXSpecialMember CSM, unsigned Quals, 5880 bool ConstRHS, CXXMethodDecl **Selected) { 5881 if (Selected) 5882 *Selected = nullptr; 5883 5884 switch (CSM) { 5885 case Sema::CXXInvalid: 5886 llvm_unreachable("not a special member"); 5887 5888 case Sema::CXXDefaultConstructor: 5889 // C++11 [class.ctor]p5: 5890 // A default constructor is trivial if: 5891 // - all the [direct subobjects] have trivial default constructors 5892 // 5893 // Note, no overload resolution is performed in this case. 5894 if (RD->hasTrivialDefaultConstructor()) 5895 return true; 5896 5897 if (Selected) { 5898 // If there's a default constructor which could have been trivial, dig it 5899 // out. Otherwise, if there's any user-provided default constructor, point 5900 // to that as an example of why there's not a trivial one. 5901 CXXConstructorDecl *DefCtor = nullptr; 5902 if (RD->needsImplicitDefaultConstructor()) 5903 S.DeclareImplicitDefaultConstructor(RD); 5904 for (auto *CI : RD->ctors()) { 5905 if (!CI->isDefaultConstructor()) 5906 continue; 5907 DefCtor = CI; 5908 if (!DefCtor->isUserProvided()) 5909 break; 5910 } 5911 5912 *Selected = DefCtor; 5913 } 5914 5915 return false; 5916 5917 case Sema::CXXDestructor: 5918 // C++11 [class.dtor]p5: 5919 // A destructor is trivial if: 5920 // - all the direct [subobjects] have trivial destructors 5921 if (RD->hasTrivialDestructor()) 5922 return true; 5923 5924 if (Selected) { 5925 if (RD->needsImplicitDestructor()) 5926 S.DeclareImplicitDestructor(RD); 5927 *Selected = RD->getDestructor(); 5928 } 5929 5930 return false; 5931 5932 case Sema::CXXCopyConstructor: 5933 // C++11 [class.copy]p12: 5934 // A copy constructor is trivial if: 5935 // - the constructor selected to copy each direct [subobject] is trivial 5936 if (RD->hasTrivialCopyConstructor()) { 5937 if (Quals == Qualifiers::Const) 5938 // We must either select the trivial copy constructor or reach an 5939 // ambiguity; no need to actually perform overload resolution. 5940 return true; 5941 } else if (!Selected) { 5942 return false; 5943 } 5944 // In C++98, we are not supposed to perform overload resolution here, but we 5945 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5946 // cases like B as having a non-trivial copy constructor: 5947 // struct A { template<typename T> A(T&); }; 5948 // struct B { mutable A a; }; 5949 goto NeedOverloadResolution; 5950 5951 case Sema::CXXCopyAssignment: 5952 // C++11 [class.copy]p25: 5953 // A copy assignment operator is trivial if: 5954 // - the assignment operator selected to copy each direct [subobject] is 5955 // trivial 5956 if (RD->hasTrivialCopyAssignment()) { 5957 if (Quals == Qualifiers::Const) 5958 return true; 5959 } else if (!Selected) { 5960 return false; 5961 } 5962 // In C++98, we are not supposed to perform overload resolution here, but we 5963 // treat that as a language defect. 5964 goto NeedOverloadResolution; 5965 5966 case Sema::CXXMoveConstructor: 5967 case Sema::CXXMoveAssignment: 5968 NeedOverloadResolution: 5969 Sema::SpecialMemberOverloadResult *SMOR = 5970 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 5971 5972 // The standard doesn't describe how to behave if the lookup is ambiguous. 5973 // We treat it as not making the member non-trivial, just like the standard 5974 // mandates for the default constructor. This should rarely matter, because 5975 // the member will also be deleted. 5976 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5977 return true; 5978 5979 if (!SMOR->getMethod()) { 5980 assert(SMOR->getKind() == 5981 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5982 return false; 5983 } 5984 5985 // We deliberately don't check if we found a deleted special member. We're 5986 // not supposed to! 5987 if (Selected) 5988 *Selected = SMOR->getMethod(); 5989 return SMOR->getMethod()->isTrivial(); 5990 } 5991 5992 llvm_unreachable("unknown special method kind"); 5993 } 5994 5995 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5996 for (auto *CI : RD->ctors()) 5997 if (!CI->isImplicit()) 5998 return CI; 5999 6000 // Look for constructor templates. 6001 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 6002 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 6003 if (CXXConstructorDecl *CD = 6004 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 6005 return CD; 6006 } 6007 6008 return nullptr; 6009 } 6010 6011 /// The kind of subobject we are checking for triviality. The values of this 6012 /// enumeration are used in diagnostics. 6013 enum TrivialSubobjectKind { 6014 /// The subobject is a base class. 6015 TSK_BaseClass, 6016 /// The subobject is a non-static data member. 6017 TSK_Field, 6018 /// The object is actually the complete object. 6019 TSK_CompleteObject 6020 }; 6021 6022 /// Check whether the special member selected for a given type would be trivial. 6023 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 6024 QualType SubType, bool ConstRHS, 6025 Sema::CXXSpecialMember CSM, 6026 TrivialSubobjectKind Kind, 6027 bool Diagnose) { 6028 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 6029 if (!SubRD) 6030 return true; 6031 6032 CXXMethodDecl *Selected; 6033 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 6034 ConstRHS, Diagnose ? &Selected : nullptr)) 6035 return true; 6036 6037 if (Diagnose) { 6038 if (ConstRHS) 6039 SubType.addConst(); 6040 6041 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 6042 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 6043 << Kind << SubType.getUnqualifiedType(); 6044 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 6045 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 6046 } else if (!Selected) 6047 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 6048 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 6049 else if (Selected->isUserProvided()) { 6050 if (Kind == TSK_CompleteObject) 6051 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 6052 << Kind << SubType.getUnqualifiedType() << CSM; 6053 else { 6054 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 6055 << Kind << SubType.getUnqualifiedType() << CSM; 6056 S.Diag(Selected->getLocation(), diag::note_declared_at); 6057 } 6058 } else { 6059 if (Kind != TSK_CompleteObject) 6060 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 6061 << Kind << SubType.getUnqualifiedType() << CSM; 6062 6063 // Explain why the defaulted or deleted special member isn't trivial. 6064 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 6065 } 6066 } 6067 6068 return false; 6069 } 6070 6071 /// Check whether the members of a class type allow a special member to be 6072 /// trivial. 6073 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 6074 Sema::CXXSpecialMember CSM, 6075 bool ConstArg, bool Diagnose) { 6076 for (const auto *FI : RD->fields()) { 6077 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 6078 continue; 6079 6080 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 6081 6082 // Pretend anonymous struct or union members are members of this class. 6083 if (FI->isAnonymousStructOrUnion()) { 6084 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 6085 CSM, ConstArg, Diagnose)) 6086 return false; 6087 continue; 6088 } 6089 6090 // C++11 [class.ctor]p5: 6091 // A default constructor is trivial if [...] 6092 // -- no non-static data member of its class has a 6093 // brace-or-equal-initializer 6094 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 6095 if (Diagnose) 6096 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 6097 return false; 6098 } 6099 6100 // Objective C ARC 4.3.5: 6101 // [...] nontrivally ownership-qualified types are [...] not trivially 6102 // default constructible, copy constructible, move constructible, copy 6103 // assignable, move assignable, or destructible [...] 6104 if (S.getLangOpts().ObjCAutoRefCount && 6105 FieldType.hasNonTrivialObjCLifetime()) { 6106 if (Diagnose) 6107 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 6108 << RD << FieldType.getObjCLifetime(); 6109 return false; 6110 } 6111 6112 bool ConstRHS = ConstArg && !FI->isMutable(); 6113 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 6114 CSM, TSK_Field, Diagnose)) 6115 return false; 6116 } 6117 6118 return true; 6119 } 6120 6121 /// Diagnose why the specified class does not have a trivial special member of 6122 /// the given kind. 6123 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 6124 QualType Ty = Context.getRecordType(RD); 6125 6126 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 6127 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 6128 TSK_CompleteObject, /*Diagnose*/true); 6129 } 6130 6131 /// Determine whether a defaulted or deleted special member function is trivial, 6132 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 6133 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 6134 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 6135 bool Diagnose) { 6136 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 6137 6138 CXXRecordDecl *RD = MD->getParent(); 6139 6140 bool ConstArg = false; 6141 6142 // C++11 [class.copy]p12, p25: [DR1593] 6143 // A [special member] is trivial if [...] its parameter-type-list is 6144 // equivalent to the parameter-type-list of an implicit declaration [...] 6145 switch (CSM) { 6146 case CXXDefaultConstructor: 6147 case CXXDestructor: 6148 // Trivial default constructors and destructors cannot have parameters. 6149 break; 6150 6151 case CXXCopyConstructor: 6152 case CXXCopyAssignment: { 6153 // Trivial copy operations always have const, non-volatile parameter types. 6154 ConstArg = true; 6155 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6156 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 6157 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 6158 if (Diagnose) 6159 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6160 << Param0->getSourceRange() << Param0->getType() 6161 << Context.getLValueReferenceType( 6162 Context.getRecordType(RD).withConst()); 6163 return false; 6164 } 6165 break; 6166 } 6167 6168 case CXXMoveConstructor: 6169 case CXXMoveAssignment: { 6170 // Trivial move operations always have non-cv-qualified parameters. 6171 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6172 const RValueReferenceType *RT = 6173 Param0->getType()->getAs<RValueReferenceType>(); 6174 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 6175 if (Diagnose) 6176 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6177 << Param0->getSourceRange() << Param0->getType() 6178 << Context.getRValueReferenceType(Context.getRecordType(RD)); 6179 return false; 6180 } 6181 break; 6182 } 6183 6184 case CXXInvalid: 6185 llvm_unreachable("not a special member"); 6186 } 6187 6188 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 6189 if (Diagnose) 6190 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 6191 diag::note_nontrivial_default_arg) 6192 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 6193 return false; 6194 } 6195 if (MD->isVariadic()) { 6196 if (Diagnose) 6197 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 6198 return false; 6199 } 6200 6201 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6202 // A copy/move [constructor or assignment operator] is trivial if 6203 // -- the [member] selected to copy/move each direct base class subobject 6204 // is trivial 6205 // 6206 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6207 // A [default constructor or destructor] is trivial if 6208 // -- all the direct base classes have trivial [default constructors or 6209 // destructors] 6210 for (const auto &BI : RD->bases()) 6211 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 6212 ConstArg, CSM, TSK_BaseClass, Diagnose)) 6213 return false; 6214 6215 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6216 // A copy/move [constructor or assignment operator] for a class X is 6217 // trivial if 6218 // -- for each non-static data member of X that is of class type (or array 6219 // thereof), the constructor selected to copy/move that member is 6220 // trivial 6221 // 6222 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6223 // A [default constructor or destructor] is trivial if 6224 // -- for all of the non-static data members of its class that are of class 6225 // type (or array thereof), each such class has a trivial [default 6226 // constructor or destructor] 6227 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 6228 return false; 6229 6230 // C++11 [class.dtor]p5: 6231 // A destructor is trivial if [...] 6232 // -- the destructor is not virtual 6233 if (CSM == CXXDestructor && MD->isVirtual()) { 6234 if (Diagnose) 6235 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 6236 return false; 6237 } 6238 6239 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 6240 // A [special member] for class X is trivial if [...] 6241 // -- class X has no virtual functions and no virtual base classes 6242 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 6243 if (!Diagnose) 6244 return false; 6245 6246 if (RD->getNumVBases()) { 6247 // Check for virtual bases. We already know that the corresponding 6248 // member in all bases is trivial, so vbases must all be direct. 6249 CXXBaseSpecifier &BS = *RD->vbases_begin(); 6250 assert(BS.isVirtual()); 6251 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 6252 return false; 6253 } 6254 6255 // Must have a virtual method. 6256 for (const auto *MI : RD->methods()) { 6257 if (MI->isVirtual()) { 6258 SourceLocation MLoc = MI->getLocStart(); 6259 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 6260 return false; 6261 } 6262 } 6263 6264 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 6265 } 6266 6267 // Looks like it's trivial! 6268 return true; 6269 } 6270 6271 namespace { 6272 struct FindHiddenVirtualMethod { 6273 Sema *S; 6274 CXXMethodDecl *Method; 6275 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 6276 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6277 6278 private: 6279 /// Check whether any most overriden method from MD in Methods 6280 static bool CheckMostOverridenMethods( 6281 const CXXMethodDecl *MD, 6282 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 6283 if (MD->size_overridden_methods() == 0) 6284 return Methods.count(MD->getCanonicalDecl()); 6285 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6286 E = MD->end_overridden_methods(); 6287 I != E; ++I) 6288 if (CheckMostOverridenMethods(*I, Methods)) 6289 return true; 6290 return false; 6291 } 6292 6293 public: 6294 /// Member lookup function that determines whether a given C++ 6295 /// method overloads virtual methods in a base class without overriding any, 6296 /// to be used with CXXRecordDecl::lookupInBases(). 6297 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 6298 RecordDecl *BaseRecord = 6299 Specifier->getType()->getAs<RecordType>()->getDecl(); 6300 6301 DeclarationName Name = Method->getDeclName(); 6302 assert(Name.getNameKind() == DeclarationName::Identifier); 6303 6304 bool foundSameNameMethod = false; 6305 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 6306 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 6307 Path.Decls = Path.Decls.slice(1)) { 6308 NamedDecl *D = Path.Decls.front(); 6309 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6310 MD = MD->getCanonicalDecl(); 6311 foundSameNameMethod = true; 6312 // Interested only in hidden virtual methods. 6313 if (!MD->isVirtual()) 6314 continue; 6315 // If the method we are checking overrides a method from its base 6316 // don't warn about the other overloaded methods. Clang deviates from 6317 // GCC by only diagnosing overloads of inherited virtual functions that 6318 // do not override any other virtual functions in the base. GCC's 6319 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 6320 // function from a base class. These cases may be better served by a 6321 // warning (not specific to virtual functions) on call sites when the 6322 // call would select a different function from the base class, were it 6323 // visible. 6324 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 6325 if (!S->IsOverload(Method, MD, false)) 6326 return true; 6327 // Collect the overload only if its hidden. 6328 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 6329 overloadedMethods.push_back(MD); 6330 } 6331 } 6332 6333 if (foundSameNameMethod) 6334 OverloadedMethods.append(overloadedMethods.begin(), 6335 overloadedMethods.end()); 6336 return foundSameNameMethod; 6337 } 6338 }; 6339 } // end anonymous namespace 6340 6341 /// \brief Add the most overriden methods from MD to Methods 6342 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 6343 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6344 if (MD->size_overridden_methods() == 0) 6345 Methods.insert(MD->getCanonicalDecl()); 6346 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6347 E = MD->end_overridden_methods(); 6348 I != E; ++I) 6349 AddMostOverridenMethods(*I, Methods); 6350 } 6351 6352 /// \brief Check if a method overloads virtual methods in a base class without 6353 /// overriding any. 6354 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 6355 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6356 if (!MD->getDeclName().isIdentifier()) 6357 return; 6358 6359 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 6360 /*bool RecordPaths=*/false, 6361 /*bool DetectVirtual=*/false); 6362 FindHiddenVirtualMethod FHVM; 6363 FHVM.Method = MD; 6364 FHVM.S = this; 6365 6366 // Keep the base methods that were overriden or introduced in the subclass 6367 // by 'using' in a set. A base method not in this set is hidden. 6368 CXXRecordDecl *DC = MD->getParent(); 6369 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 6370 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 6371 NamedDecl *ND = *I; 6372 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 6373 ND = shad->getTargetDecl(); 6374 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6375 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 6376 } 6377 6378 if (DC->lookupInBases(FHVM, Paths)) 6379 OverloadedMethods = FHVM.OverloadedMethods; 6380 } 6381 6382 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 6383 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6384 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 6385 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 6386 PartialDiagnostic PD = PDiag( 6387 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 6388 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 6389 Diag(overloadedMD->getLocation(), PD); 6390 } 6391 } 6392 6393 /// \brief Diagnose methods which overload virtual methods in a base class 6394 /// without overriding any. 6395 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 6396 if (MD->isInvalidDecl()) 6397 return; 6398 6399 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 6400 return; 6401 6402 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6403 FindHiddenVirtualMethods(MD, OverloadedMethods); 6404 if (!OverloadedMethods.empty()) { 6405 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 6406 << MD << (OverloadedMethods.size() > 1); 6407 6408 NoteHiddenVirtualMethods(MD, OverloadedMethods); 6409 } 6410 } 6411 6412 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 6413 Decl *TagDecl, 6414 SourceLocation LBrac, 6415 SourceLocation RBrac, 6416 AttributeList *AttrList) { 6417 if (!TagDecl) 6418 return; 6419 6420 AdjustDeclIfTemplate(TagDecl); 6421 6422 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 6423 if (l->getKind() != AttributeList::AT_Visibility) 6424 continue; 6425 l->setInvalid(); 6426 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 6427 l->getName(); 6428 } 6429 6430 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 6431 // strict aliasing violation! 6432 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 6433 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 6434 6435 CheckCompletedCXXClass( 6436 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 6437 } 6438 6439 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 6440 /// special functions, such as the default constructor, copy 6441 /// constructor, or destructor, to the given C++ class (C++ 6442 /// [special]p1). This routine can only be executed just before the 6443 /// definition of the class is complete. 6444 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 6445 if (!ClassDecl->hasUserDeclaredConstructor()) 6446 ++ASTContext::NumImplicitDefaultConstructors; 6447 6448 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 6449 ++ASTContext::NumImplicitCopyConstructors; 6450 6451 // If the properties or semantics of the copy constructor couldn't be 6452 // determined while the class was being declared, force a declaration 6453 // of it now. 6454 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 6455 DeclareImplicitCopyConstructor(ClassDecl); 6456 } 6457 6458 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 6459 ++ASTContext::NumImplicitMoveConstructors; 6460 6461 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 6462 DeclareImplicitMoveConstructor(ClassDecl); 6463 } 6464 6465 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 6466 ++ASTContext::NumImplicitCopyAssignmentOperators; 6467 6468 // If we have a dynamic class, then the copy assignment operator may be 6469 // virtual, so we have to declare it immediately. This ensures that, e.g., 6470 // it shows up in the right place in the vtable and that we diagnose 6471 // problems with the implicit exception specification. 6472 if (ClassDecl->isDynamicClass() || 6473 ClassDecl->needsOverloadResolutionForCopyAssignment()) 6474 DeclareImplicitCopyAssignment(ClassDecl); 6475 } 6476 6477 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 6478 ++ASTContext::NumImplicitMoveAssignmentOperators; 6479 6480 // Likewise for the move assignment operator. 6481 if (ClassDecl->isDynamicClass() || 6482 ClassDecl->needsOverloadResolutionForMoveAssignment()) 6483 DeclareImplicitMoveAssignment(ClassDecl); 6484 } 6485 6486 if (!ClassDecl->hasUserDeclaredDestructor()) { 6487 ++ASTContext::NumImplicitDestructors; 6488 6489 // If we have a dynamic class, then the destructor may be virtual, so we 6490 // have to declare the destructor immediately. This ensures that, e.g., it 6491 // shows up in the right place in the vtable and that we diagnose problems 6492 // with the implicit exception specification. 6493 if (ClassDecl->isDynamicClass() || 6494 ClassDecl->needsOverloadResolutionForDestructor()) 6495 DeclareImplicitDestructor(ClassDecl); 6496 } 6497 } 6498 6499 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 6500 if (!D) 6501 return 0; 6502 6503 // The order of template parameters is not important here. All names 6504 // get added to the same scope. 6505 SmallVector<TemplateParameterList *, 4> ParameterLists; 6506 6507 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 6508 D = TD->getTemplatedDecl(); 6509 6510 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6511 ParameterLists.push_back(PSD->getTemplateParameters()); 6512 6513 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 6514 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 6515 ParameterLists.push_back(DD->getTemplateParameterList(i)); 6516 6517 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6518 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 6519 ParameterLists.push_back(FTD->getTemplateParameters()); 6520 } 6521 } 6522 6523 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 6524 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 6525 ParameterLists.push_back(TD->getTemplateParameterList(i)); 6526 6527 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 6528 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 6529 ParameterLists.push_back(CTD->getTemplateParameters()); 6530 } 6531 } 6532 6533 unsigned Count = 0; 6534 for (TemplateParameterList *Params : ParameterLists) { 6535 if (Params->size() > 0) 6536 // Ignore explicit specializations; they don't contribute to the template 6537 // depth. 6538 ++Count; 6539 for (NamedDecl *Param : *Params) { 6540 if (Param->getDeclName()) { 6541 S->AddDecl(Param); 6542 IdResolver.AddDecl(Param); 6543 } 6544 } 6545 } 6546 6547 return Count; 6548 } 6549 6550 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6551 if (!RecordD) return; 6552 AdjustDeclIfTemplate(RecordD); 6553 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6554 PushDeclContext(S, Record); 6555 } 6556 6557 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6558 if (!RecordD) return; 6559 PopDeclContext(); 6560 } 6561 6562 /// This is used to implement the constant expression evaluation part of the 6563 /// attribute enable_if extension. There is nothing in standard C++ which would 6564 /// require reentering parameters. 6565 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 6566 if (!Param) 6567 return; 6568 6569 S->AddDecl(Param); 6570 if (Param->getDeclName()) 6571 IdResolver.AddDecl(Param); 6572 } 6573 6574 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 6575 /// parsing a top-level (non-nested) C++ class, and we are now 6576 /// parsing those parts of the given Method declaration that could 6577 /// not be parsed earlier (C++ [class.mem]p2), such as default 6578 /// arguments. This action should enter the scope of the given 6579 /// Method declaration as if we had just parsed the qualified method 6580 /// name. However, it should not bring the parameters into scope; 6581 /// that will be performed by ActOnDelayedCXXMethodParameter. 6582 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6583 } 6584 6585 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 6586 /// C++ method declaration. We're (re-)introducing the given 6587 /// function parameter into scope for use in parsing later parts of 6588 /// the method declaration. For example, we could see an 6589 /// ActOnParamDefaultArgument event for this parameter. 6590 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6591 if (!ParamD) 6592 return; 6593 6594 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6595 6596 // If this parameter has an unparsed default argument, clear it out 6597 // to make way for the parsed default argument. 6598 if (Param->hasUnparsedDefaultArg()) 6599 Param->setDefaultArg(nullptr); 6600 6601 S->AddDecl(Param); 6602 if (Param->getDeclName()) 6603 IdResolver.AddDecl(Param); 6604 } 6605 6606 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6607 /// processing the delayed method declaration for Method. The method 6608 /// declaration is now considered finished. There may be a separate 6609 /// ActOnStartOfFunctionDef action later (not necessarily 6610 /// immediately!) for this method, if it was also defined inside the 6611 /// class body. 6612 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6613 if (!MethodD) 6614 return; 6615 6616 AdjustDeclIfTemplate(MethodD); 6617 6618 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6619 6620 // Now that we have our default arguments, check the constructor 6621 // again. It could produce additional diagnostics or affect whether 6622 // the class has implicitly-declared destructors, among other 6623 // things. 6624 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6625 CheckConstructor(Constructor); 6626 6627 // Check the default arguments, which we may have added. 6628 if (!Method->isInvalidDecl()) 6629 CheckCXXDefaultArguments(Method); 6630 } 6631 6632 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6633 /// the well-formedness of the constructor declarator @p D with type @p 6634 /// R. If there are any errors in the declarator, this routine will 6635 /// emit diagnostics and set the invalid bit to true. In any case, the type 6636 /// will be updated to reflect a well-formed type for the constructor and 6637 /// returned. 6638 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6639 StorageClass &SC) { 6640 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6641 6642 // C++ [class.ctor]p3: 6643 // A constructor shall not be virtual (10.3) or static (9.4). A 6644 // constructor can be invoked for a const, volatile or const 6645 // volatile object. A constructor shall not be declared const, 6646 // volatile, or const volatile (9.3.2). 6647 if (isVirtual) { 6648 if (!D.isInvalidType()) 6649 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6650 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6651 << SourceRange(D.getIdentifierLoc()); 6652 D.setInvalidType(); 6653 } 6654 if (SC == SC_Static) { 6655 if (!D.isInvalidType()) 6656 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6657 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6658 << SourceRange(D.getIdentifierLoc()); 6659 D.setInvalidType(); 6660 SC = SC_None; 6661 } 6662 6663 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6664 diagnoseIgnoredQualifiers( 6665 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 6666 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 6667 D.getDeclSpec().getRestrictSpecLoc(), 6668 D.getDeclSpec().getAtomicSpecLoc()); 6669 D.setInvalidType(); 6670 } 6671 6672 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6673 if (FTI.TypeQuals != 0) { 6674 if (FTI.TypeQuals & Qualifiers::Const) 6675 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6676 << "const" << SourceRange(D.getIdentifierLoc()); 6677 if (FTI.TypeQuals & Qualifiers::Volatile) 6678 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6679 << "volatile" << SourceRange(D.getIdentifierLoc()); 6680 if (FTI.TypeQuals & Qualifiers::Restrict) 6681 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6682 << "restrict" << SourceRange(D.getIdentifierLoc()); 6683 D.setInvalidType(); 6684 } 6685 6686 // C++0x [class.ctor]p4: 6687 // A constructor shall not be declared with a ref-qualifier. 6688 if (FTI.hasRefQualifier()) { 6689 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6690 << FTI.RefQualifierIsLValueRef 6691 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6692 D.setInvalidType(); 6693 } 6694 6695 // Rebuild the function type "R" without any type qualifiers (in 6696 // case any of the errors above fired) and with "void" as the 6697 // return type, since constructors don't have return types. 6698 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6699 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 6700 return R; 6701 6702 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6703 EPI.TypeQuals = 0; 6704 EPI.RefQualifier = RQ_None; 6705 6706 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 6707 } 6708 6709 /// CheckConstructor - Checks a fully-formed constructor for 6710 /// well-formedness, issuing any diagnostics required. Returns true if 6711 /// the constructor declarator is invalid. 6712 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6713 CXXRecordDecl *ClassDecl 6714 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6715 if (!ClassDecl) 6716 return Constructor->setInvalidDecl(); 6717 6718 // C++ [class.copy]p3: 6719 // A declaration of a constructor for a class X is ill-formed if 6720 // its first parameter is of type (optionally cv-qualified) X and 6721 // either there are no other parameters or else all other 6722 // parameters have default arguments. 6723 if (!Constructor->isInvalidDecl() && 6724 ((Constructor->getNumParams() == 1) || 6725 (Constructor->getNumParams() > 1 && 6726 Constructor->getParamDecl(1)->hasDefaultArg())) && 6727 Constructor->getTemplateSpecializationKind() 6728 != TSK_ImplicitInstantiation) { 6729 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6730 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6731 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6732 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6733 const char *ConstRef 6734 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6735 : " const &"; 6736 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6737 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6738 6739 // FIXME: Rather that making the constructor invalid, we should endeavor 6740 // to fix the type. 6741 Constructor->setInvalidDecl(); 6742 } 6743 } 6744 } 6745 6746 /// CheckDestructor - Checks a fully-formed destructor definition for 6747 /// well-formedness, issuing any diagnostics required. Returns true 6748 /// on error. 6749 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6750 CXXRecordDecl *RD = Destructor->getParent(); 6751 6752 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6753 SourceLocation Loc; 6754 6755 if (!Destructor->isImplicit()) 6756 Loc = Destructor->getLocation(); 6757 else 6758 Loc = RD->getLocation(); 6759 6760 // If we have a virtual destructor, look up the deallocation function 6761 FunctionDecl *OperatorDelete = nullptr; 6762 DeclarationName Name = 6763 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6764 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6765 return true; 6766 // If there's no class-specific operator delete, look up the global 6767 // non-array delete. 6768 if (!OperatorDelete) 6769 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name); 6770 6771 MarkFunctionReferenced(Loc, OperatorDelete); 6772 6773 Destructor->setOperatorDelete(OperatorDelete); 6774 } 6775 6776 return false; 6777 } 6778 6779 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6780 /// the well-formednes of the destructor declarator @p D with type @p 6781 /// R. If there are any errors in the declarator, this routine will 6782 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6783 /// will be updated to reflect a well-formed type for the destructor and 6784 /// returned. 6785 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6786 StorageClass& SC) { 6787 // C++ [class.dtor]p1: 6788 // [...] A typedef-name that names a class is a class-name 6789 // (7.1.3); however, a typedef-name that names a class shall not 6790 // be used as the identifier in the declarator for a destructor 6791 // declaration. 6792 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6793 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6794 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6795 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6796 else if (const TemplateSpecializationType *TST = 6797 DeclaratorType->getAs<TemplateSpecializationType>()) 6798 if (TST->isTypeAlias()) 6799 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6800 << DeclaratorType << 1; 6801 6802 // C++ [class.dtor]p2: 6803 // A destructor is used to destroy objects of its class type. A 6804 // destructor takes no parameters, and no return type can be 6805 // specified for it (not even void). The address of a destructor 6806 // shall not be taken. A destructor shall not be static. A 6807 // destructor can be invoked for a const, volatile or const 6808 // volatile object. A destructor shall not be declared const, 6809 // volatile or const volatile (9.3.2). 6810 if (SC == SC_Static) { 6811 if (!D.isInvalidType()) 6812 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6813 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6814 << SourceRange(D.getIdentifierLoc()) 6815 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6816 6817 SC = SC_None; 6818 } 6819 if (!D.isInvalidType()) { 6820 // Destructors don't have return types, but the parser will 6821 // happily parse something like: 6822 // 6823 // class X { 6824 // float ~X(); 6825 // }; 6826 // 6827 // The return type will be eliminated later. 6828 if (D.getDeclSpec().hasTypeSpecifier()) 6829 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6830 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6831 << SourceRange(D.getIdentifierLoc()); 6832 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6833 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 6834 SourceLocation(), 6835 D.getDeclSpec().getConstSpecLoc(), 6836 D.getDeclSpec().getVolatileSpecLoc(), 6837 D.getDeclSpec().getRestrictSpecLoc(), 6838 D.getDeclSpec().getAtomicSpecLoc()); 6839 D.setInvalidType(); 6840 } 6841 } 6842 6843 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6844 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6845 if (FTI.TypeQuals & Qualifiers::Const) 6846 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6847 << "const" << SourceRange(D.getIdentifierLoc()); 6848 if (FTI.TypeQuals & Qualifiers::Volatile) 6849 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6850 << "volatile" << SourceRange(D.getIdentifierLoc()); 6851 if (FTI.TypeQuals & Qualifiers::Restrict) 6852 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6853 << "restrict" << SourceRange(D.getIdentifierLoc()); 6854 D.setInvalidType(); 6855 } 6856 6857 // C++0x [class.dtor]p2: 6858 // A destructor shall not be declared with a ref-qualifier. 6859 if (FTI.hasRefQualifier()) { 6860 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6861 << FTI.RefQualifierIsLValueRef 6862 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6863 D.setInvalidType(); 6864 } 6865 6866 // Make sure we don't have any parameters. 6867 if (FTIHasNonVoidParameters(FTI)) { 6868 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6869 6870 // Delete the parameters. 6871 FTI.freeParams(); 6872 D.setInvalidType(); 6873 } 6874 6875 // Make sure the destructor isn't variadic. 6876 if (FTI.isVariadic) { 6877 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6878 D.setInvalidType(); 6879 } 6880 6881 // Rebuild the function type "R" without any type qualifiers or 6882 // parameters (in case any of the errors above fired) and with 6883 // "void" as the return type, since destructors don't have return 6884 // types. 6885 if (!D.isInvalidType()) 6886 return R; 6887 6888 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6889 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6890 EPI.Variadic = false; 6891 EPI.TypeQuals = 0; 6892 EPI.RefQualifier = RQ_None; 6893 return Context.getFunctionType(Context.VoidTy, None, EPI); 6894 } 6895 6896 static void extendLeft(SourceRange &R, const SourceRange &Before) { 6897 if (Before.isInvalid()) 6898 return; 6899 R.setBegin(Before.getBegin()); 6900 if (R.getEnd().isInvalid()) 6901 R.setEnd(Before.getEnd()); 6902 } 6903 6904 static void extendRight(SourceRange &R, const SourceRange &After) { 6905 if (After.isInvalid()) 6906 return; 6907 if (R.getBegin().isInvalid()) 6908 R.setBegin(After.getBegin()); 6909 R.setEnd(After.getEnd()); 6910 } 6911 6912 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6913 /// well-formednes of the conversion function declarator @p D with 6914 /// type @p R. If there are any errors in the declarator, this routine 6915 /// will emit diagnostics and return true. Otherwise, it will return 6916 /// false. Either way, the type @p R will be updated to reflect a 6917 /// well-formed type for the conversion operator. 6918 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6919 StorageClass& SC) { 6920 // C++ [class.conv.fct]p1: 6921 // Neither parameter types nor return type can be specified. The 6922 // type of a conversion function (8.3.5) is "function taking no 6923 // parameter returning conversion-type-id." 6924 if (SC == SC_Static) { 6925 if (!D.isInvalidType()) 6926 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6927 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6928 << D.getName().getSourceRange(); 6929 D.setInvalidType(); 6930 SC = SC_None; 6931 } 6932 6933 TypeSourceInfo *ConvTSI = nullptr; 6934 QualType ConvType = 6935 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 6936 6937 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6938 // Conversion functions don't have return types, but the parser will 6939 // happily parse something like: 6940 // 6941 // class X { 6942 // float operator bool(); 6943 // }; 6944 // 6945 // The return type will be changed later anyway. 6946 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6947 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6948 << SourceRange(D.getIdentifierLoc()); 6949 D.setInvalidType(); 6950 } 6951 6952 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6953 6954 // Make sure we don't have any parameters. 6955 if (Proto->getNumParams() > 0) { 6956 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6957 6958 // Delete the parameters. 6959 D.getFunctionTypeInfo().freeParams(); 6960 D.setInvalidType(); 6961 } else if (Proto->isVariadic()) { 6962 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6963 D.setInvalidType(); 6964 } 6965 6966 // Diagnose "&operator bool()" and other such nonsense. This 6967 // is actually a gcc extension which we don't support. 6968 if (Proto->getReturnType() != ConvType) { 6969 bool NeedsTypedef = false; 6970 SourceRange Before, After; 6971 6972 // Walk the chunks and extract information on them for our diagnostic. 6973 bool PastFunctionChunk = false; 6974 for (auto &Chunk : D.type_objects()) { 6975 switch (Chunk.Kind) { 6976 case DeclaratorChunk::Function: 6977 if (!PastFunctionChunk) { 6978 if (Chunk.Fun.HasTrailingReturnType) { 6979 TypeSourceInfo *TRT = nullptr; 6980 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 6981 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 6982 } 6983 PastFunctionChunk = true; 6984 break; 6985 } 6986 // Fall through. 6987 case DeclaratorChunk::Array: 6988 NeedsTypedef = true; 6989 extendRight(After, Chunk.getSourceRange()); 6990 break; 6991 6992 case DeclaratorChunk::Pointer: 6993 case DeclaratorChunk::BlockPointer: 6994 case DeclaratorChunk::Reference: 6995 case DeclaratorChunk::MemberPointer: 6996 extendLeft(Before, Chunk.getSourceRange()); 6997 break; 6998 6999 case DeclaratorChunk::Paren: 7000 extendLeft(Before, Chunk.Loc); 7001 extendRight(After, Chunk.EndLoc); 7002 break; 7003 } 7004 } 7005 7006 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 7007 After.isValid() ? After.getBegin() : 7008 D.getIdentifierLoc(); 7009 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 7010 DB << Before << After; 7011 7012 if (!NeedsTypedef) { 7013 DB << /*don't need a typedef*/0; 7014 7015 // If we can provide a correct fix-it hint, do so. 7016 if (After.isInvalid() && ConvTSI) { 7017 SourceLocation InsertLoc = 7018 PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 7019 DB << FixItHint::CreateInsertion(InsertLoc, " ") 7020 << FixItHint::CreateInsertionFromRange( 7021 InsertLoc, CharSourceRange::getTokenRange(Before)) 7022 << FixItHint::CreateRemoval(Before); 7023 } 7024 } else if (!Proto->getReturnType()->isDependentType()) { 7025 DB << /*typedef*/1 << Proto->getReturnType(); 7026 } else if (getLangOpts().CPlusPlus11) { 7027 DB << /*alias template*/2 << Proto->getReturnType(); 7028 } else { 7029 DB << /*might not be fixable*/3; 7030 } 7031 7032 // Recover by incorporating the other type chunks into the result type. 7033 // Note, this does *not* change the name of the function. This is compatible 7034 // with the GCC extension: 7035 // struct S { &operator int(); } s; 7036 // int &r = s.operator int(); // ok in GCC 7037 // S::operator int&() {} // error in GCC, function name is 'operator int'. 7038 ConvType = Proto->getReturnType(); 7039 } 7040 7041 // C++ [class.conv.fct]p4: 7042 // The conversion-type-id shall not represent a function type nor 7043 // an array type. 7044 if (ConvType->isArrayType()) { 7045 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 7046 ConvType = Context.getPointerType(ConvType); 7047 D.setInvalidType(); 7048 } else if (ConvType->isFunctionType()) { 7049 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 7050 ConvType = Context.getPointerType(ConvType); 7051 D.setInvalidType(); 7052 } 7053 7054 // Rebuild the function type "R" without any parameters (in case any 7055 // of the errors above fired) and with the conversion type as the 7056 // return type. 7057 if (D.isInvalidType()) 7058 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 7059 7060 // C++0x explicit conversion operators. 7061 if (D.getDeclSpec().isExplicitSpecified()) 7062 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7063 getLangOpts().CPlusPlus11 ? 7064 diag::warn_cxx98_compat_explicit_conversion_functions : 7065 diag::ext_explicit_conversion_functions) 7066 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 7067 } 7068 7069 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 7070 /// the declaration of the given C++ conversion function. This routine 7071 /// is responsible for recording the conversion function in the C++ 7072 /// class, if possible. 7073 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 7074 assert(Conversion && "Expected to receive a conversion function declaration"); 7075 7076 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 7077 7078 // Make sure we aren't redeclaring the conversion function. 7079 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 7080 7081 // C++ [class.conv.fct]p1: 7082 // [...] A conversion function is never used to convert a 7083 // (possibly cv-qualified) object to the (possibly cv-qualified) 7084 // same object type (or a reference to it), to a (possibly 7085 // cv-qualified) base class of that type (or a reference to it), 7086 // or to (possibly cv-qualified) void. 7087 // FIXME: Suppress this warning if the conversion function ends up being a 7088 // virtual function that overrides a virtual function in a base class. 7089 QualType ClassType 7090 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7091 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 7092 ConvType = ConvTypeRef->getPointeeType(); 7093 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 7094 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 7095 /* Suppress diagnostics for instantiations. */; 7096 else if (ConvType->isRecordType()) { 7097 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 7098 if (ConvType == ClassType) 7099 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 7100 << ClassType; 7101 else if (IsDerivedFrom(ClassType, ConvType)) 7102 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 7103 << ClassType << ConvType; 7104 } else if (ConvType->isVoidType()) { 7105 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 7106 << ClassType << ConvType; 7107 } 7108 7109 if (FunctionTemplateDecl *ConversionTemplate 7110 = Conversion->getDescribedFunctionTemplate()) 7111 return ConversionTemplate; 7112 7113 return Conversion; 7114 } 7115 7116 //===----------------------------------------------------------------------===// 7117 // Namespace Handling 7118 //===----------------------------------------------------------------------===// 7119 7120 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 7121 /// reopened. 7122 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 7123 SourceLocation Loc, 7124 IdentifierInfo *II, bool *IsInline, 7125 NamespaceDecl *PrevNS) { 7126 assert(*IsInline != PrevNS->isInline()); 7127 7128 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 7129 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 7130 // inline namespaces, with the intention of bringing names into namespace std. 7131 // 7132 // We support this just well enough to get that case working; this is not 7133 // sufficient to support reopening namespaces as inline in general. 7134 if (*IsInline && II && II->getName().startswith("__atomic") && 7135 S.getSourceManager().isInSystemHeader(Loc)) { 7136 // Mark all prior declarations of the namespace as inline. 7137 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 7138 NS = NS->getPreviousDecl()) 7139 NS->setInline(*IsInline); 7140 // Patch up the lookup table for the containing namespace. This isn't really 7141 // correct, but it's good enough for this particular case. 7142 for (auto *I : PrevNS->decls()) 7143 if (auto *ND = dyn_cast<NamedDecl>(I)) 7144 PrevNS->getParent()->makeDeclVisibleInContext(ND); 7145 return; 7146 } 7147 7148 if (PrevNS->isInline()) 7149 // The user probably just forgot the 'inline', so suggest that it 7150 // be added back. 7151 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 7152 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 7153 else 7154 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline; 7155 7156 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 7157 *IsInline = PrevNS->isInline(); 7158 } 7159 7160 /// ActOnStartNamespaceDef - This is called at the start of a namespace 7161 /// definition. 7162 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 7163 SourceLocation InlineLoc, 7164 SourceLocation NamespaceLoc, 7165 SourceLocation IdentLoc, 7166 IdentifierInfo *II, 7167 SourceLocation LBrace, 7168 AttributeList *AttrList) { 7169 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 7170 // For anonymous namespace, take the location of the left brace. 7171 SourceLocation Loc = II ? IdentLoc : LBrace; 7172 bool IsInline = InlineLoc.isValid(); 7173 bool IsInvalid = false; 7174 bool IsStd = false; 7175 bool AddToKnown = false; 7176 Scope *DeclRegionScope = NamespcScope->getParent(); 7177 7178 NamespaceDecl *PrevNS = nullptr; 7179 if (II) { 7180 // C++ [namespace.def]p2: 7181 // The identifier in an original-namespace-definition shall not 7182 // have been previously defined in the declarative region in 7183 // which the original-namespace-definition appears. The 7184 // identifier in an original-namespace-definition is the name of 7185 // the namespace. Subsequently in that declarative region, it is 7186 // treated as an original-namespace-name. 7187 // 7188 // Since namespace names are unique in their scope, and we don't 7189 // look through using directives, just look for any ordinary names. 7190 7191 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 7192 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 7193 Decl::IDNS_Namespace; 7194 NamedDecl *PrevDecl = nullptr; 7195 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 7196 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 7197 ++I) { 7198 if ((*I)->getIdentifierNamespace() & IDNS) { 7199 PrevDecl = *I; 7200 break; 7201 } 7202 } 7203 7204 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 7205 7206 if (PrevNS) { 7207 // This is an extended namespace definition. 7208 if (IsInline != PrevNS->isInline()) 7209 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 7210 &IsInline, PrevNS); 7211 } else if (PrevDecl) { 7212 // This is an invalid name redefinition. 7213 Diag(Loc, diag::err_redefinition_different_kind) 7214 << II; 7215 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7216 IsInvalid = true; 7217 // Continue on to push Namespc as current DeclContext and return it. 7218 } else if (II->isStr("std") && 7219 CurContext->getRedeclContext()->isTranslationUnit()) { 7220 // This is the first "real" definition of the namespace "std", so update 7221 // our cache of the "std" namespace to point at this definition. 7222 PrevNS = getStdNamespace(); 7223 IsStd = true; 7224 AddToKnown = !IsInline; 7225 } else { 7226 // We've seen this namespace for the first time. 7227 AddToKnown = !IsInline; 7228 } 7229 } else { 7230 // Anonymous namespaces. 7231 7232 // Determine whether the parent already has an anonymous namespace. 7233 DeclContext *Parent = CurContext->getRedeclContext(); 7234 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7235 PrevNS = TU->getAnonymousNamespace(); 7236 } else { 7237 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 7238 PrevNS = ND->getAnonymousNamespace(); 7239 } 7240 7241 if (PrevNS && IsInline != PrevNS->isInline()) 7242 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 7243 &IsInline, PrevNS); 7244 } 7245 7246 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 7247 StartLoc, Loc, II, PrevNS); 7248 if (IsInvalid) 7249 Namespc->setInvalidDecl(); 7250 7251 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 7252 7253 // FIXME: Should we be merging attributes? 7254 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 7255 PushNamespaceVisibilityAttr(Attr, Loc); 7256 7257 if (IsStd) 7258 StdNamespace = Namespc; 7259 if (AddToKnown) 7260 KnownNamespaces[Namespc] = false; 7261 7262 if (II) { 7263 PushOnScopeChains(Namespc, DeclRegionScope); 7264 } else { 7265 // Link the anonymous namespace into its parent. 7266 DeclContext *Parent = CurContext->getRedeclContext(); 7267 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7268 TU->setAnonymousNamespace(Namespc); 7269 } else { 7270 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 7271 } 7272 7273 CurContext->addDecl(Namespc); 7274 7275 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 7276 // behaves as if it were replaced by 7277 // namespace unique { /* empty body */ } 7278 // using namespace unique; 7279 // namespace unique { namespace-body } 7280 // where all occurrences of 'unique' in a translation unit are 7281 // replaced by the same identifier and this identifier differs 7282 // from all other identifiers in the entire program. 7283 7284 // We just create the namespace with an empty name and then add an 7285 // implicit using declaration, just like the standard suggests. 7286 // 7287 // CodeGen enforces the "universally unique" aspect by giving all 7288 // declarations semantically contained within an anonymous 7289 // namespace internal linkage. 7290 7291 if (!PrevNS) { 7292 UsingDirectiveDecl* UD 7293 = UsingDirectiveDecl::Create(Context, Parent, 7294 /* 'using' */ LBrace, 7295 /* 'namespace' */ SourceLocation(), 7296 /* qualifier */ NestedNameSpecifierLoc(), 7297 /* identifier */ SourceLocation(), 7298 Namespc, 7299 /* Ancestor */ Parent); 7300 UD->setImplicit(); 7301 Parent->addDecl(UD); 7302 } 7303 } 7304 7305 ActOnDocumentableDecl(Namespc); 7306 7307 // Although we could have an invalid decl (i.e. the namespace name is a 7308 // redefinition), push it as current DeclContext and try to continue parsing. 7309 // FIXME: We should be able to push Namespc here, so that the each DeclContext 7310 // for the namespace has the declarations that showed up in that particular 7311 // namespace definition. 7312 PushDeclContext(NamespcScope, Namespc); 7313 return Namespc; 7314 } 7315 7316 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 7317 /// is a namespace alias, returns the namespace it points to. 7318 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 7319 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 7320 return AD->getNamespace(); 7321 return dyn_cast_or_null<NamespaceDecl>(D); 7322 } 7323 7324 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 7325 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 7326 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 7327 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 7328 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 7329 Namespc->setRBraceLoc(RBrace); 7330 PopDeclContext(); 7331 if (Namespc->hasAttr<VisibilityAttr>()) 7332 PopPragmaVisibility(true, RBrace); 7333 } 7334 7335 CXXRecordDecl *Sema::getStdBadAlloc() const { 7336 return cast_or_null<CXXRecordDecl>( 7337 StdBadAlloc.get(Context.getExternalSource())); 7338 } 7339 7340 NamespaceDecl *Sema::getStdNamespace() const { 7341 return cast_or_null<NamespaceDecl>( 7342 StdNamespace.get(Context.getExternalSource())); 7343 } 7344 7345 /// \brief Retrieve the special "std" namespace, which may require us to 7346 /// implicitly define the namespace. 7347 NamespaceDecl *Sema::getOrCreateStdNamespace() { 7348 if (!StdNamespace) { 7349 // The "std" namespace has not yet been defined, so build one implicitly. 7350 StdNamespace = NamespaceDecl::Create(Context, 7351 Context.getTranslationUnitDecl(), 7352 /*Inline=*/false, 7353 SourceLocation(), SourceLocation(), 7354 &PP.getIdentifierTable().get("std"), 7355 /*PrevDecl=*/nullptr); 7356 getStdNamespace()->setImplicit(true); 7357 } 7358 7359 return getStdNamespace(); 7360 } 7361 7362 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 7363 assert(getLangOpts().CPlusPlus && 7364 "Looking for std::initializer_list outside of C++."); 7365 7366 // We're looking for implicit instantiations of 7367 // template <typename E> class std::initializer_list. 7368 7369 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 7370 return false; 7371 7372 ClassTemplateDecl *Template = nullptr; 7373 const TemplateArgument *Arguments = nullptr; 7374 7375 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7376 7377 ClassTemplateSpecializationDecl *Specialization = 7378 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 7379 if (!Specialization) 7380 return false; 7381 7382 Template = Specialization->getSpecializedTemplate(); 7383 Arguments = Specialization->getTemplateArgs().data(); 7384 } else if (const TemplateSpecializationType *TST = 7385 Ty->getAs<TemplateSpecializationType>()) { 7386 Template = dyn_cast_or_null<ClassTemplateDecl>( 7387 TST->getTemplateName().getAsTemplateDecl()); 7388 Arguments = TST->getArgs(); 7389 } 7390 if (!Template) 7391 return false; 7392 7393 if (!StdInitializerList) { 7394 // Haven't recognized std::initializer_list yet, maybe this is it. 7395 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 7396 if (TemplateClass->getIdentifier() != 7397 &PP.getIdentifierTable().get("initializer_list") || 7398 !getStdNamespace()->InEnclosingNamespaceSetOf( 7399 TemplateClass->getDeclContext())) 7400 return false; 7401 // This is a template called std::initializer_list, but is it the right 7402 // template? 7403 TemplateParameterList *Params = Template->getTemplateParameters(); 7404 if (Params->getMinRequiredArguments() != 1) 7405 return false; 7406 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 7407 return false; 7408 7409 // It's the right template. 7410 StdInitializerList = Template; 7411 } 7412 7413 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 7414 return false; 7415 7416 // This is an instance of std::initializer_list. Find the argument type. 7417 if (Element) 7418 *Element = Arguments[0].getAsType(); 7419 return true; 7420 } 7421 7422 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 7423 NamespaceDecl *Std = S.getStdNamespace(); 7424 if (!Std) { 7425 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7426 return nullptr; 7427 } 7428 7429 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 7430 Loc, Sema::LookupOrdinaryName); 7431 if (!S.LookupQualifiedName(Result, Std)) { 7432 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7433 return nullptr; 7434 } 7435 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 7436 if (!Template) { 7437 Result.suppressDiagnostics(); 7438 // We found something weird. Complain about the first thing we found. 7439 NamedDecl *Found = *Result.begin(); 7440 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 7441 return nullptr; 7442 } 7443 7444 // We found some template called std::initializer_list. Now verify that it's 7445 // correct. 7446 TemplateParameterList *Params = Template->getTemplateParameters(); 7447 if (Params->getMinRequiredArguments() != 1 || 7448 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 7449 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 7450 return nullptr; 7451 } 7452 7453 return Template; 7454 } 7455 7456 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 7457 if (!StdInitializerList) { 7458 StdInitializerList = LookupStdInitializerList(*this, Loc); 7459 if (!StdInitializerList) 7460 return QualType(); 7461 } 7462 7463 TemplateArgumentListInfo Args(Loc, Loc); 7464 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 7465 Context.getTrivialTypeSourceInfo(Element, 7466 Loc))); 7467 return Context.getCanonicalType( 7468 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 7469 } 7470 7471 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 7472 // C++ [dcl.init.list]p2: 7473 // A constructor is an initializer-list constructor if its first parameter 7474 // is of type std::initializer_list<E> or reference to possibly cv-qualified 7475 // std::initializer_list<E> for some type E, and either there are no other 7476 // parameters or else all other parameters have default arguments. 7477 if (Ctor->getNumParams() < 1 || 7478 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 7479 return false; 7480 7481 QualType ArgType = Ctor->getParamDecl(0)->getType(); 7482 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 7483 ArgType = RT->getPointeeType().getUnqualifiedType(); 7484 7485 return isStdInitializerList(ArgType, nullptr); 7486 } 7487 7488 /// \brief Determine whether a using statement is in a context where it will be 7489 /// apply in all contexts. 7490 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 7491 switch (CurContext->getDeclKind()) { 7492 case Decl::TranslationUnit: 7493 return true; 7494 case Decl::LinkageSpec: 7495 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 7496 default: 7497 return false; 7498 } 7499 } 7500 7501 namespace { 7502 7503 // Callback to only accept typo corrections that are namespaces. 7504 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 7505 public: 7506 bool ValidateCandidate(const TypoCorrection &candidate) override { 7507 if (NamedDecl *ND = candidate.getCorrectionDecl()) 7508 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 7509 return false; 7510 } 7511 }; 7512 7513 } 7514 7515 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 7516 CXXScopeSpec &SS, 7517 SourceLocation IdentLoc, 7518 IdentifierInfo *Ident) { 7519 R.clear(); 7520 if (TypoCorrection Corrected = 7521 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 7522 llvm::make_unique<NamespaceValidatorCCC>(), 7523 Sema::CTK_ErrorRecovery)) { 7524 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 7525 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 7526 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 7527 Ident->getName().equals(CorrectedStr); 7528 S.diagnoseTypo(Corrected, 7529 S.PDiag(diag::err_using_directive_member_suggest) 7530 << Ident << DC << DroppedSpecifier << SS.getRange(), 7531 S.PDiag(diag::note_namespace_defined_here)); 7532 } else { 7533 S.diagnoseTypo(Corrected, 7534 S.PDiag(diag::err_using_directive_suggest) << Ident, 7535 S.PDiag(diag::note_namespace_defined_here)); 7536 } 7537 R.addDecl(Corrected.getCorrectionDecl()); 7538 return true; 7539 } 7540 return false; 7541 } 7542 7543 Decl *Sema::ActOnUsingDirective(Scope *S, 7544 SourceLocation UsingLoc, 7545 SourceLocation NamespcLoc, 7546 CXXScopeSpec &SS, 7547 SourceLocation IdentLoc, 7548 IdentifierInfo *NamespcName, 7549 AttributeList *AttrList) { 7550 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7551 assert(NamespcName && "Invalid NamespcName."); 7552 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 7553 7554 // This can only happen along a recovery path. 7555 while (S->getFlags() & Scope::TemplateParamScope) 7556 S = S->getParent(); 7557 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7558 7559 UsingDirectiveDecl *UDir = nullptr; 7560 NestedNameSpecifier *Qualifier = nullptr; 7561 if (SS.isSet()) 7562 Qualifier = SS.getScopeRep(); 7563 7564 // Lookup namespace name. 7565 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 7566 LookupParsedName(R, S, &SS); 7567 if (R.isAmbiguous()) 7568 return nullptr; 7569 7570 if (R.empty()) { 7571 R.clear(); 7572 // Allow "using namespace std;" or "using namespace ::std;" even if 7573 // "std" hasn't been defined yet, for GCC compatibility. 7574 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 7575 NamespcName->isStr("std")) { 7576 Diag(IdentLoc, diag::ext_using_undefined_std); 7577 R.addDecl(getOrCreateStdNamespace()); 7578 R.resolveKind(); 7579 } 7580 // Otherwise, attempt typo correction. 7581 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 7582 } 7583 7584 if (!R.empty()) { 7585 NamedDecl *Named = R.getFoundDecl(); 7586 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 7587 && "expected namespace decl"); 7588 7589 // The use of a nested name specifier may trigger deprecation warnings. 7590 DiagnoseUseOfDecl(Named, IdentLoc); 7591 7592 // C++ [namespace.udir]p1: 7593 // A using-directive specifies that the names in the nominated 7594 // namespace can be used in the scope in which the 7595 // using-directive appears after the using-directive. During 7596 // unqualified name lookup (3.4.1), the names appear as if they 7597 // were declared in the nearest enclosing namespace which 7598 // contains both the using-directive and the nominated 7599 // namespace. [Note: in this context, "contains" means "contains 7600 // directly or indirectly". ] 7601 7602 // Find enclosing context containing both using-directive and 7603 // nominated namespace. 7604 NamespaceDecl *NS = getNamespaceDecl(Named); 7605 DeclContext *CommonAncestor = cast<DeclContext>(NS); 7606 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 7607 CommonAncestor = CommonAncestor->getParent(); 7608 7609 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 7610 SS.getWithLocInContext(Context), 7611 IdentLoc, Named, CommonAncestor); 7612 7613 if (IsUsingDirectiveInToplevelContext(CurContext) && 7614 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 7615 Diag(IdentLoc, diag::warn_using_directive_in_header); 7616 } 7617 7618 PushUsingDirective(S, UDir); 7619 } else { 7620 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7621 } 7622 7623 if (UDir) 7624 ProcessDeclAttributeList(S, UDir, AttrList); 7625 7626 return UDir; 7627 } 7628 7629 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 7630 // If the scope has an associated entity and the using directive is at 7631 // namespace or translation unit scope, add the UsingDirectiveDecl into 7632 // its lookup structure so qualified name lookup can find it. 7633 DeclContext *Ctx = S->getEntity(); 7634 if (Ctx && !Ctx->isFunctionOrMethod()) 7635 Ctx->addDecl(UDir); 7636 else 7637 // Otherwise, it is at block scope. The using-directives will affect lookup 7638 // only to the end of the scope. 7639 S->PushUsingDirective(UDir); 7640 } 7641 7642 7643 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7644 AccessSpecifier AS, 7645 bool HasUsingKeyword, 7646 SourceLocation UsingLoc, 7647 CXXScopeSpec &SS, 7648 UnqualifiedId &Name, 7649 AttributeList *AttrList, 7650 bool HasTypenameKeyword, 7651 SourceLocation TypenameLoc) { 7652 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7653 7654 switch (Name.getKind()) { 7655 case UnqualifiedId::IK_ImplicitSelfParam: 7656 case UnqualifiedId::IK_Identifier: 7657 case UnqualifiedId::IK_OperatorFunctionId: 7658 case UnqualifiedId::IK_LiteralOperatorId: 7659 case UnqualifiedId::IK_ConversionFunctionId: 7660 break; 7661 7662 case UnqualifiedId::IK_ConstructorName: 7663 case UnqualifiedId::IK_ConstructorTemplateId: 7664 // C++11 inheriting constructors. 7665 Diag(Name.getLocStart(), 7666 getLangOpts().CPlusPlus11 ? 7667 diag::warn_cxx98_compat_using_decl_constructor : 7668 diag::err_using_decl_constructor) 7669 << SS.getRange(); 7670 7671 if (getLangOpts().CPlusPlus11) break; 7672 7673 return nullptr; 7674 7675 case UnqualifiedId::IK_DestructorName: 7676 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7677 << SS.getRange(); 7678 return nullptr; 7679 7680 case UnqualifiedId::IK_TemplateId: 7681 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7682 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7683 return nullptr; 7684 } 7685 7686 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7687 DeclarationName TargetName = TargetNameInfo.getName(); 7688 if (!TargetName) 7689 return nullptr; 7690 7691 // Warn about access declarations. 7692 if (!HasUsingKeyword) { 7693 Diag(Name.getLocStart(), 7694 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7695 : diag::warn_access_decl_deprecated) 7696 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7697 } 7698 7699 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7700 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7701 return nullptr; 7702 7703 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7704 TargetNameInfo, AttrList, 7705 /* IsInstantiation */ false, 7706 HasTypenameKeyword, TypenameLoc); 7707 if (UD) 7708 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7709 7710 return UD; 7711 } 7712 7713 /// \brief Determine whether a using declaration considers the given 7714 /// declarations as "equivalent", e.g., if they are redeclarations of 7715 /// the same entity or are both typedefs of the same type. 7716 static bool 7717 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7718 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7719 return true; 7720 7721 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7722 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7723 return Context.hasSameType(TD1->getUnderlyingType(), 7724 TD2->getUnderlyingType()); 7725 7726 return false; 7727 } 7728 7729 7730 /// Determines whether to create a using shadow decl for a particular 7731 /// decl, given the set of decls existing prior to this using lookup. 7732 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7733 const LookupResult &Previous, 7734 UsingShadowDecl *&PrevShadow) { 7735 // Diagnose finding a decl which is not from a base class of the 7736 // current class. We do this now because there are cases where this 7737 // function will silently decide not to build a shadow decl, which 7738 // will pre-empt further diagnostics. 7739 // 7740 // We don't need to do this in C++0x because we do the check once on 7741 // the qualifier. 7742 // 7743 // FIXME: diagnose the following if we care enough: 7744 // struct A { int foo; }; 7745 // struct B : A { using A::foo; }; 7746 // template <class T> struct C : A {}; 7747 // template <class T> struct D : C<T> { using B::foo; } // <--- 7748 // This is invalid (during instantiation) in C++03 because B::foo 7749 // resolves to the using decl in B, which is not a base class of D<T>. 7750 // We can't diagnose it immediately because C<T> is an unknown 7751 // specialization. The UsingShadowDecl in D<T> then points directly 7752 // to A::foo, which will look well-formed when we instantiate. 7753 // The right solution is to not collapse the shadow-decl chain. 7754 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7755 DeclContext *OrigDC = Orig->getDeclContext(); 7756 7757 // Handle enums and anonymous structs. 7758 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7759 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7760 while (OrigRec->isAnonymousStructOrUnion()) 7761 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7762 7763 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7764 if (OrigDC == CurContext) { 7765 Diag(Using->getLocation(), 7766 diag::err_using_decl_nested_name_specifier_is_current_class) 7767 << Using->getQualifierLoc().getSourceRange(); 7768 Diag(Orig->getLocation(), diag::note_using_decl_target); 7769 return true; 7770 } 7771 7772 Diag(Using->getQualifierLoc().getBeginLoc(), 7773 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7774 << Using->getQualifier() 7775 << cast<CXXRecordDecl>(CurContext) 7776 << Using->getQualifierLoc().getSourceRange(); 7777 Diag(Orig->getLocation(), diag::note_using_decl_target); 7778 return true; 7779 } 7780 } 7781 7782 if (Previous.empty()) return false; 7783 7784 NamedDecl *Target = Orig; 7785 if (isa<UsingShadowDecl>(Target)) 7786 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7787 7788 // If the target happens to be one of the previous declarations, we 7789 // don't have a conflict. 7790 // 7791 // FIXME: but we might be increasing its access, in which case we 7792 // should redeclare it. 7793 NamedDecl *NonTag = nullptr, *Tag = nullptr; 7794 bool FoundEquivalentDecl = false; 7795 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7796 I != E; ++I) { 7797 NamedDecl *D = (*I)->getUnderlyingDecl(); 7798 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7799 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7800 PrevShadow = Shadow; 7801 FoundEquivalentDecl = true; 7802 } 7803 7804 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7805 } 7806 7807 if (FoundEquivalentDecl) 7808 return false; 7809 7810 if (FunctionDecl *FD = Target->getAsFunction()) { 7811 NamedDecl *OldDecl = nullptr; 7812 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 7813 /*IsForUsingDecl*/ true)) { 7814 case Ovl_Overload: 7815 return false; 7816 7817 case Ovl_NonFunction: 7818 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7819 break; 7820 7821 // We found a decl with the exact signature. 7822 case Ovl_Match: 7823 // If we're in a record, we want to hide the target, so we 7824 // return true (without a diagnostic) to tell the caller not to 7825 // build a shadow decl. 7826 if (CurContext->isRecord()) 7827 return true; 7828 7829 // If we're not in a record, this is an error. 7830 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7831 break; 7832 } 7833 7834 Diag(Target->getLocation(), diag::note_using_decl_target); 7835 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7836 return true; 7837 } 7838 7839 // Target is not a function. 7840 7841 if (isa<TagDecl>(Target)) { 7842 // No conflict between a tag and a non-tag. 7843 if (!Tag) return false; 7844 7845 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7846 Diag(Target->getLocation(), diag::note_using_decl_target); 7847 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7848 return true; 7849 } 7850 7851 // No conflict between a tag and a non-tag. 7852 if (!NonTag) return false; 7853 7854 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7855 Diag(Target->getLocation(), diag::note_using_decl_target); 7856 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7857 return true; 7858 } 7859 7860 /// Builds a shadow declaration corresponding to a 'using' declaration. 7861 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7862 UsingDecl *UD, 7863 NamedDecl *Orig, 7864 UsingShadowDecl *PrevDecl) { 7865 7866 // If we resolved to another shadow declaration, just coalesce them. 7867 NamedDecl *Target = Orig; 7868 if (isa<UsingShadowDecl>(Target)) { 7869 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7870 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7871 } 7872 7873 UsingShadowDecl *Shadow 7874 = UsingShadowDecl::Create(Context, CurContext, 7875 UD->getLocation(), UD, Target); 7876 UD->addShadowDecl(Shadow); 7877 7878 Shadow->setAccess(UD->getAccess()); 7879 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7880 Shadow->setInvalidDecl(); 7881 7882 Shadow->setPreviousDecl(PrevDecl); 7883 7884 if (S) 7885 PushOnScopeChains(Shadow, S); 7886 else 7887 CurContext->addDecl(Shadow); 7888 7889 7890 return Shadow; 7891 } 7892 7893 /// Hides a using shadow declaration. This is required by the current 7894 /// using-decl implementation when a resolvable using declaration in a 7895 /// class is followed by a declaration which would hide or override 7896 /// one or more of the using decl's targets; for example: 7897 /// 7898 /// struct Base { void foo(int); }; 7899 /// struct Derived : Base { 7900 /// using Base::foo; 7901 /// void foo(int); 7902 /// }; 7903 /// 7904 /// The governing language is C++03 [namespace.udecl]p12: 7905 /// 7906 /// When a using-declaration brings names from a base class into a 7907 /// derived class scope, member functions in the derived class 7908 /// override and/or hide member functions with the same name and 7909 /// parameter types in a base class (rather than conflicting). 7910 /// 7911 /// There are two ways to implement this: 7912 /// (1) optimistically create shadow decls when they're not hidden 7913 /// by existing declarations, or 7914 /// (2) don't create any shadow decls (or at least don't make them 7915 /// visible) until we've fully parsed/instantiated the class. 7916 /// The problem with (1) is that we might have to retroactively remove 7917 /// a shadow decl, which requires several O(n) operations because the 7918 /// decl structures are (very reasonably) not designed for removal. 7919 /// (2) avoids this but is very fiddly and phase-dependent. 7920 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7921 if (Shadow->getDeclName().getNameKind() == 7922 DeclarationName::CXXConversionFunctionName) 7923 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7924 7925 // Remove it from the DeclContext... 7926 Shadow->getDeclContext()->removeDecl(Shadow); 7927 7928 // ...and the scope, if applicable... 7929 if (S) { 7930 S->RemoveDecl(Shadow); 7931 IdResolver.RemoveDecl(Shadow); 7932 } 7933 7934 // ...and the using decl. 7935 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7936 7937 // TODO: complain somehow if Shadow was used. It shouldn't 7938 // be possible for this to happen, because...? 7939 } 7940 7941 /// Find the base specifier for a base class with the given type. 7942 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 7943 QualType DesiredBase, 7944 bool &AnyDependentBases) { 7945 // Check whether the named type is a direct base class. 7946 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 7947 for (auto &Base : Derived->bases()) { 7948 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 7949 if (CanonicalDesiredBase == BaseType) 7950 return &Base; 7951 if (BaseType->isDependentType()) 7952 AnyDependentBases = true; 7953 } 7954 return nullptr; 7955 } 7956 7957 namespace { 7958 class UsingValidatorCCC : public CorrectionCandidateCallback { 7959 public: 7960 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7961 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 7962 : HasTypenameKeyword(HasTypenameKeyword), 7963 IsInstantiation(IsInstantiation), OldNNS(NNS), 7964 RequireMemberOf(RequireMemberOf) {} 7965 7966 bool ValidateCandidate(const TypoCorrection &Candidate) override { 7967 NamedDecl *ND = Candidate.getCorrectionDecl(); 7968 7969 // Keywords are not valid here. 7970 if (!ND || isa<NamespaceDecl>(ND)) 7971 return false; 7972 7973 // Completely unqualified names are invalid for a 'using' declaration. 7974 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7975 return false; 7976 7977 if (RequireMemberOf) { 7978 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 7979 if (FoundRecord && FoundRecord->isInjectedClassName()) { 7980 // No-one ever wants a using-declaration to name an injected-class-name 7981 // of a base class, unless they're declaring an inheriting constructor. 7982 ASTContext &Ctx = ND->getASTContext(); 7983 if (!Ctx.getLangOpts().CPlusPlus11) 7984 return false; 7985 QualType FoundType = Ctx.getRecordType(FoundRecord); 7986 7987 // Check that the injected-class-name is named as a member of its own 7988 // type; we don't want to suggest 'using Derived::Base;', since that 7989 // means something else. 7990 NestedNameSpecifier *Specifier = 7991 Candidate.WillReplaceSpecifier() 7992 ? Candidate.getCorrectionSpecifier() 7993 : OldNNS; 7994 if (!Specifier->getAsType() || 7995 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 7996 return false; 7997 7998 // Check that this inheriting constructor declaration actually names a 7999 // direct base class of the current class. 8000 bool AnyDependentBases = false; 8001 if (!findDirectBaseWithType(RequireMemberOf, 8002 Ctx.getRecordType(FoundRecord), 8003 AnyDependentBases) && 8004 !AnyDependentBases) 8005 return false; 8006 } else { 8007 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 8008 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 8009 return false; 8010 8011 // FIXME: Check that the base class member is accessible? 8012 } 8013 } 8014 8015 if (isa<TypeDecl>(ND)) 8016 return HasTypenameKeyword || !IsInstantiation; 8017 8018 return !HasTypenameKeyword; 8019 } 8020 8021 private: 8022 bool HasTypenameKeyword; 8023 bool IsInstantiation; 8024 NestedNameSpecifier *OldNNS; 8025 CXXRecordDecl *RequireMemberOf; 8026 }; 8027 } // end anonymous namespace 8028 8029 /// Builds a using declaration. 8030 /// 8031 /// \param IsInstantiation - Whether this call arises from an 8032 /// instantiation of an unresolved using declaration. We treat 8033 /// the lookup differently for these declarations. 8034 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 8035 SourceLocation UsingLoc, 8036 CXXScopeSpec &SS, 8037 DeclarationNameInfo NameInfo, 8038 AttributeList *AttrList, 8039 bool IsInstantiation, 8040 bool HasTypenameKeyword, 8041 SourceLocation TypenameLoc) { 8042 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 8043 SourceLocation IdentLoc = NameInfo.getLoc(); 8044 assert(IdentLoc.isValid() && "Invalid TargetName location."); 8045 8046 // FIXME: We ignore attributes for now. 8047 8048 if (SS.isEmpty()) { 8049 Diag(IdentLoc, diag::err_using_requires_qualname); 8050 return nullptr; 8051 } 8052 8053 // Do the redeclaration lookup in the current scope. 8054 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 8055 ForRedeclaration); 8056 Previous.setHideTags(false); 8057 if (S) { 8058 LookupName(Previous, S); 8059 8060 // It is really dumb that we have to do this. 8061 LookupResult::Filter F = Previous.makeFilter(); 8062 while (F.hasNext()) { 8063 NamedDecl *D = F.next(); 8064 if (!isDeclInScope(D, CurContext, S)) 8065 F.erase(); 8066 // If we found a local extern declaration that's not ordinarily visible, 8067 // and this declaration is being added to a non-block scope, ignore it. 8068 // We're only checking for scope conflicts here, not also for violations 8069 // of the linkage rules. 8070 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 8071 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 8072 F.erase(); 8073 } 8074 F.done(); 8075 } else { 8076 assert(IsInstantiation && "no scope in non-instantiation"); 8077 assert(CurContext->isRecord() && "scope not record in instantiation"); 8078 LookupQualifiedName(Previous, CurContext); 8079 } 8080 8081 // Check for invalid redeclarations. 8082 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 8083 SS, IdentLoc, Previous)) 8084 return nullptr; 8085 8086 // Check for bad qualifiers. 8087 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 8088 return nullptr; 8089 8090 DeclContext *LookupContext = computeDeclContext(SS); 8091 NamedDecl *D; 8092 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 8093 if (!LookupContext) { 8094 if (HasTypenameKeyword) { 8095 // FIXME: not all declaration name kinds are legal here 8096 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 8097 UsingLoc, TypenameLoc, 8098 QualifierLoc, 8099 IdentLoc, NameInfo.getName()); 8100 } else { 8101 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 8102 QualifierLoc, NameInfo); 8103 } 8104 D->setAccess(AS); 8105 CurContext->addDecl(D); 8106 return D; 8107 } 8108 8109 auto Build = [&](bool Invalid) { 8110 UsingDecl *UD = 8111 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo, 8112 HasTypenameKeyword); 8113 UD->setAccess(AS); 8114 CurContext->addDecl(UD); 8115 UD->setInvalidDecl(Invalid); 8116 return UD; 8117 }; 8118 auto BuildInvalid = [&]{ return Build(true); }; 8119 auto BuildValid = [&]{ return Build(false); }; 8120 8121 if (RequireCompleteDeclContext(SS, LookupContext)) 8122 return BuildInvalid(); 8123 8124 // Look up the target name. 8125 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8126 8127 // Unlike most lookups, we don't always want to hide tag 8128 // declarations: tag names are visible through the using declaration 8129 // even if hidden by ordinary names, *except* in a dependent context 8130 // where it's important for the sanity of two-phase lookup. 8131 if (!IsInstantiation) 8132 R.setHideTags(false); 8133 8134 // For the purposes of this lookup, we have a base object type 8135 // equal to that of the current context. 8136 if (CurContext->isRecord()) { 8137 R.setBaseObjectType( 8138 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 8139 } 8140 8141 LookupQualifiedName(R, LookupContext); 8142 8143 // Try to correct typos if possible. If constructor name lookup finds no 8144 // results, that means the named class has no explicit constructors, and we 8145 // suppressed declaring implicit ones (probably because it's dependent or 8146 // invalid). 8147 if (R.empty() && 8148 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 8149 if (TypoCorrection Corrected = CorrectTypo( 8150 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 8151 llvm::make_unique<UsingValidatorCCC>( 8152 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 8153 dyn_cast<CXXRecordDecl>(CurContext)), 8154 CTK_ErrorRecovery)) { 8155 // We reject any correction for which ND would be NULL. 8156 NamedDecl *ND = Corrected.getCorrectionDecl(); 8157 8158 // We reject candidates where DroppedSpecifier == true, hence the 8159 // literal '0' below. 8160 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 8161 << NameInfo.getName() << LookupContext << 0 8162 << SS.getRange()); 8163 8164 // If we corrected to an inheriting constructor, handle it as one. 8165 auto *RD = dyn_cast<CXXRecordDecl>(ND); 8166 if (RD && RD->isInjectedClassName()) { 8167 // Fix up the information we'll use to build the using declaration. 8168 if (Corrected.WillReplaceSpecifier()) { 8169 NestedNameSpecifierLocBuilder Builder; 8170 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 8171 QualifierLoc.getSourceRange()); 8172 QualifierLoc = Builder.getWithLocInContext(Context); 8173 } 8174 8175 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 8176 Context.getCanonicalType(Context.getRecordType(RD)))); 8177 NameInfo.setNamedTypeInfo(nullptr); 8178 for (auto *Ctor : LookupConstructors(RD)) 8179 R.addDecl(Ctor); 8180 } else { 8181 // FIXME: Pick up all the declarations if we found an overloaded function. 8182 R.addDecl(ND); 8183 } 8184 } else { 8185 Diag(IdentLoc, diag::err_no_member) 8186 << NameInfo.getName() << LookupContext << SS.getRange(); 8187 return BuildInvalid(); 8188 } 8189 } 8190 8191 if (R.isAmbiguous()) 8192 return BuildInvalid(); 8193 8194 if (HasTypenameKeyword) { 8195 // If we asked for a typename and got a non-type decl, error out. 8196 if (!R.getAsSingle<TypeDecl>()) { 8197 Diag(IdentLoc, diag::err_using_typename_non_type); 8198 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 8199 Diag((*I)->getUnderlyingDecl()->getLocation(), 8200 diag::note_using_decl_target); 8201 return BuildInvalid(); 8202 } 8203 } else { 8204 // If we asked for a non-typename and we got a type, error out, 8205 // but only if this is an instantiation of an unresolved using 8206 // decl. Otherwise just silently find the type name. 8207 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 8208 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 8209 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 8210 return BuildInvalid(); 8211 } 8212 } 8213 8214 // C++0x N2914 [namespace.udecl]p6: 8215 // A using-declaration shall not name a namespace. 8216 if (R.getAsSingle<NamespaceDecl>()) { 8217 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 8218 << SS.getRange(); 8219 return BuildInvalid(); 8220 } 8221 8222 UsingDecl *UD = BuildValid(); 8223 8224 // The normal rules do not apply to inheriting constructor declarations. 8225 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 8226 // Suppress access diagnostics; the access check is instead performed at the 8227 // point of use for an inheriting constructor. 8228 R.suppressDiagnostics(); 8229 CheckInheritingConstructorUsingDecl(UD); 8230 return UD; 8231 } 8232 8233 // Otherwise, look up the target name. 8234 8235 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8236 UsingShadowDecl *PrevDecl = nullptr; 8237 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 8238 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 8239 } 8240 8241 return UD; 8242 } 8243 8244 /// Additional checks for a using declaration referring to a constructor name. 8245 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 8246 assert(!UD->hasTypename() && "expecting a constructor name"); 8247 8248 const Type *SourceType = UD->getQualifier()->getAsType(); 8249 assert(SourceType && 8250 "Using decl naming constructor doesn't have type in scope spec."); 8251 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 8252 8253 // Check whether the named type is a direct base class. 8254 bool AnyDependentBases = false; 8255 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 8256 AnyDependentBases); 8257 if (!Base && !AnyDependentBases) { 8258 Diag(UD->getUsingLoc(), 8259 diag::err_using_decl_constructor_not_in_direct_base) 8260 << UD->getNameInfo().getSourceRange() 8261 << QualType(SourceType, 0) << TargetClass; 8262 UD->setInvalidDecl(); 8263 return true; 8264 } 8265 8266 if (Base) 8267 Base->setInheritConstructors(); 8268 8269 return false; 8270 } 8271 8272 /// Checks that the given using declaration is not an invalid 8273 /// redeclaration. Note that this is checking only for the using decl 8274 /// itself, not for any ill-formedness among the UsingShadowDecls. 8275 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 8276 bool HasTypenameKeyword, 8277 const CXXScopeSpec &SS, 8278 SourceLocation NameLoc, 8279 const LookupResult &Prev) { 8280 // C++03 [namespace.udecl]p8: 8281 // C++0x [namespace.udecl]p10: 8282 // A using-declaration is a declaration and can therefore be used 8283 // repeatedly where (and only where) multiple declarations are 8284 // allowed. 8285 // 8286 // That's in non-member contexts. 8287 if (!CurContext->getRedeclContext()->isRecord()) 8288 return false; 8289 8290 NestedNameSpecifier *Qual = SS.getScopeRep(); 8291 8292 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 8293 NamedDecl *D = *I; 8294 8295 bool DTypename; 8296 NestedNameSpecifier *DQual; 8297 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 8298 DTypename = UD->hasTypename(); 8299 DQual = UD->getQualifier(); 8300 } else if (UnresolvedUsingValueDecl *UD 8301 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 8302 DTypename = false; 8303 DQual = UD->getQualifier(); 8304 } else if (UnresolvedUsingTypenameDecl *UD 8305 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 8306 DTypename = true; 8307 DQual = UD->getQualifier(); 8308 } else continue; 8309 8310 // using decls differ if one says 'typename' and the other doesn't. 8311 // FIXME: non-dependent using decls? 8312 if (HasTypenameKeyword != DTypename) continue; 8313 8314 // using decls differ if they name different scopes (but note that 8315 // template instantiation can cause this check to trigger when it 8316 // didn't before instantiation). 8317 if (Context.getCanonicalNestedNameSpecifier(Qual) != 8318 Context.getCanonicalNestedNameSpecifier(DQual)) 8319 continue; 8320 8321 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 8322 Diag(D->getLocation(), diag::note_using_decl) << 1; 8323 return true; 8324 } 8325 8326 return false; 8327 } 8328 8329 8330 /// Checks that the given nested-name qualifier used in a using decl 8331 /// in the current context is appropriately related to the current 8332 /// scope. If an error is found, diagnoses it and returns true. 8333 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 8334 const CXXScopeSpec &SS, 8335 const DeclarationNameInfo &NameInfo, 8336 SourceLocation NameLoc) { 8337 DeclContext *NamedContext = computeDeclContext(SS); 8338 8339 if (!CurContext->isRecord()) { 8340 // C++03 [namespace.udecl]p3: 8341 // C++0x [namespace.udecl]p8: 8342 // A using-declaration for a class member shall be a member-declaration. 8343 8344 // If we weren't able to compute a valid scope, it must be a 8345 // dependent class scope. 8346 if (!NamedContext || NamedContext->isRecord()) { 8347 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext); 8348 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 8349 RD = nullptr; 8350 8351 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 8352 << SS.getRange(); 8353 8354 // If we have a complete, non-dependent source type, try to suggest a 8355 // way to get the same effect. 8356 if (!RD) 8357 return true; 8358 8359 // Find what this using-declaration was referring to. 8360 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8361 R.setHideTags(false); 8362 R.suppressDiagnostics(); 8363 LookupQualifiedName(R, RD); 8364 8365 if (R.getAsSingle<TypeDecl>()) { 8366 if (getLangOpts().CPlusPlus11) { 8367 // Convert 'using X::Y;' to 'using Y = X::Y;'. 8368 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 8369 << 0 // alias declaration 8370 << FixItHint::CreateInsertion(SS.getBeginLoc(), 8371 NameInfo.getName().getAsString() + 8372 " = "); 8373 } else { 8374 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 8375 SourceLocation InsertLoc = 8376 PP.getLocForEndOfToken(NameInfo.getLocEnd()); 8377 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 8378 << 1 // typedef declaration 8379 << FixItHint::CreateReplacement(UsingLoc, "typedef") 8380 << FixItHint::CreateInsertion( 8381 InsertLoc, " " + NameInfo.getName().getAsString()); 8382 } 8383 } else if (R.getAsSingle<VarDecl>()) { 8384 // Don't provide a fixit outside C++11 mode; we don't want to suggest 8385 // repeating the type of the static data member here. 8386 FixItHint FixIt; 8387 if (getLangOpts().CPlusPlus11) { 8388 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 8389 FixIt = FixItHint::CreateReplacement( 8390 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 8391 } 8392 8393 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 8394 << 2 // reference declaration 8395 << FixIt; 8396 } 8397 return true; 8398 } 8399 8400 // Otherwise, everything is known to be fine. 8401 return false; 8402 } 8403 8404 // The current scope is a record. 8405 8406 // If the named context is dependent, we can't decide much. 8407 if (!NamedContext) { 8408 // FIXME: in C++0x, we can diagnose if we can prove that the 8409 // nested-name-specifier does not refer to a base class, which is 8410 // still possible in some cases. 8411 8412 // Otherwise we have to conservatively report that things might be 8413 // okay. 8414 return false; 8415 } 8416 8417 if (!NamedContext->isRecord()) { 8418 // Ideally this would point at the last name in the specifier, 8419 // but we don't have that level of source info. 8420 Diag(SS.getRange().getBegin(), 8421 diag::err_using_decl_nested_name_specifier_is_not_class) 8422 << SS.getScopeRep() << SS.getRange(); 8423 return true; 8424 } 8425 8426 if (!NamedContext->isDependentContext() && 8427 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 8428 return true; 8429 8430 if (getLangOpts().CPlusPlus11) { 8431 // C++0x [namespace.udecl]p3: 8432 // In a using-declaration used as a member-declaration, the 8433 // nested-name-specifier shall name a base class of the class 8434 // being defined. 8435 8436 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 8437 cast<CXXRecordDecl>(NamedContext))) { 8438 if (CurContext == NamedContext) { 8439 Diag(NameLoc, 8440 diag::err_using_decl_nested_name_specifier_is_current_class) 8441 << SS.getRange(); 8442 return true; 8443 } 8444 8445 Diag(SS.getRange().getBegin(), 8446 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8447 << SS.getScopeRep() 8448 << cast<CXXRecordDecl>(CurContext) 8449 << SS.getRange(); 8450 return true; 8451 } 8452 8453 return false; 8454 } 8455 8456 // C++03 [namespace.udecl]p4: 8457 // A using-declaration used as a member-declaration shall refer 8458 // to a member of a base class of the class being defined [etc.]. 8459 8460 // Salient point: SS doesn't have to name a base class as long as 8461 // lookup only finds members from base classes. Therefore we can 8462 // diagnose here only if we can prove that that can't happen, 8463 // i.e. if the class hierarchies provably don't intersect. 8464 8465 // TODO: it would be nice if "definitely valid" results were cached 8466 // in the UsingDecl and UsingShadowDecl so that these checks didn't 8467 // need to be repeated. 8468 8469 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 8470 auto Collect = [&Bases](const CXXRecordDecl *Base) { 8471 Bases.insert(Base); 8472 return true; 8473 }; 8474 8475 // Collect all bases. Return false if we find a dependent base. 8476 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 8477 return false; 8478 8479 // Returns true if the base is dependent or is one of the accumulated base 8480 // classes. 8481 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 8482 return !Bases.count(Base); 8483 }; 8484 8485 // Return false if the class has a dependent base or if it or one 8486 // of its bases is present in the base set of the current context. 8487 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 8488 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 8489 return false; 8490 8491 Diag(SS.getRange().getBegin(), 8492 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8493 << SS.getScopeRep() 8494 << cast<CXXRecordDecl>(CurContext) 8495 << SS.getRange(); 8496 8497 return true; 8498 } 8499 8500 Decl *Sema::ActOnAliasDeclaration(Scope *S, 8501 AccessSpecifier AS, 8502 MultiTemplateParamsArg TemplateParamLists, 8503 SourceLocation UsingLoc, 8504 UnqualifiedId &Name, 8505 AttributeList *AttrList, 8506 TypeResult Type, 8507 Decl *DeclFromDeclSpec) { 8508 // Skip up to the relevant declaration scope. 8509 while (S->getFlags() & Scope::TemplateParamScope) 8510 S = S->getParent(); 8511 assert((S->getFlags() & Scope::DeclScope) && 8512 "got alias-declaration outside of declaration scope"); 8513 8514 if (Type.isInvalid()) 8515 return nullptr; 8516 8517 bool Invalid = false; 8518 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 8519 TypeSourceInfo *TInfo = nullptr; 8520 GetTypeFromParser(Type.get(), &TInfo); 8521 8522 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 8523 return nullptr; 8524 8525 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 8526 UPPC_DeclarationType)) { 8527 Invalid = true; 8528 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 8529 TInfo->getTypeLoc().getBeginLoc()); 8530 } 8531 8532 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 8533 LookupName(Previous, S); 8534 8535 // Warn about shadowing the name of a template parameter. 8536 if (Previous.isSingleResult() && 8537 Previous.getFoundDecl()->isTemplateParameter()) { 8538 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 8539 Previous.clear(); 8540 } 8541 8542 assert(Name.Kind == UnqualifiedId::IK_Identifier && 8543 "name in alias declaration must be an identifier"); 8544 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 8545 Name.StartLocation, 8546 Name.Identifier, TInfo); 8547 8548 NewTD->setAccess(AS); 8549 8550 if (Invalid) 8551 NewTD->setInvalidDecl(); 8552 8553 ProcessDeclAttributeList(S, NewTD, AttrList); 8554 8555 CheckTypedefForVariablyModifiedType(S, NewTD); 8556 Invalid |= NewTD->isInvalidDecl(); 8557 8558 bool Redeclaration = false; 8559 8560 NamedDecl *NewND; 8561 if (TemplateParamLists.size()) { 8562 TypeAliasTemplateDecl *OldDecl = nullptr; 8563 TemplateParameterList *OldTemplateParams = nullptr; 8564 8565 if (TemplateParamLists.size() != 1) { 8566 Diag(UsingLoc, diag::err_alias_template_extra_headers) 8567 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 8568 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 8569 } 8570 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 8571 8572 // Only consider previous declarations in the same scope. 8573 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 8574 /*ExplicitInstantiationOrSpecialization*/false); 8575 if (!Previous.empty()) { 8576 Redeclaration = true; 8577 8578 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 8579 if (!OldDecl && !Invalid) { 8580 Diag(UsingLoc, diag::err_redefinition_different_kind) 8581 << Name.Identifier; 8582 8583 NamedDecl *OldD = Previous.getRepresentativeDecl(); 8584 if (OldD->getLocation().isValid()) 8585 Diag(OldD->getLocation(), diag::note_previous_definition); 8586 8587 Invalid = true; 8588 } 8589 8590 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 8591 if (TemplateParameterListsAreEqual(TemplateParams, 8592 OldDecl->getTemplateParameters(), 8593 /*Complain=*/true, 8594 TPL_TemplateMatch)) 8595 OldTemplateParams = OldDecl->getTemplateParameters(); 8596 else 8597 Invalid = true; 8598 8599 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 8600 if (!Invalid && 8601 !Context.hasSameType(OldTD->getUnderlyingType(), 8602 NewTD->getUnderlyingType())) { 8603 // FIXME: The C++0x standard does not clearly say this is ill-formed, 8604 // but we can't reasonably accept it. 8605 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 8606 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 8607 if (OldTD->getLocation().isValid()) 8608 Diag(OldTD->getLocation(), diag::note_previous_definition); 8609 Invalid = true; 8610 } 8611 } 8612 } 8613 8614 // Merge any previous default template arguments into our parameters, 8615 // and check the parameter list. 8616 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 8617 TPC_TypeAliasTemplate)) 8618 return nullptr; 8619 8620 TypeAliasTemplateDecl *NewDecl = 8621 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 8622 Name.Identifier, TemplateParams, 8623 NewTD); 8624 NewTD->setDescribedAliasTemplate(NewDecl); 8625 8626 NewDecl->setAccess(AS); 8627 8628 if (Invalid) 8629 NewDecl->setInvalidDecl(); 8630 else if (OldDecl) 8631 NewDecl->setPreviousDecl(OldDecl); 8632 8633 NewND = NewDecl; 8634 } else { 8635 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 8636 setTagNameForLinkagePurposes(TD, NewTD); 8637 handleTagNumbering(TD, S); 8638 } 8639 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 8640 NewND = NewTD; 8641 } 8642 8643 if (!Redeclaration) 8644 PushOnScopeChains(NewND, S); 8645 8646 ActOnDocumentableDecl(NewND); 8647 return NewND; 8648 } 8649 8650 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 8651 SourceLocation AliasLoc, 8652 IdentifierInfo *Alias, CXXScopeSpec &SS, 8653 SourceLocation IdentLoc, 8654 IdentifierInfo *Ident) { 8655 8656 // Lookup the namespace name. 8657 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 8658 LookupParsedName(R, S, &SS); 8659 8660 if (R.isAmbiguous()) 8661 return nullptr; 8662 8663 if (R.empty()) { 8664 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 8665 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8666 return nullptr; 8667 } 8668 } 8669 assert(!R.isAmbiguous() && !R.empty()); 8670 8671 // Check if we have a previous declaration with the same name. 8672 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 8673 ForRedeclaration); 8674 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 8675 PrevDecl = nullptr; 8676 8677 NamedDecl *ND = R.getFoundDecl(); 8678 8679 if (PrevDecl) { 8680 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 8681 // We already have an alias with the same name that points to the same 8682 // namespace; check that it matches. 8683 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 8684 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 8685 << Alias; 8686 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias) 8687 << AD->getNamespace(); 8688 return nullptr; 8689 } 8690 } else { 8691 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) 8692 ? diag::err_redefinition 8693 : diag::err_redefinition_different_kind; 8694 Diag(AliasLoc, DiagID) << Alias; 8695 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8696 return nullptr; 8697 } 8698 } 8699 8700 // The use of a nested name specifier may trigger deprecation warnings. 8701 DiagnoseUseOfDecl(ND, IdentLoc); 8702 8703 NamespaceAliasDecl *AliasDecl = 8704 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 8705 Alias, SS.getWithLocInContext(Context), 8706 IdentLoc, ND); 8707 if (PrevDecl) 8708 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl)); 8709 8710 PushOnScopeChains(AliasDecl, S); 8711 return AliasDecl; 8712 } 8713 8714 Sema::ImplicitExceptionSpecification 8715 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 8716 CXXMethodDecl *MD) { 8717 CXXRecordDecl *ClassDecl = MD->getParent(); 8718 8719 // C++ [except.spec]p14: 8720 // An implicitly declared special member function (Clause 12) shall have an 8721 // exception-specification. [...] 8722 ImplicitExceptionSpecification ExceptSpec(*this); 8723 if (ClassDecl->isInvalidDecl()) 8724 return ExceptSpec; 8725 8726 // Direct base-class constructors. 8727 for (const auto &B : ClassDecl->bases()) { 8728 if (B.isVirtual()) // Handled below. 8729 continue; 8730 8731 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8732 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8733 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8734 // If this is a deleted function, add it anyway. This might be conformant 8735 // with the standard. This might not. I'm not sure. It might not matter. 8736 if (Constructor) 8737 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8738 } 8739 } 8740 8741 // Virtual base-class constructors. 8742 for (const auto &B : ClassDecl->vbases()) { 8743 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8744 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8745 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8746 // If this is a deleted function, add it anyway. This might be conformant 8747 // with the standard. This might not. I'm not sure. It might not matter. 8748 if (Constructor) 8749 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8750 } 8751 } 8752 8753 // Field constructors. 8754 for (const auto *F : ClassDecl->fields()) { 8755 if (F->hasInClassInitializer()) { 8756 if (Expr *E = F->getInClassInitializer()) 8757 ExceptSpec.CalledExpr(E); 8758 } else if (const RecordType *RecordTy 8759 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8760 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8761 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8762 // If this is a deleted function, add it anyway. This might be conformant 8763 // with the standard. This might not. I'm not sure. It might not matter. 8764 // In particular, the problem is that this function never gets called. It 8765 // might just be ill-formed because this function attempts to refer to 8766 // a deleted function here. 8767 if (Constructor) 8768 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8769 } 8770 } 8771 8772 return ExceptSpec; 8773 } 8774 8775 Sema::ImplicitExceptionSpecification 8776 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8777 CXXRecordDecl *ClassDecl = CD->getParent(); 8778 8779 // C++ [except.spec]p14: 8780 // An inheriting constructor [...] shall have an exception-specification. [...] 8781 ImplicitExceptionSpecification ExceptSpec(*this); 8782 if (ClassDecl->isInvalidDecl()) 8783 return ExceptSpec; 8784 8785 // Inherited constructor. 8786 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8787 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8788 // FIXME: Copying or moving the parameters could add extra exceptions to the 8789 // set, as could the default arguments for the inherited constructor. This 8790 // will be addressed when we implement the resolution of core issue 1351. 8791 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8792 8793 // Direct base-class constructors. 8794 for (const auto &B : ClassDecl->bases()) { 8795 if (B.isVirtual()) // Handled below. 8796 continue; 8797 8798 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8799 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8800 if (BaseClassDecl == InheritedDecl) 8801 continue; 8802 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8803 if (Constructor) 8804 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8805 } 8806 } 8807 8808 // Virtual base-class constructors. 8809 for (const auto &B : ClassDecl->vbases()) { 8810 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8811 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8812 if (BaseClassDecl == InheritedDecl) 8813 continue; 8814 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8815 if (Constructor) 8816 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8817 } 8818 } 8819 8820 // Field constructors. 8821 for (const auto *F : ClassDecl->fields()) { 8822 if (F->hasInClassInitializer()) { 8823 if (Expr *E = F->getInClassInitializer()) 8824 ExceptSpec.CalledExpr(E); 8825 } else if (const RecordType *RecordTy 8826 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8827 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8828 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8829 if (Constructor) 8830 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8831 } 8832 } 8833 8834 return ExceptSpec; 8835 } 8836 8837 namespace { 8838 /// RAII object to register a special member as being currently declared. 8839 struct DeclaringSpecialMember { 8840 Sema &S; 8841 Sema::SpecialMemberDecl D; 8842 bool WasAlreadyBeingDeclared; 8843 8844 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8845 : S(S), D(RD, CSM) { 8846 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 8847 if (WasAlreadyBeingDeclared) 8848 // This almost never happens, but if it does, ensure that our cache 8849 // doesn't contain a stale result. 8850 S.SpecialMemberCache.clear(); 8851 8852 // FIXME: Register a note to be produced if we encounter an error while 8853 // declaring the special member. 8854 } 8855 ~DeclaringSpecialMember() { 8856 if (!WasAlreadyBeingDeclared) 8857 S.SpecialMembersBeingDeclared.erase(D); 8858 } 8859 8860 /// \brief Are we already trying to declare this special member? 8861 bool isAlreadyBeingDeclared() const { 8862 return WasAlreadyBeingDeclared; 8863 } 8864 }; 8865 } 8866 8867 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8868 CXXRecordDecl *ClassDecl) { 8869 // C++ [class.ctor]p5: 8870 // A default constructor for a class X is a constructor of class X 8871 // that can be called without an argument. If there is no 8872 // user-declared constructor for class X, a default constructor is 8873 // implicitly declared. An implicitly-declared default constructor 8874 // is an inline public member of its class. 8875 assert(ClassDecl->needsImplicitDefaultConstructor() && 8876 "Should not build implicit default constructor!"); 8877 8878 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8879 if (DSM.isAlreadyBeingDeclared()) 8880 return nullptr; 8881 8882 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8883 CXXDefaultConstructor, 8884 false); 8885 8886 // Create the actual constructor declaration. 8887 CanQualType ClassType 8888 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8889 SourceLocation ClassLoc = ClassDecl->getLocation(); 8890 DeclarationName Name 8891 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8892 DeclarationNameInfo NameInfo(Name, ClassLoc); 8893 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8894 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 8895 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 8896 /*isImplicitlyDeclared=*/true, Constexpr); 8897 DefaultCon->setAccess(AS_public); 8898 DefaultCon->setDefaulted(); 8899 8900 if (getLangOpts().CUDA) { 8901 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 8902 DefaultCon, 8903 /* ConstRHS */ false, 8904 /* Diagnose */ false); 8905 } 8906 8907 // Build an exception specification pointing back at this constructor. 8908 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8909 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8910 8911 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8912 // constructors is easy to compute. 8913 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8914 8915 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8916 SetDeclDeleted(DefaultCon, ClassLoc); 8917 8918 // Note that we have declared this constructor. 8919 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8920 8921 if (Scope *S = getScopeForContext(ClassDecl)) 8922 PushOnScopeChains(DefaultCon, S, false); 8923 ClassDecl->addDecl(DefaultCon); 8924 8925 return DefaultCon; 8926 } 8927 8928 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8929 CXXConstructorDecl *Constructor) { 8930 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8931 !Constructor->doesThisDeclarationHaveABody() && 8932 !Constructor->isDeleted()) && 8933 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8934 8935 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8936 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8937 8938 SynthesizedFunctionScope Scope(*this, Constructor); 8939 DiagnosticErrorTrap Trap(Diags); 8940 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8941 Trap.hasErrorOccurred()) { 8942 Diag(CurrentLocation, diag::note_member_synthesized_at) 8943 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8944 Constructor->setInvalidDecl(); 8945 return; 8946 } 8947 8948 // The exception specification is needed because we are defining the 8949 // function. 8950 ResolveExceptionSpec(CurrentLocation, 8951 Constructor->getType()->castAs<FunctionProtoType>()); 8952 8953 SourceLocation Loc = Constructor->getLocEnd().isValid() 8954 ? Constructor->getLocEnd() 8955 : Constructor->getLocation(); 8956 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8957 8958 Constructor->markUsed(Context); 8959 MarkVTableUsed(CurrentLocation, ClassDecl); 8960 8961 if (ASTMutationListener *L = getASTMutationListener()) { 8962 L->CompletedImplicitDefinition(Constructor); 8963 } 8964 8965 DiagnoseUninitializedFields(*this, Constructor); 8966 } 8967 8968 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8969 // Perform any delayed checks on exception specifications. 8970 CheckDelayedMemberExceptionSpecs(); 8971 } 8972 8973 namespace { 8974 /// Information on inheriting constructors to declare. 8975 class InheritingConstructorInfo { 8976 public: 8977 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8978 : SemaRef(SemaRef), Derived(Derived) { 8979 // Mark the constructors that we already have in the derived class. 8980 // 8981 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8982 // unless there is a user-declared constructor with the same signature in 8983 // the class where the using-declaration appears. 8984 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8985 } 8986 8987 void inheritAll(CXXRecordDecl *RD) { 8988 visitAll(RD, &InheritingConstructorInfo::inherit); 8989 } 8990 8991 private: 8992 /// Information about an inheriting constructor. 8993 struct InheritingConstructor { 8994 InheritingConstructor() 8995 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {} 8996 8997 /// If \c true, a constructor with this signature is already declared 8998 /// in the derived class. 8999 bool DeclaredInDerived; 9000 9001 /// The constructor which is inherited. 9002 const CXXConstructorDecl *BaseCtor; 9003 9004 /// The derived constructor we declared. 9005 CXXConstructorDecl *DerivedCtor; 9006 }; 9007 9008 /// Inheriting constructors with a given canonical type. There can be at 9009 /// most one such non-template constructor, and any number of templated 9010 /// constructors. 9011 struct InheritingConstructorsForType { 9012 InheritingConstructor NonTemplate; 9013 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 9014 Templates; 9015 9016 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 9017 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 9018 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 9019 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 9020 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 9021 false, S.TPL_TemplateMatch)) 9022 return Templates[I].second; 9023 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 9024 return Templates.back().second; 9025 } 9026 9027 return NonTemplate; 9028 } 9029 }; 9030 9031 /// Get or create the inheriting constructor record for a constructor. 9032 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 9033 QualType CtorType) { 9034 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 9035 .getEntry(SemaRef, Ctor); 9036 } 9037 9038 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 9039 9040 /// Process all constructors for a class. 9041 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 9042 for (const auto *Ctor : RD->ctors()) 9043 (this->*Callback)(Ctor); 9044 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 9045 I(RD->decls_begin()), E(RD->decls_end()); 9046 I != E; ++I) { 9047 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 9048 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 9049 (this->*Callback)(CD); 9050 } 9051 } 9052 9053 /// Note that a constructor (or constructor template) was declared in Derived. 9054 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 9055 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 9056 } 9057 9058 /// Inherit a single constructor. 9059 void inherit(const CXXConstructorDecl *Ctor) { 9060 const FunctionProtoType *CtorType = 9061 Ctor->getType()->castAs<FunctionProtoType>(); 9062 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes(); 9063 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 9064 9065 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 9066 9067 // Core issue (no number yet): the ellipsis is always discarded. 9068 if (EPI.Variadic) { 9069 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 9070 SemaRef.Diag(Ctor->getLocation(), 9071 diag::note_using_decl_constructor_ellipsis); 9072 EPI.Variadic = false; 9073 } 9074 9075 // Declare a constructor for each number of parameters. 9076 // 9077 // C++11 [class.inhctor]p1: 9078 // The candidate set of inherited constructors from the class X named in 9079 // the using-declaration consists of [... modulo defects ...] for each 9080 // constructor or constructor template of X, the set of constructors or 9081 // constructor templates that results from omitting any ellipsis parameter 9082 // specification and successively omitting parameters with a default 9083 // argument from the end of the parameter-type-list 9084 unsigned MinParams = minParamsToInherit(Ctor); 9085 unsigned Params = Ctor->getNumParams(); 9086 if (Params >= MinParams) { 9087 do 9088 declareCtor(UsingLoc, Ctor, 9089 SemaRef.Context.getFunctionType( 9090 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 9091 while (Params > MinParams && 9092 Ctor->getParamDecl(--Params)->hasDefaultArg()); 9093 } 9094 } 9095 9096 /// Find the using-declaration which specified that we should inherit the 9097 /// constructors of \p Base. 9098 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 9099 // No fancy lookup required; just look for the base constructor name 9100 // directly within the derived class. 9101 ASTContext &Context = SemaRef.Context; 9102 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 9103 Context.getCanonicalType(Context.getRecordType(Base))); 9104 DeclContext::lookup_result Decls = Derived->lookup(Name); 9105 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 9106 } 9107 9108 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 9109 // C++11 [class.inhctor]p3: 9110 // [F]or each constructor template in the candidate set of inherited 9111 // constructors, a constructor template is implicitly declared 9112 if (Ctor->getDescribedFunctionTemplate()) 9113 return 0; 9114 9115 // For each non-template constructor in the candidate set of inherited 9116 // constructors other than a constructor having no parameters or a 9117 // copy/move constructor having a single parameter, a constructor is 9118 // implicitly declared [...] 9119 if (Ctor->getNumParams() == 0) 9120 return 1; 9121 if (Ctor->isCopyOrMoveConstructor()) 9122 return 2; 9123 9124 // Per discussion on core reflector, never inherit a constructor which 9125 // would become a default, copy, or move constructor of Derived either. 9126 const ParmVarDecl *PD = Ctor->getParamDecl(0); 9127 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 9128 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 9129 } 9130 9131 /// Declare a single inheriting constructor, inheriting the specified 9132 /// constructor, with the given type. 9133 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 9134 QualType DerivedType) { 9135 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 9136 9137 // C++11 [class.inhctor]p3: 9138 // ... a constructor is implicitly declared with the same constructor 9139 // characteristics unless there is a user-declared constructor with 9140 // the same signature in the class where the using-declaration appears 9141 if (Entry.DeclaredInDerived) 9142 return; 9143 9144 // C++11 [class.inhctor]p7: 9145 // If two using-declarations declare inheriting constructors with the 9146 // same signature, the program is ill-formed 9147 if (Entry.DerivedCtor) { 9148 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 9149 // Only diagnose this once per constructor. 9150 if (Entry.DerivedCtor->isInvalidDecl()) 9151 return; 9152 Entry.DerivedCtor->setInvalidDecl(); 9153 9154 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 9155 SemaRef.Diag(BaseCtor->getLocation(), 9156 diag::note_using_decl_constructor_conflict_current_ctor); 9157 SemaRef.Diag(Entry.BaseCtor->getLocation(), 9158 diag::note_using_decl_constructor_conflict_previous_ctor); 9159 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 9160 diag::note_using_decl_constructor_conflict_previous_using); 9161 } else { 9162 // Core issue (no number): if the same inheriting constructor is 9163 // produced by multiple base class constructors from the same base 9164 // class, the inheriting constructor is defined as deleted. 9165 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 9166 } 9167 9168 return; 9169 } 9170 9171 ASTContext &Context = SemaRef.Context; 9172 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 9173 Context.getCanonicalType(Context.getRecordType(Derived))); 9174 DeclarationNameInfo NameInfo(Name, UsingLoc); 9175 9176 TemplateParameterList *TemplateParams = nullptr; 9177 if (const FunctionTemplateDecl *FTD = 9178 BaseCtor->getDescribedFunctionTemplate()) { 9179 TemplateParams = FTD->getTemplateParameters(); 9180 // We're reusing template parameters from a different DeclContext. This 9181 // is questionable at best, but works out because the template depth in 9182 // both places is guaranteed to be 0. 9183 // FIXME: Rebuild the template parameters in the new context, and 9184 // transform the function type to refer to them. 9185 } 9186 9187 // Build type source info pointing at the using-declaration. This is 9188 // required by template instantiation. 9189 TypeSourceInfo *TInfo = 9190 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 9191 FunctionProtoTypeLoc ProtoLoc = 9192 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 9193 9194 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 9195 Context, Derived, UsingLoc, NameInfo, DerivedType, 9196 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 9197 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 9198 9199 // Build an unevaluated exception specification for this constructor. 9200 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 9201 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9202 EPI.ExceptionSpec.Type = EST_Unevaluated; 9203 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 9204 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 9205 FPT->getParamTypes(), EPI)); 9206 9207 // Build the parameter declarations. 9208 SmallVector<ParmVarDecl *, 16> ParamDecls; 9209 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 9210 TypeSourceInfo *TInfo = 9211 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 9212 ParmVarDecl *PD = ParmVarDecl::Create( 9213 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 9214 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 9215 PD->setScopeInfo(0, I); 9216 PD->setImplicit(); 9217 ParamDecls.push_back(PD); 9218 ProtoLoc.setParam(I, PD); 9219 } 9220 9221 // Set up the new constructor. 9222 DerivedCtor->setAccess(BaseCtor->getAccess()); 9223 DerivedCtor->setParams(ParamDecls); 9224 DerivedCtor->setInheritedConstructor(BaseCtor); 9225 if (BaseCtor->isDeleted()) 9226 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 9227 9228 // If this is a constructor template, build the template declaration. 9229 if (TemplateParams) { 9230 FunctionTemplateDecl *DerivedTemplate = 9231 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 9232 TemplateParams, DerivedCtor); 9233 DerivedTemplate->setAccess(BaseCtor->getAccess()); 9234 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 9235 Derived->addDecl(DerivedTemplate); 9236 } else { 9237 Derived->addDecl(DerivedCtor); 9238 } 9239 9240 Entry.BaseCtor = BaseCtor; 9241 Entry.DerivedCtor = DerivedCtor; 9242 } 9243 9244 Sema &SemaRef; 9245 CXXRecordDecl *Derived; 9246 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 9247 MapType Map; 9248 }; 9249 } 9250 9251 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 9252 // Defer declaring the inheriting constructors until the class is 9253 // instantiated. 9254 if (ClassDecl->isDependentContext()) 9255 return; 9256 9257 // Find base classes from which we might inherit constructors. 9258 SmallVector<CXXRecordDecl*, 4> InheritedBases; 9259 for (const auto &BaseIt : ClassDecl->bases()) 9260 if (BaseIt.getInheritConstructors()) 9261 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl()); 9262 9263 // Go no further if we're not inheriting any constructors. 9264 if (InheritedBases.empty()) 9265 return; 9266 9267 // Declare the inherited constructors. 9268 InheritingConstructorInfo ICI(*this, ClassDecl); 9269 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 9270 ICI.inheritAll(InheritedBases[I]); 9271 } 9272 9273 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 9274 CXXConstructorDecl *Constructor) { 9275 CXXRecordDecl *ClassDecl = Constructor->getParent(); 9276 assert(Constructor->getInheritedConstructor() && 9277 !Constructor->doesThisDeclarationHaveABody() && 9278 !Constructor->isDeleted()); 9279 9280 SynthesizedFunctionScope Scope(*this, Constructor); 9281 DiagnosticErrorTrap Trap(Diags); 9282 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 9283 Trap.hasErrorOccurred()) { 9284 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 9285 << Context.getTagDeclType(ClassDecl); 9286 Constructor->setInvalidDecl(); 9287 return; 9288 } 9289 9290 SourceLocation Loc = Constructor->getLocation(); 9291 Constructor->setBody(new (Context) CompoundStmt(Loc)); 9292 9293 Constructor->markUsed(Context); 9294 MarkVTableUsed(CurrentLocation, ClassDecl); 9295 9296 if (ASTMutationListener *L = getASTMutationListener()) { 9297 L->CompletedImplicitDefinition(Constructor); 9298 } 9299 } 9300 9301 9302 Sema::ImplicitExceptionSpecification 9303 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 9304 CXXRecordDecl *ClassDecl = MD->getParent(); 9305 9306 // C++ [except.spec]p14: 9307 // An implicitly declared special member function (Clause 12) shall have 9308 // an exception-specification. 9309 ImplicitExceptionSpecification ExceptSpec(*this); 9310 if (ClassDecl->isInvalidDecl()) 9311 return ExceptSpec; 9312 9313 // Direct base-class destructors. 9314 for (const auto &B : ClassDecl->bases()) { 9315 if (B.isVirtual()) // Handled below. 9316 continue; 9317 9318 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9319 ExceptSpec.CalledDecl(B.getLocStart(), 9320 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9321 } 9322 9323 // Virtual base-class destructors. 9324 for (const auto &B : ClassDecl->vbases()) { 9325 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9326 ExceptSpec.CalledDecl(B.getLocStart(), 9327 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9328 } 9329 9330 // Field destructors. 9331 for (const auto *F : ClassDecl->fields()) { 9332 if (const RecordType *RecordTy 9333 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 9334 ExceptSpec.CalledDecl(F->getLocation(), 9335 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 9336 } 9337 9338 return ExceptSpec; 9339 } 9340 9341 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 9342 // C++ [class.dtor]p2: 9343 // If a class has no user-declared destructor, a destructor is 9344 // declared implicitly. An implicitly-declared destructor is an 9345 // inline public member of its class. 9346 assert(ClassDecl->needsImplicitDestructor()); 9347 9348 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 9349 if (DSM.isAlreadyBeingDeclared()) 9350 return nullptr; 9351 9352 // Create the actual destructor declaration. 9353 CanQualType ClassType 9354 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 9355 SourceLocation ClassLoc = ClassDecl->getLocation(); 9356 DeclarationName Name 9357 = Context.DeclarationNames.getCXXDestructorName(ClassType); 9358 DeclarationNameInfo NameInfo(Name, ClassLoc); 9359 CXXDestructorDecl *Destructor 9360 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 9361 QualType(), nullptr, /*isInline=*/true, 9362 /*isImplicitlyDeclared=*/true); 9363 Destructor->setAccess(AS_public); 9364 Destructor->setDefaulted(); 9365 9366 if (getLangOpts().CUDA) { 9367 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 9368 Destructor, 9369 /* ConstRHS */ false, 9370 /* Diagnose */ false); 9371 } 9372 9373 // Build an exception specification pointing back at this destructor. 9374 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 9375 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9376 9377 AddOverriddenMethods(ClassDecl, Destructor); 9378 9379 // We don't need to use SpecialMemberIsTrivial here; triviality for 9380 // destructors is easy to compute. 9381 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 9382 9383 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 9384 SetDeclDeleted(Destructor, ClassLoc); 9385 9386 // Note that we have declared this destructor. 9387 ++ASTContext::NumImplicitDestructorsDeclared; 9388 9389 // Introduce this destructor into its scope. 9390 if (Scope *S = getScopeForContext(ClassDecl)) 9391 PushOnScopeChains(Destructor, S, false); 9392 ClassDecl->addDecl(Destructor); 9393 9394 return Destructor; 9395 } 9396 9397 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 9398 CXXDestructorDecl *Destructor) { 9399 assert((Destructor->isDefaulted() && 9400 !Destructor->doesThisDeclarationHaveABody() && 9401 !Destructor->isDeleted()) && 9402 "DefineImplicitDestructor - call it for implicit default dtor"); 9403 CXXRecordDecl *ClassDecl = Destructor->getParent(); 9404 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 9405 9406 if (Destructor->isInvalidDecl()) 9407 return; 9408 9409 SynthesizedFunctionScope Scope(*this, Destructor); 9410 9411 DiagnosticErrorTrap Trap(Diags); 9412 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9413 Destructor->getParent()); 9414 9415 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 9416 Diag(CurrentLocation, diag::note_member_synthesized_at) 9417 << CXXDestructor << Context.getTagDeclType(ClassDecl); 9418 9419 Destructor->setInvalidDecl(); 9420 return; 9421 } 9422 9423 // The exception specification is needed because we are defining the 9424 // function. 9425 ResolveExceptionSpec(CurrentLocation, 9426 Destructor->getType()->castAs<FunctionProtoType>()); 9427 9428 SourceLocation Loc = Destructor->getLocEnd().isValid() 9429 ? Destructor->getLocEnd() 9430 : Destructor->getLocation(); 9431 Destructor->setBody(new (Context) CompoundStmt(Loc)); 9432 Destructor->markUsed(Context); 9433 MarkVTableUsed(CurrentLocation, ClassDecl); 9434 9435 if (ASTMutationListener *L = getASTMutationListener()) { 9436 L->CompletedImplicitDefinition(Destructor); 9437 } 9438 } 9439 9440 /// \brief Perform any semantic analysis which needs to be delayed until all 9441 /// pending class member declarations have been parsed. 9442 void Sema::ActOnFinishCXXMemberDecls() { 9443 // If the context is an invalid C++ class, just suppress these checks. 9444 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 9445 if (Record->isInvalidDecl()) { 9446 DelayedDefaultedMemberExceptionSpecs.clear(); 9447 DelayedExceptionSpecChecks.clear(); 9448 return; 9449 } 9450 } 9451 } 9452 9453 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) { 9454 // Don't do anything for template patterns. 9455 if (Class->getDescribedClassTemplate()) 9456 return; 9457 9458 for (Decl *Member : Class->decls()) { 9459 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 9460 if (!CD) { 9461 // Recurse on nested classes. 9462 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member)) 9463 getDefaultArgExprsForConstructors(S, NestedRD); 9464 continue; 9465 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) { 9466 continue; 9467 } 9468 9469 for (unsigned I = 0, E = CD->getNumParams(); I != E; ++I) { 9470 // Skip any default arguments that we've already instantiated. 9471 if (S.Context.getDefaultArgExprForConstructor(CD, I)) 9472 continue; 9473 9474 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD, 9475 CD->getParamDecl(I)).get(); 9476 S.DiscardCleanupsInEvaluationContext(); 9477 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg); 9478 } 9479 } 9480 } 9481 9482 void Sema::ActOnFinishCXXMemberDefaultArgs(Decl *D) { 9483 auto *RD = dyn_cast<CXXRecordDecl>(D); 9484 9485 // Default constructors that are annotated with __declspec(dllexport) which 9486 // have default arguments or don't use the standard calling convention are 9487 // wrapped with a thunk called the default constructor closure. 9488 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft()) 9489 getDefaultArgExprsForConstructors(*this, RD); 9490 } 9491 9492 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 9493 CXXDestructorDecl *Destructor) { 9494 assert(getLangOpts().CPlusPlus11 && 9495 "adjusting dtor exception specs was introduced in c++11"); 9496 9497 // C++11 [class.dtor]p3: 9498 // A declaration of a destructor that does not have an exception- 9499 // specification is implicitly considered to have the same exception- 9500 // specification as an implicit declaration. 9501 const FunctionProtoType *DtorType = Destructor->getType()-> 9502 getAs<FunctionProtoType>(); 9503 if (DtorType->hasExceptionSpec()) 9504 return; 9505 9506 // Replace the destructor's type, building off the existing one. Fortunately, 9507 // the only thing of interest in the destructor type is its extended info. 9508 // The return and arguments are fixed. 9509 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 9510 EPI.ExceptionSpec.Type = EST_Unevaluated; 9511 EPI.ExceptionSpec.SourceDecl = Destructor; 9512 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9513 9514 // FIXME: If the destructor has a body that could throw, and the newly created 9515 // spec doesn't allow exceptions, we should emit a warning, because this 9516 // change in behavior can break conforming C++03 programs at runtime. 9517 // However, we don't have a body or an exception specification yet, so it 9518 // needs to be done somewhere else. 9519 } 9520 9521 namespace { 9522 /// \brief An abstract base class for all helper classes used in building the 9523 // copy/move operators. These classes serve as factory functions and help us 9524 // avoid using the same Expr* in the AST twice. 9525 class ExprBuilder { 9526 ExprBuilder(const ExprBuilder&) = delete; 9527 ExprBuilder &operator=(const ExprBuilder&) = delete; 9528 9529 protected: 9530 static Expr *assertNotNull(Expr *E) { 9531 assert(E && "Expression construction must not fail."); 9532 return E; 9533 } 9534 9535 public: 9536 ExprBuilder() {} 9537 virtual ~ExprBuilder() {} 9538 9539 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 9540 }; 9541 9542 class RefBuilder: public ExprBuilder { 9543 VarDecl *Var; 9544 QualType VarType; 9545 9546 public: 9547 Expr *build(Sema &S, SourceLocation Loc) const override { 9548 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 9549 } 9550 9551 RefBuilder(VarDecl *Var, QualType VarType) 9552 : Var(Var), VarType(VarType) {} 9553 }; 9554 9555 class ThisBuilder: public ExprBuilder { 9556 public: 9557 Expr *build(Sema &S, SourceLocation Loc) const override { 9558 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 9559 } 9560 }; 9561 9562 class CastBuilder: public ExprBuilder { 9563 const ExprBuilder &Builder; 9564 QualType Type; 9565 ExprValueKind Kind; 9566 const CXXCastPath &Path; 9567 9568 public: 9569 Expr *build(Sema &S, SourceLocation Loc) const override { 9570 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 9571 CK_UncheckedDerivedToBase, Kind, 9572 &Path).get()); 9573 } 9574 9575 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 9576 const CXXCastPath &Path) 9577 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 9578 }; 9579 9580 class DerefBuilder: public ExprBuilder { 9581 const ExprBuilder &Builder; 9582 9583 public: 9584 Expr *build(Sema &S, SourceLocation Loc) const override { 9585 return assertNotNull( 9586 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 9587 } 9588 9589 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9590 }; 9591 9592 class MemberBuilder: public ExprBuilder { 9593 const ExprBuilder &Builder; 9594 QualType Type; 9595 CXXScopeSpec SS; 9596 bool IsArrow; 9597 LookupResult &MemberLookup; 9598 9599 public: 9600 Expr *build(Sema &S, SourceLocation Loc) const override { 9601 return assertNotNull(S.BuildMemberReferenceExpr( 9602 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 9603 nullptr, MemberLookup, nullptr).get()); 9604 } 9605 9606 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 9607 LookupResult &MemberLookup) 9608 : Builder(Builder), Type(Type), IsArrow(IsArrow), 9609 MemberLookup(MemberLookup) {} 9610 }; 9611 9612 class MoveCastBuilder: public ExprBuilder { 9613 const ExprBuilder &Builder; 9614 9615 public: 9616 Expr *build(Sema &S, SourceLocation Loc) const override { 9617 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 9618 } 9619 9620 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9621 }; 9622 9623 class LvalueConvBuilder: public ExprBuilder { 9624 const ExprBuilder &Builder; 9625 9626 public: 9627 Expr *build(Sema &S, SourceLocation Loc) const override { 9628 return assertNotNull( 9629 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 9630 } 9631 9632 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9633 }; 9634 9635 class SubscriptBuilder: public ExprBuilder { 9636 const ExprBuilder &Base; 9637 const ExprBuilder &Index; 9638 9639 public: 9640 Expr *build(Sema &S, SourceLocation Loc) const override { 9641 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 9642 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 9643 } 9644 9645 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 9646 : Base(Base), Index(Index) {} 9647 }; 9648 9649 } // end anonymous namespace 9650 9651 /// When generating a defaulted copy or move assignment operator, if a field 9652 /// should be copied with __builtin_memcpy rather than via explicit assignments, 9653 /// do so. This optimization only applies for arrays of scalars, and for arrays 9654 /// of class type where the selected copy/move-assignment operator is trivial. 9655 static StmtResult 9656 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 9657 const ExprBuilder &ToB, const ExprBuilder &FromB) { 9658 // Compute the size of the memory buffer to be copied. 9659 QualType SizeType = S.Context.getSizeType(); 9660 llvm::APInt Size(S.Context.getTypeSize(SizeType), 9661 S.Context.getTypeSizeInChars(T).getQuantity()); 9662 9663 // Take the address of the field references for "from" and "to". We 9664 // directly construct UnaryOperators here because semantic analysis 9665 // does not permit us to take the address of an xvalue. 9666 Expr *From = FromB.build(S, Loc); 9667 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 9668 S.Context.getPointerType(From->getType()), 9669 VK_RValue, OK_Ordinary, Loc); 9670 Expr *To = ToB.build(S, Loc); 9671 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 9672 S.Context.getPointerType(To->getType()), 9673 VK_RValue, OK_Ordinary, Loc); 9674 9675 const Type *E = T->getBaseElementTypeUnsafe(); 9676 bool NeedsCollectableMemCpy = 9677 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 9678 9679 // Create a reference to the __builtin_objc_memmove_collectable function 9680 StringRef MemCpyName = NeedsCollectableMemCpy ? 9681 "__builtin_objc_memmove_collectable" : 9682 "__builtin_memcpy"; 9683 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 9684 Sema::LookupOrdinaryName); 9685 S.LookupName(R, S.TUScope, true); 9686 9687 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 9688 if (!MemCpy) 9689 // Something went horribly wrong earlier, and we will have complained 9690 // about it. 9691 return StmtError(); 9692 9693 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 9694 VK_RValue, Loc, nullptr); 9695 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 9696 9697 Expr *CallArgs[] = { 9698 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 9699 }; 9700 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 9701 Loc, CallArgs, Loc); 9702 9703 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 9704 return Call.getAs<Stmt>(); 9705 } 9706 9707 /// \brief Builds a statement that copies/moves the given entity from \p From to 9708 /// \c To. 9709 /// 9710 /// This routine is used to copy/move the members of a class with an 9711 /// implicitly-declared copy/move assignment operator. When the entities being 9712 /// copied are arrays, this routine builds for loops to copy them. 9713 /// 9714 /// \param S The Sema object used for type-checking. 9715 /// 9716 /// \param Loc The location where the implicit copy/move is being generated. 9717 /// 9718 /// \param T The type of the expressions being copied/moved. Both expressions 9719 /// must have this type. 9720 /// 9721 /// \param To The expression we are copying/moving to. 9722 /// 9723 /// \param From The expression we are copying/moving from. 9724 /// 9725 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 9726 /// Otherwise, it's a non-static member subobject. 9727 /// 9728 /// \param Copying Whether we're copying or moving. 9729 /// 9730 /// \param Depth Internal parameter recording the depth of the recursion. 9731 /// 9732 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 9733 /// if a memcpy should be used instead. 9734 static StmtResult 9735 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 9736 const ExprBuilder &To, const ExprBuilder &From, 9737 bool CopyingBaseSubobject, bool Copying, 9738 unsigned Depth = 0) { 9739 // C++11 [class.copy]p28: 9740 // Each subobject is assigned in the manner appropriate to its type: 9741 // 9742 // - if the subobject is of class type, as if by a call to operator= with 9743 // the subobject as the object expression and the corresponding 9744 // subobject of x as a single function argument (as if by explicit 9745 // qualification; that is, ignoring any possible virtual overriding 9746 // functions in more derived classes); 9747 // 9748 // C++03 [class.copy]p13: 9749 // - if the subobject is of class type, the copy assignment operator for 9750 // the class is used (as if by explicit qualification; that is, 9751 // ignoring any possible virtual overriding functions in more derived 9752 // classes); 9753 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9754 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9755 9756 // Look for operator=. 9757 DeclarationName Name 9758 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9759 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9760 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9761 9762 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9763 // operator. 9764 if (!S.getLangOpts().CPlusPlus11) { 9765 LookupResult::Filter F = OpLookup.makeFilter(); 9766 while (F.hasNext()) { 9767 NamedDecl *D = F.next(); 9768 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9769 if (Method->isCopyAssignmentOperator() || 9770 (!Copying && Method->isMoveAssignmentOperator())) 9771 continue; 9772 9773 F.erase(); 9774 } 9775 F.done(); 9776 } 9777 9778 // Suppress the protected check (C++ [class.protected]) for each of the 9779 // assignment operators we found. This strange dance is required when 9780 // we're assigning via a base classes's copy-assignment operator. To 9781 // ensure that we're getting the right base class subobject (without 9782 // ambiguities), we need to cast "this" to that subobject type; to 9783 // ensure that we don't go through the virtual call mechanism, we need 9784 // to qualify the operator= name with the base class (see below). However, 9785 // this means that if the base class has a protected copy assignment 9786 // operator, the protected member access check will fail. So, we 9787 // rewrite "protected" access to "public" access in this case, since we 9788 // know by construction that we're calling from a derived class. 9789 if (CopyingBaseSubobject) { 9790 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9791 L != LEnd; ++L) { 9792 if (L.getAccess() == AS_protected) 9793 L.setAccess(AS_public); 9794 } 9795 } 9796 9797 // Create the nested-name-specifier that will be used to qualify the 9798 // reference to operator=; this is required to suppress the virtual 9799 // call mechanism. 9800 CXXScopeSpec SS; 9801 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9802 SS.MakeTrivial(S.Context, 9803 NestedNameSpecifier::Create(S.Context, nullptr, false, 9804 CanonicalT), 9805 Loc); 9806 9807 // Create the reference to operator=. 9808 ExprResult OpEqualRef 9809 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9810 SS, /*TemplateKWLoc=*/SourceLocation(), 9811 /*FirstQualifierInScope=*/nullptr, 9812 OpLookup, 9813 /*TemplateArgs=*/nullptr, 9814 /*SuppressQualifierCheck=*/true); 9815 if (OpEqualRef.isInvalid()) 9816 return StmtError(); 9817 9818 // Build the call to the assignment operator. 9819 9820 Expr *FromInst = From.build(S, Loc); 9821 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 9822 OpEqualRef.getAs<Expr>(), 9823 Loc, FromInst, Loc); 9824 if (Call.isInvalid()) 9825 return StmtError(); 9826 9827 // If we built a call to a trivial 'operator=' while copying an array, 9828 // bail out. We'll replace the whole shebang with a memcpy. 9829 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9830 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9831 return StmtResult((Stmt*)nullptr); 9832 9833 // Convert to an expression-statement, and clean up any produced 9834 // temporaries. 9835 return S.ActOnExprStmt(Call); 9836 } 9837 9838 // - if the subobject is of scalar type, the built-in assignment 9839 // operator is used. 9840 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9841 if (!ArrayTy) { 9842 ExprResult Assignment = S.CreateBuiltinBinOp( 9843 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9844 if (Assignment.isInvalid()) 9845 return StmtError(); 9846 return S.ActOnExprStmt(Assignment); 9847 } 9848 9849 // - if the subobject is an array, each element is assigned, in the 9850 // manner appropriate to the element type; 9851 9852 // Construct a loop over the array bounds, e.g., 9853 // 9854 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9855 // 9856 // that will copy each of the array elements. 9857 QualType SizeType = S.Context.getSizeType(); 9858 9859 // Create the iteration variable. 9860 IdentifierInfo *IterationVarName = nullptr; 9861 { 9862 SmallString<8> Str; 9863 llvm::raw_svector_ostream OS(Str); 9864 OS << "__i" << Depth; 9865 IterationVarName = &S.Context.Idents.get(OS.str()); 9866 } 9867 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9868 IterationVarName, SizeType, 9869 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9870 SC_None); 9871 9872 // Initialize the iteration variable to zero. 9873 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9874 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9875 9876 // Creates a reference to the iteration variable. 9877 RefBuilder IterationVarRef(IterationVar, SizeType); 9878 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9879 9880 // Create the DeclStmt that holds the iteration variable. 9881 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9882 9883 // Subscript the "from" and "to" expressions with the iteration variable. 9884 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9885 MoveCastBuilder FromIndexMove(FromIndexCopy); 9886 const ExprBuilder *FromIndex; 9887 if (Copying) 9888 FromIndex = &FromIndexCopy; 9889 else 9890 FromIndex = &FromIndexMove; 9891 9892 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9893 9894 // Build the copy/move for an individual element of the array. 9895 StmtResult Copy = 9896 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9897 ToIndex, *FromIndex, CopyingBaseSubobject, 9898 Copying, Depth + 1); 9899 // Bail out if copying fails or if we determined that we should use memcpy. 9900 if (Copy.isInvalid() || !Copy.get()) 9901 return Copy; 9902 9903 // Create the comparison against the array bound. 9904 llvm::APInt Upper 9905 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9906 Expr *Comparison 9907 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9908 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9909 BO_NE, S.Context.BoolTy, 9910 VK_RValue, OK_Ordinary, Loc, false); 9911 9912 // Create the pre-increment of the iteration variable. 9913 Expr *Increment 9914 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9915 SizeType, VK_LValue, OK_Ordinary, Loc); 9916 9917 // Construct the loop that copies all elements of this array. 9918 return S.ActOnForStmt(Loc, Loc, InitStmt, 9919 S.MakeFullExpr(Comparison), 9920 nullptr, S.MakeFullDiscardedValueExpr(Increment), 9921 Loc, Copy.get()); 9922 } 9923 9924 static StmtResult 9925 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9926 const ExprBuilder &To, const ExprBuilder &From, 9927 bool CopyingBaseSubobject, bool Copying) { 9928 // Maybe we should use a memcpy? 9929 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9930 T.isTriviallyCopyableType(S.Context)) 9931 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9932 9933 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9934 CopyingBaseSubobject, 9935 Copying, 0)); 9936 9937 // If we ended up picking a trivial assignment operator for an array of a 9938 // non-trivially-copyable class type, just emit a memcpy. 9939 if (!Result.isInvalid() && !Result.get()) 9940 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9941 9942 return Result; 9943 } 9944 9945 Sema::ImplicitExceptionSpecification 9946 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9947 CXXRecordDecl *ClassDecl = MD->getParent(); 9948 9949 ImplicitExceptionSpecification ExceptSpec(*this); 9950 if (ClassDecl->isInvalidDecl()) 9951 return ExceptSpec; 9952 9953 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9954 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9955 unsigned ArgQuals = 9956 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9957 9958 // C++ [except.spec]p14: 9959 // An implicitly declared special member function (Clause 12) shall have an 9960 // exception-specification. [...] 9961 9962 // It is unspecified whether or not an implicit copy assignment operator 9963 // attempts to deduplicate calls to assignment operators of virtual bases are 9964 // made. As such, this exception specification is effectively unspecified. 9965 // Based on a similar decision made for constness in C++0x, we're erring on 9966 // the side of assuming such calls to be made regardless of whether they 9967 // actually happen. 9968 for (const auto &Base : ClassDecl->bases()) { 9969 if (Base.isVirtual()) 9970 continue; 9971 9972 CXXRecordDecl *BaseClassDecl 9973 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9974 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9975 ArgQuals, false, 0)) 9976 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9977 } 9978 9979 for (const auto &Base : ClassDecl->vbases()) { 9980 CXXRecordDecl *BaseClassDecl 9981 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9982 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9983 ArgQuals, false, 0)) 9984 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9985 } 9986 9987 for (const auto *Field : ClassDecl->fields()) { 9988 QualType FieldType = Context.getBaseElementType(Field->getType()); 9989 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9990 if (CXXMethodDecl *CopyAssign = 9991 LookupCopyingAssignment(FieldClassDecl, 9992 ArgQuals | FieldType.getCVRQualifiers(), 9993 false, 0)) 9994 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 9995 } 9996 } 9997 9998 return ExceptSpec; 9999 } 10000 10001 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 10002 // Note: The following rules are largely analoguous to the copy 10003 // constructor rules. Note that virtual bases are not taken into account 10004 // for determining the argument type of the operator. Note also that 10005 // operators taking an object instead of a reference are allowed. 10006 assert(ClassDecl->needsImplicitCopyAssignment()); 10007 10008 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 10009 if (DSM.isAlreadyBeingDeclared()) 10010 return nullptr; 10011 10012 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10013 QualType RetType = Context.getLValueReferenceType(ArgType); 10014 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 10015 if (Const) 10016 ArgType = ArgType.withConst(); 10017 ArgType = Context.getLValueReferenceType(ArgType); 10018 10019 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10020 CXXCopyAssignment, 10021 Const); 10022 10023 // An implicitly-declared copy assignment operator is an inline public 10024 // member of its class. 10025 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10026 SourceLocation ClassLoc = ClassDecl->getLocation(); 10027 DeclarationNameInfo NameInfo(Name, ClassLoc); 10028 CXXMethodDecl *CopyAssignment = 10029 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10030 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10031 /*isInline=*/true, Constexpr, SourceLocation()); 10032 CopyAssignment->setAccess(AS_public); 10033 CopyAssignment->setDefaulted(); 10034 CopyAssignment->setImplicit(); 10035 10036 if (getLangOpts().CUDA) { 10037 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 10038 CopyAssignment, 10039 /* ConstRHS */ Const, 10040 /* Diagnose */ false); 10041 } 10042 10043 // Build an exception specification pointing back at this member. 10044 FunctionProtoType::ExtProtoInfo EPI = 10045 getImplicitMethodEPI(*this, CopyAssignment); 10046 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10047 10048 // Add the parameter to the operator. 10049 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 10050 ClassLoc, ClassLoc, 10051 /*Id=*/nullptr, ArgType, 10052 /*TInfo=*/nullptr, SC_None, 10053 nullptr); 10054 CopyAssignment->setParams(FromParam); 10055 10056 AddOverriddenMethods(ClassDecl, CopyAssignment); 10057 10058 CopyAssignment->setTrivial( 10059 ClassDecl->needsOverloadResolutionForCopyAssignment() 10060 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 10061 : ClassDecl->hasTrivialCopyAssignment()); 10062 10063 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 10064 SetDeclDeleted(CopyAssignment, ClassLoc); 10065 10066 // Note that we have added this copy-assignment operator. 10067 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 10068 10069 if (Scope *S = getScopeForContext(ClassDecl)) 10070 PushOnScopeChains(CopyAssignment, S, false); 10071 ClassDecl->addDecl(CopyAssignment); 10072 10073 return CopyAssignment; 10074 } 10075 10076 /// Diagnose an implicit copy operation for a class which is odr-used, but 10077 /// which is deprecated because the class has a user-declared copy constructor, 10078 /// copy assignment operator, or destructor. 10079 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 10080 SourceLocation UseLoc) { 10081 assert(CopyOp->isImplicit()); 10082 10083 CXXRecordDecl *RD = CopyOp->getParent(); 10084 CXXMethodDecl *UserDeclaredOperation = nullptr; 10085 10086 // In Microsoft mode, assignment operations don't affect constructors and 10087 // vice versa. 10088 if (RD->hasUserDeclaredDestructor()) { 10089 UserDeclaredOperation = RD->getDestructor(); 10090 } else if (!isa<CXXConstructorDecl>(CopyOp) && 10091 RD->hasUserDeclaredCopyConstructor() && 10092 !S.getLangOpts().MSVCCompat) { 10093 // Find any user-declared copy constructor. 10094 for (auto *I : RD->ctors()) { 10095 if (I->isCopyConstructor()) { 10096 UserDeclaredOperation = I; 10097 break; 10098 } 10099 } 10100 assert(UserDeclaredOperation); 10101 } else if (isa<CXXConstructorDecl>(CopyOp) && 10102 RD->hasUserDeclaredCopyAssignment() && 10103 !S.getLangOpts().MSVCCompat) { 10104 // Find any user-declared move assignment operator. 10105 for (auto *I : RD->methods()) { 10106 if (I->isCopyAssignmentOperator()) { 10107 UserDeclaredOperation = I; 10108 break; 10109 } 10110 } 10111 assert(UserDeclaredOperation); 10112 } 10113 10114 if (UserDeclaredOperation) { 10115 S.Diag(UserDeclaredOperation->getLocation(), 10116 diag::warn_deprecated_copy_operation) 10117 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 10118 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 10119 S.Diag(UseLoc, diag::note_member_synthesized_at) 10120 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 10121 : Sema::CXXCopyAssignment) 10122 << RD; 10123 } 10124 } 10125 10126 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 10127 CXXMethodDecl *CopyAssignOperator) { 10128 assert((CopyAssignOperator->isDefaulted() && 10129 CopyAssignOperator->isOverloadedOperator() && 10130 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 10131 !CopyAssignOperator->doesThisDeclarationHaveABody() && 10132 !CopyAssignOperator->isDeleted()) && 10133 "DefineImplicitCopyAssignment called for wrong function"); 10134 10135 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 10136 10137 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 10138 CopyAssignOperator->setInvalidDecl(); 10139 return; 10140 } 10141 10142 // C++11 [class.copy]p18: 10143 // The [definition of an implicitly declared copy assignment operator] is 10144 // deprecated if the class has a user-declared copy constructor or a 10145 // user-declared destructor. 10146 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 10147 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 10148 10149 CopyAssignOperator->markUsed(Context); 10150 10151 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 10152 DiagnosticErrorTrap Trap(Diags); 10153 10154 // C++0x [class.copy]p30: 10155 // The implicitly-defined or explicitly-defaulted copy assignment operator 10156 // for a non-union class X performs memberwise copy assignment of its 10157 // subobjects. The direct base classes of X are assigned first, in the 10158 // order of their declaration in the base-specifier-list, and then the 10159 // immediate non-static data members of X are assigned, in the order in 10160 // which they were declared in the class definition. 10161 10162 // The statements that form the synthesized function body. 10163 SmallVector<Stmt*, 8> Statements; 10164 10165 // The parameter for the "other" object, which we are copying from. 10166 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 10167 Qualifiers OtherQuals = Other->getType().getQualifiers(); 10168 QualType OtherRefType = Other->getType(); 10169 if (const LValueReferenceType *OtherRef 10170 = OtherRefType->getAs<LValueReferenceType>()) { 10171 OtherRefType = OtherRef->getPointeeType(); 10172 OtherQuals = OtherRefType.getQualifiers(); 10173 } 10174 10175 // Our location for everything implicitly-generated. 10176 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 10177 ? CopyAssignOperator->getLocEnd() 10178 : CopyAssignOperator->getLocation(); 10179 10180 // Builds a DeclRefExpr for the "other" object. 10181 RefBuilder OtherRef(Other, OtherRefType); 10182 10183 // Builds the "this" pointer. 10184 ThisBuilder This; 10185 10186 // Assign base classes. 10187 bool Invalid = false; 10188 for (auto &Base : ClassDecl->bases()) { 10189 // Form the assignment: 10190 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 10191 QualType BaseType = Base.getType().getUnqualifiedType(); 10192 if (!BaseType->isRecordType()) { 10193 Invalid = true; 10194 continue; 10195 } 10196 10197 CXXCastPath BasePath; 10198 BasePath.push_back(&Base); 10199 10200 // Construct the "from" expression, which is an implicit cast to the 10201 // appropriately-qualified base type. 10202 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 10203 VK_LValue, BasePath); 10204 10205 // Dereference "this". 10206 DerefBuilder DerefThis(This); 10207 CastBuilder To(DerefThis, 10208 Context.getCVRQualifiedType( 10209 BaseType, CopyAssignOperator->getTypeQualifiers()), 10210 VK_LValue, BasePath); 10211 10212 // Build the copy. 10213 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 10214 To, From, 10215 /*CopyingBaseSubobject=*/true, 10216 /*Copying=*/true); 10217 if (Copy.isInvalid()) { 10218 Diag(CurrentLocation, diag::note_member_synthesized_at) 10219 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10220 CopyAssignOperator->setInvalidDecl(); 10221 return; 10222 } 10223 10224 // Success! Record the copy. 10225 Statements.push_back(Copy.getAs<Expr>()); 10226 } 10227 10228 // Assign non-static members. 10229 for (auto *Field : ClassDecl->fields()) { 10230 // FIXME: We should form some kind of AST representation for the implied 10231 // memcpy in a union copy operation. 10232 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 10233 continue; 10234 10235 if (Field->isInvalidDecl()) { 10236 Invalid = true; 10237 continue; 10238 } 10239 10240 // Check for members of reference type; we can't copy those. 10241 if (Field->getType()->isReferenceType()) { 10242 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10243 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10244 Diag(Field->getLocation(), diag::note_declared_at); 10245 Diag(CurrentLocation, diag::note_member_synthesized_at) 10246 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10247 Invalid = true; 10248 continue; 10249 } 10250 10251 // Check for members of const-qualified, non-class type. 10252 QualType BaseType = Context.getBaseElementType(Field->getType()); 10253 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10254 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10255 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10256 Diag(Field->getLocation(), diag::note_declared_at); 10257 Diag(CurrentLocation, diag::note_member_synthesized_at) 10258 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10259 Invalid = true; 10260 continue; 10261 } 10262 10263 // Suppress assigning zero-width bitfields. 10264 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10265 continue; 10266 10267 QualType FieldType = Field->getType().getNonReferenceType(); 10268 if (FieldType->isIncompleteArrayType()) { 10269 assert(ClassDecl->hasFlexibleArrayMember() && 10270 "Incomplete array type is not valid"); 10271 continue; 10272 } 10273 10274 // Build references to the field in the object we're copying from and to. 10275 CXXScopeSpec SS; // Intentionally empty 10276 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10277 LookupMemberName); 10278 MemberLookup.addDecl(Field); 10279 MemberLookup.resolveKind(); 10280 10281 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 10282 10283 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 10284 10285 // Build the copy of this field. 10286 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 10287 To, From, 10288 /*CopyingBaseSubobject=*/false, 10289 /*Copying=*/true); 10290 if (Copy.isInvalid()) { 10291 Diag(CurrentLocation, diag::note_member_synthesized_at) 10292 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10293 CopyAssignOperator->setInvalidDecl(); 10294 return; 10295 } 10296 10297 // Success! Record the copy. 10298 Statements.push_back(Copy.getAs<Stmt>()); 10299 } 10300 10301 if (!Invalid) { 10302 // Add a "return *this;" 10303 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10304 10305 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10306 if (Return.isInvalid()) 10307 Invalid = true; 10308 else { 10309 Statements.push_back(Return.getAs<Stmt>()); 10310 10311 if (Trap.hasErrorOccurred()) { 10312 Diag(CurrentLocation, diag::note_member_synthesized_at) 10313 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10314 Invalid = true; 10315 } 10316 } 10317 } 10318 10319 // The exception specification is needed because we are defining the 10320 // function. 10321 ResolveExceptionSpec(CurrentLocation, 10322 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 10323 10324 if (Invalid) { 10325 CopyAssignOperator->setInvalidDecl(); 10326 return; 10327 } 10328 10329 StmtResult Body; 10330 { 10331 CompoundScopeRAII CompoundScope(*this); 10332 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10333 /*isStmtExpr=*/false); 10334 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10335 } 10336 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 10337 10338 if (ASTMutationListener *L = getASTMutationListener()) { 10339 L->CompletedImplicitDefinition(CopyAssignOperator); 10340 } 10341 } 10342 10343 Sema::ImplicitExceptionSpecification 10344 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 10345 CXXRecordDecl *ClassDecl = MD->getParent(); 10346 10347 ImplicitExceptionSpecification ExceptSpec(*this); 10348 if (ClassDecl->isInvalidDecl()) 10349 return ExceptSpec; 10350 10351 // C++0x [except.spec]p14: 10352 // An implicitly declared special member function (Clause 12) shall have an 10353 // exception-specification. [...] 10354 10355 // It is unspecified whether or not an implicit move assignment operator 10356 // attempts to deduplicate calls to assignment operators of virtual bases are 10357 // made. As such, this exception specification is effectively unspecified. 10358 // Based on a similar decision made for constness in C++0x, we're erring on 10359 // the side of assuming such calls to be made regardless of whether they 10360 // actually happen. 10361 // Note that a move constructor is not implicitly declared when there are 10362 // virtual bases, but it can still be user-declared and explicitly defaulted. 10363 for (const auto &Base : ClassDecl->bases()) { 10364 if (Base.isVirtual()) 10365 continue; 10366 10367 CXXRecordDecl *BaseClassDecl 10368 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10369 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10370 0, false, 0)) 10371 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10372 } 10373 10374 for (const auto &Base : ClassDecl->vbases()) { 10375 CXXRecordDecl *BaseClassDecl 10376 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10377 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10378 0, false, 0)) 10379 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10380 } 10381 10382 for (const auto *Field : ClassDecl->fields()) { 10383 QualType FieldType = Context.getBaseElementType(Field->getType()); 10384 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10385 if (CXXMethodDecl *MoveAssign = 10386 LookupMovingAssignment(FieldClassDecl, 10387 FieldType.getCVRQualifiers(), 10388 false, 0)) 10389 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 10390 } 10391 } 10392 10393 return ExceptSpec; 10394 } 10395 10396 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 10397 assert(ClassDecl->needsImplicitMoveAssignment()); 10398 10399 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 10400 if (DSM.isAlreadyBeingDeclared()) 10401 return nullptr; 10402 10403 // Note: The following rules are largely analoguous to the move 10404 // constructor rules. 10405 10406 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10407 QualType RetType = Context.getLValueReferenceType(ArgType); 10408 ArgType = Context.getRValueReferenceType(ArgType); 10409 10410 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10411 CXXMoveAssignment, 10412 false); 10413 10414 // An implicitly-declared move assignment operator is an inline public 10415 // member of its class. 10416 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10417 SourceLocation ClassLoc = ClassDecl->getLocation(); 10418 DeclarationNameInfo NameInfo(Name, ClassLoc); 10419 CXXMethodDecl *MoveAssignment = 10420 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10421 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10422 /*isInline=*/true, Constexpr, SourceLocation()); 10423 MoveAssignment->setAccess(AS_public); 10424 MoveAssignment->setDefaulted(); 10425 MoveAssignment->setImplicit(); 10426 10427 if (getLangOpts().CUDA) { 10428 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 10429 MoveAssignment, 10430 /* ConstRHS */ false, 10431 /* Diagnose */ false); 10432 } 10433 10434 // Build an exception specification pointing back at this member. 10435 FunctionProtoType::ExtProtoInfo EPI = 10436 getImplicitMethodEPI(*this, MoveAssignment); 10437 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10438 10439 // Add the parameter to the operator. 10440 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 10441 ClassLoc, ClassLoc, 10442 /*Id=*/nullptr, ArgType, 10443 /*TInfo=*/nullptr, SC_None, 10444 nullptr); 10445 MoveAssignment->setParams(FromParam); 10446 10447 AddOverriddenMethods(ClassDecl, MoveAssignment); 10448 10449 MoveAssignment->setTrivial( 10450 ClassDecl->needsOverloadResolutionForMoveAssignment() 10451 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 10452 : ClassDecl->hasTrivialMoveAssignment()); 10453 10454 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 10455 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 10456 SetDeclDeleted(MoveAssignment, ClassLoc); 10457 } 10458 10459 // Note that we have added this copy-assignment operator. 10460 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 10461 10462 if (Scope *S = getScopeForContext(ClassDecl)) 10463 PushOnScopeChains(MoveAssignment, S, false); 10464 ClassDecl->addDecl(MoveAssignment); 10465 10466 return MoveAssignment; 10467 } 10468 10469 /// Check if we're implicitly defining a move assignment operator for a class 10470 /// with virtual bases. Such a move assignment might move-assign the virtual 10471 /// base multiple times. 10472 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 10473 SourceLocation CurrentLocation) { 10474 assert(!Class->isDependentContext() && "should not define dependent move"); 10475 10476 // Only a virtual base could get implicitly move-assigned multiple times. 10477 // Only a non-trivial move assignment can observe this. We only want to 10478 // diagnose if we implicitly define an assignment operator that assigns 10479 // two base classes, both of which move-assign the same virtual base. 10480 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 10481 Class->getNumBases() < 2) 10482 return; 10483 10484 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 10485 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 10486 VBaseMap VBases; 10487 10488 for (auto &BI : Class->bases()) { 10489 Worklist.push_back(&BI); 10490 while (!Worklist.empty()) { 10491 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 10492 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 10493 10494 // If the base has no non-trivial move assignment operators, 10495 // we don't care about moves from it. 10496 if (!Base->hasNonTrivialMoveAssignment()) 10497 continue; 10498 10499 // If there's nothing virtual here, skip it. 10500 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 10501 continue; 10502 10503 // If we're not actually going to call a move assignment for this base, 10504 // or the selected move assignment is trivial, skip it. 10505 Sema::SpecialMemberOverloadResult *SMOR = 10506 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 10507 /*ConstArg*/false, /*VolatileArg*/false, 10508 /*RValueThis*/true, /*ConstThis*/false, 10509 /*VolatileThis*/false); 10510 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 10511 !SMOR->getMethod()->isMoveAssignmentOperator()) 10512 continue; 10513 10514 if (BaseSpec->isVirtual()) { 10515 // We're going to move-assign this virtual base, and its move 10516 // assignment operator is not trivial. If this can happen for 10517 // multiple distinct direct bases of Class, diagnose it. (If it 10518 // only happens in one base, we'll diagnose it when synthesizing 10519 // that base class's move assignment operator.) 10520 CXXBaseSpecifier *&Existing = 10521 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 10522 .first->second; 10523 if (Existing && Existing != &BI) { 10524 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 10525 << Class << Base; 10526 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 10527 << (Base->getCanonicalDecl() == 10528 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10529 << Base << Existing->getType() << Existing->getSourceRange(); 10530 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 10531 << (Base->getCanonicalDecl() == 10532 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10533 << Base << BI.getType() << BaseSpec->getSourceRange(); 10534 10535 // Only diagnose each vbase once. 10536 Existing = nullptr; 10537 } 10538 } else { 10539 // Only walk over bases that have defaulted move assignment operators. 10540 // We assume that any user-provided move assignment operator handles 10541 // the multiple-moves-of-vbase case itself somehow. 10542 if (!SMOR->getMethod()->isDefaulted()) 10543 continue; 10544 10545 // We're going to move the base classes of Base. Add them to the list. 10546 for (auto &BI : Base->bases()) 10547 Worklist.push_back(&BI); 10548 } 10549 } 10550 } 10551 } 10552 10553 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 10554 CXXMethodDecl *MoveAssignOperator) { 10555 assert((MoveAssignOperator->isDefaulted() && 10556 MoveAssignOperator->isOverloadedOperator() && 10557 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 10558 !MoveAssignOperator->doesThisDeclarationHaveABody() && 10559 !MoveAssignOperator->isDeleted()) && 10560 "DefineImplicitMoveAssignment called for wrong function"); 10561 10562 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 10563 10564 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 10565 MoveAssignOperator->setInvalidDecl(); 10566 return; 10567 } 10568 10569 MoveAssignOperator->markUsed(Context); 10570 10571 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 10572 DiagnosticErrorTrap Trap(Diags); 10573 10574 // C++0x [class.copy]p28: 10575 // The implicitly-defined or move assignment operator for a non-union class 10576 // X performs memberwise move assignment of its subobjects. The direct base 10577 // classes of X are assigned first, in the order of their declaration in the 10578 // base-specifier-list, and then the immediate non-static data members of X 10579 // are assigned, in the order in which they were declared in the class 10580 // definition. 10581 10582 // Issue a warning if our implicit move assignment operator will move 10583 // from a virtual base more than once. 10584 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 10585 10586 // The statements that form the synthesized function body. 10587 SmallVector<Stmt*, 8> Statements; 10588 10589 // The parameter for the "other" object, which we are move from. 10590 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 10591 QualType OtherRefType = Other->getType()-> 10592 getAs<RValueReferenceType>()->getPointeeType(); 10593 assert(!OtherRefType.getQualifiers() && 10594 "Bad argument type of defaulted move assignment"); 10595 10596 // Our location for everything implicitly-generated. 10597 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 10598 ? MoveAssignOperator->getLocEnd() 10599 : MoveAssignOperator->getLocation(); 10600 10601 // Builds a reference to the "other" object. 10602 RefBuilder OtherRef(Other, OtherRefType); 10603 // Cast to rvalue. 10604 MoveCastBuilder MoveOther(OtherRef); 10605 10606 // Builds the "this" pointer. 10607 ThisBuilder This; 10608 10609 // Assign base classes. 10610 bool Invalid = false; 10611 for (auto &Base : ClassDecl->bases()) { 10612 // C++11 [class.copy]p28: 10613 // It is unspecified whether subobjects representing virtual base classes 10614 // are assigned more than once by the implicitly-defined copy assignment 10615 // operator. 10616 // FIXME: Do not assign to a vbase that will be assigned by some other base 10617 // class. For a move-assignment, this can result in the vbase being moved 10618 // multiple times. 10619 10620 // Form the assignment: 10621 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 10622 QualType BaseType = Base.getType().getUnqualifiedType(); 10623 if (!BaseType->isRecordType()) { 10624 Invalid = true; 10625 continue; 10626 } 10627 10628 CXXCastPath BasePath; 10629 BasePath.push_back(&Base); 10630 10631 // Construct the "from" expression, which is an implicit cast to the 10632 // appropriately-qualified base type. 10633 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 10634 10635 // Dereference "this". 10636 DerefBuilder DerefThis(This); 10637 10638 // Implicitly cast "this" to the appropriately-qualified base type. 10639 CastBuilder To(DerefThis, 10640 Context.getCVRQualifiedType( 10641 BaseType, MoveAssignOperator->getTypeQualifiers()), 10642 VK_LValue, BasePath); 10643 10644 // Build the move. 10645 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 10646 To, From, 10647 /*CopyingBaseSubobject=*/true, 10648 /*Copying=*/false); 10649 if (Move.isInvalid()) { 10650 Diag(CurrentLocation, diag::note_member_synthesized_at) 10651 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10652 MoveAssignOperator->setInvalidDecl(); 10653 return; 10654 } 10655 10656 // Success! Record the move. 10657 Statements.push_back(Move.getAs<Expr>()); 10658 } 10659 10660 // Assign non-static members. 10661 for (auto *Field : ClassDecl->fields()) { 10662 // FIXME: We should form some kind of AST representation for the implied 10663 // memcpy in a union copy operation. 10664 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 10665 continue; 10666 10667 if (Field->isInvalidDecl()) { 10668 Invalid = true; 10669 continue; 10670 } 10671 10672 // Check for members of reference type; we can't move those. 10673 if (Field->getType()->isReferenceType()) { 10674 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10675 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10676 Diag(Field->getLocation(), diag::note_declared_at); 10677 Diag(CurrentLocation, diag::note_member_synthesized_at) 10678 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10679 Invalid = true; 10680 continue; 10681 } 10682 10683 // Check for members of const-qualified, non-class type. 10684 QualType BaseType = Context.getBaseElementType(Field->getType()); 10685 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10686 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10687 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10688 Diag(Field->getLocation(), diag::note_declared_at); 10689 Diag(CurrentLocation, diag::note_member_synthesized_at) 10690 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10691 Invalid = true; 10692 continue; 10693 } 10694 10695 // Suppress assigning zero-width bitfields. 10696 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10697 continue; 10698 10699 QualType FieldType = Field->getType().getNonReferenceType(); 10700 if (FieldType->isIncompleteArrayType()) { 10701 assert(ClassDecl->hasFlexibleArrayMember() && 10702 "Incomplete array type is not valid"); 10703 continue; 10704 } 10705 10706 // Build references to the field in the object we're copying from and to. 10707 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10708 LookupMemberName); 10709 MemberLookup.addDecl(Field); 10710 MemberLookup.resolveKind(); 10711 MemberBuilder From(MoveOther, OtherRefType, 10712 /*IsArrow=*/false, MemberLookup); 10713 MemberBuilder To(This, getCurrentThisType(), 10714 /*IsArrow=*/true, MemberLookup); 10715 10716 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 10717 "Member reference with rvalue base must be rvalue except for reference " 10718 "members, which aren't allowed for move assignment."); 10719 10720 // Build the move of this field. 10721 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 10722 To, From, 10723 /*CopyingBaseSubobject=*/false, 10724 /*Copying=*/false); 10725 if (Move.isInvalid()) { 10726 Diag(CurrentLocation, diag::note_member_synthesized_at) 10727 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10728 MoveAssignOperator->setInvalidDecl(); 10729 return; 10730 } 10731 10732 // Success! Record the copy. 10733 Statements.push_back(Move.getAs<Stmt>()); 10734 } 10735 10736 if (!Invalid) { 10737 // Add a "return *this;" 10738 ExprResult ThisObj = 10739 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10740 10741 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10742 if (Return.isInvalid()) 10743 Invalid = true; 10744 else { 10745 Statements.push_back(Return.getAs<Stmt>()); 10746 10747 if (Trap.hasErrorOccurred()) { 10748 Diag(CurrentLocation, diag::note_member_synthesized_at) 10749 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10750 Invalid = true; 10751 } 10752 } 10753 } 10754 10755 // The exception specification is needed because we are defining the 10756 // function. 10757 ResolveExceptionSpec(CurrentLocation, 10758 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 10759 10760 if (Invalid) { 10761 MoveAssignOperator->setInvalidDecl(); 10762 return; 10763 } 10764 10765 StmtResult Body; 10766 { 10767 CompoundScopeRAII CompoundScope(*this); 10768 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10769 /*isStmtExpr=*/false); 10770 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10771 } 10772 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 10773 10774 if (ASTMutationListener *L = getASTMutationListener()) { 10775 L->CompletedImplicitDefinition(MoveAssignOperator); 10776 } 10777 } 10778 10779 Sema::ImplicitExceptionSpecification 10780 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10781 CXXRecordDecl *ClassDecl = MD->getParent(); 10782 10783 ImplicitExceptionSpecification ExceptSpec(*this); 10784 if (ClassDecl->isInvalidDecl()) 10785 return ExceptSpec; 10786 10787 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10788 assert(T->getNumParams() >= 1 && "not a copy ctor"); 10789 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10790 10791 // C++ [except.spec]p14: 10792 // An implicitly declared special member function (Clause 12) shall have an 10793 // exception-specification. [...] 10794 for (const auto &Base : ClassDecl->bases()) { 10795 // Virtual bases are handled below. 10796 if (Base.isVirtual()) 10797 continue; 10798 10799 CXXRecordDecl *BaseClassDecl 10800 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10801 if (CXXConstructorDecl *CopyConstructor = 10802 LookupCopyingConstructor(BaseClassDecl, Quals)) 10803 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10804 } 10805 for (const auto &Base : ClassDecl->vbases()) { 10806 CXXRecordDecl *BaseClassDecl 10807 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10808 if (CXXConstructorDecl *CopyConstructor = 10809 LookupCopyingConstructor(BaseClassDecl, Quals)) 10810 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10811 } 10812 for (const auto *Field : ClassDecl->fields()) { 10813 QualType FieldType = Context.getBaseElementType(Field->getType()); 10814 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10815 if (CXXConstructorDecl *CopyConstructor = 10816 LookupCopyingConstructor(FieldClassDecl, 10817 Quals | FieldType.getCVRQualifiers())) 10818 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10819 } 10820 } 10821 10822 return ExceptSpec; 10823 } 10824 10825 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10826 CXXRecordDecl *ClassDecl) { 10827 // C++ [class.copy]p4: 10828 // If the class definition does not explicitly declare a copy 10829 // constructor, one is declared implicitly. 10830 assert(ClassDecl->needsImplicitCopyConstructor()); 10831 10832 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10833 if (DSM.isAlreadyBeingDeclared()) 10834 return nullptr; 10835 10836 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10837 QualType ArgType = ClassType; 10838 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10839 if (Const) 10840 ArgType = ArgType.withConst(); 10841 ArgType = Context.getLValueReferenceType(ArgType); 10842 10843 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10844 CXXCopyConstructor, 10845 Const); 10846 10847 DeclarationName Name 10848 = Context.DeclarationNames.getCXXConstructorName( 10849 Context.getCanonicalType(ClassType)); 10850 SourceLocation ClassLoc = ClassDecl->getLocation(); 10851 DeclarationNameInfo NameInfo(Name, ClassLoc); 10852 10853 // An implicitly-declared copy constructor is an inline public 10854 // member of its class. 10855 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10856 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10857 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10858 Constexpr); 10859 CopyConstructor->setAccess(AS_public); 10860 CopyConstructor->setDefaulted(); 10861 10862 if (getLangOpts().CUDA) { 10863 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 10864 CopyConstructor, 10865 /* ConstRHS */ Const, 10866 /* Diagnose */ false); 10867 } 10868 10869 // Build an exception specification pointing back at this member. 10870 FunctionProtoType::ExtProtoInfo EPI = 10871 getImplicitMethodEPI(*this, CopyConstructor); 10872 CopyConstructor->setType( 10873 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10874 10875 // Add the parameter to the constructor. 10876 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10877 ClassLoc, ClassLoc, 10878 /*IdentifierInfo=*/nullptr, 10879 ArgType, /*TInfo=*/nullptr, 10880 SC_None, nullptr); 10881 CopyConstructor->setParams(FromParam); 10882 10883 CopyConstructor->setTrivial( 10884 ClassDecl->needsOverloadResolutionForCopyConstructor() 10885 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10886 : ClassDecl->hasTrivialCopyConstructor()); 10887 10888 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10889 SetDeclDeleted(CopyConstructor, ClassLoc); 10890 10891 // Note that we have declared this constructor. 10892 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10893 10894 if (Scope *S = getScopeForContext(ClassDecl)) 10895 PushOnScopeChains(CopyConstructor, S, false); 10896 ClassDecl->addDecl(CopyConstructor); 10897 10898 return CopyConstructor; 10899 } 10900 10901 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10902 CXXConstructorDecl *CopyConstructor) { 10903 assert((CopyConstructor->isDefaulted() && 10904 CopyConstructor->isCopyConstructor() && 10905 !CopyConstructor->doesThisDeclarationHaveABody() && 10906 !CopyConstructor->isDeleted()) && 10907 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10908 10909 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10910 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10911 10912 // C++11 [class.copy]p7: 10913 // The [definition of an implicitly declared copy constructor] is 10914 // deprecated if the class has a user-declared copy assignment operator 10915 // or a user-declared destructor. 10916 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10917 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10918 10919 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10920 DiagnosticErrorTrap Trap(Diags); 10921 10922 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10923 Trap.hasErrorOccurred()) { 10924 Diag(CurrentLocation, diag::note_member_synthesized_at) 10925 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10926 CopyConstructor->setInvalidDecl(); 10927 } else { 10928 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 10929 ? CopyConstructor->getLocEnd() 10930 : CopyConstructor->getLocation(); 10931 Sema::CompoundScopeRAII CompoundScope(*this); 10932 CopyConstructor->setBody( 10933 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 10934 } 10935 10936 // The exception specification is needed because we are defining the 10937 // function. 10938 ResolveExceptionSpec(CurrentLocation, 10939 CopyConstructor->getType()->castAs<FunctionProtoType>()); 10940 10941 CopyConstructor->markUsed(Context); 10942 MarkVTableUsed(CurrentLocation, ClassDecl); 10943 10944 if (ASTMutationListener *L = getASTMutationListener()) { 10945 L->CompletedImplicitDefinition(CopyConstructor); 10946 } 10947 } 10948 10949 Sema::ImplicitExceptionSpecification 10950 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10951 CXXRecordDecl *ClassDecl = MD->getParent(); 10952 10953 // C++ [except.spec]p14: 10954 // An implicitly declared special member function (Clause 12) shall have an 10955 // exception-specification. [...] 10956 ImplicitExceptionSpecification ExceptSpec(*this); 10957 if (ClassDecl->isInvalidDecl()) 10958 return ExceptSpec; 10959 10960 // Direct base-class constructors. 10961 for (const auto &B : ClassDecl->bases()) { 10962 if (B.isVirtual()) // Handled below. 10963 continue; 10964 10965 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10966 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10967 CXXConstructorDecl *Constructor = 10968 LookupMovingConstructor(BaseClassDecl, 0); 10969 // If this is a deleted function, add it anyway. This might be conformant 10970 // with the standard. This might not. I'm not sure. It might not matter. 10971 if (Constructor) 10972 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10973 } 10974 } 10975 10976 // Virtual base-class constructors. 10977 for (const auto &B : ClassDecl->vbases()) { 10978 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10979 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10980 CXXConstructorDecl *Constructor = 10981 LookupMovingConstructor(BaseClassDecl, 0); 10982 // If this is a deleted function, add it anyway. This might be conformant 10983 // with the standard. This might not. I'm not sure. It might not matter. 10984 if (Constructor) 10985 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10986 } 10987 } 10988 10989 // Field constructors. 10990 for (const auto *F : ClassDecl->fields()) { 10991 QualType FieldType = Context.getBaseElementType(F->getType()); 10992 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 10993 CXXConstructorDecl *Constructor = 10994 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 10995 // If this is a deleted function, add it anyway. This might be conformant 10996 // with the standard. This might not. I'm not sure. It might not matter. 10997 // In particular, the problem is that this function never gets called. It 10998 // might just be ill-formed because this function attempts to refer to 10999 // a deleted function here. 11000 if (Constructor) 11001 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 11002 } 11003 } 11004 11005 return ExceptSpec; 11006 } 11007 11008 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 11009 CXXRecordDecl *ClassDecl) { 11010 assert(ClassDecl->needsImplicitMoveConstructor()); 11011 11012 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 11013 if (DSM.isAlreadyBeingDeclared()) 11014 return nullptr; 11015 11016 QualType ClassType = Context.getTypeDeclType(ClassDecl); 11017 QualType ArgType = Context.getRValueReferenceType(ClassType); 11018 11019 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11020 CXXMoveConstructor, 11021 false); 11022 11023 DeclarationName Name 11024 = Context.DeclarationNames.getCXXConstructorName( 11025 Context.getCanonicalType(ClassType)); 11026 SourceLocation ClassLoc = ClassDecl->getLocation(); 11027 DeclarationNameInfo NameInfo(Name, ClassLoc); 11028 11029 // C++11 [class.copy]p11: 11030 // An implicitly-declared copy/move constructor is an inline public 11031 // member of its class. 11032 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 11033 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 11034 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 11035 Constexpr); 11036 MoveConstructor->setAccess(AS_public); 11037 MoveConstructor->setDefaulted(); 11038 11039 if (getLangOpts().CUDA) { 11040 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 11041 MoveConstructor, 11042 /* ConstRHS */ false, 11043 /* Diagnose */ false); 11044 } 11045 11046 // Build an exception specification pointing back at this member. 11047 FunctionProtoType::ExtProtoInfo EPI = 11048 getImplicitMethodEPI(*this, MoveConstructor); 11049 MoveConstructor->setType( 11050 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 11051 11052 // Add the parameter to the constructor. 11053 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 11054 ClassLoc, ClassLoc, 11055 /*IdentifierInfo=*/nullptr, 11056 ArgType, /*TInfo=*/nullptr, 11057 SC_None, nullptr); 11058 MoveConstructor->setParams(FromParam); 11059 11060 MoveConstructor->setTrivial( 11061 ClassDecl->needsOverloadResolutionForMoveConstructor() 11062 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 11063 : ClassDecl->hasTrivialMoveConstructor()); 11064 11065 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 11066 ClassDecl->setImplicitMoveConstructorIsDeleted(); 11067 SetDeclDeleted(MoveConstructor, ClassLoc); 11068 } 11069 11070 // Note that we have declared this constructor. 11071 ++ASTContext::NumImplicitMoveConstructorsDeclared; 11072 11073 if (Scope *S = getScopeForContext(ClassDecl)) 11074 PushOnScopeChains(MoveConstructor, S, false); 11075 ClassDecl->addDecl(MoveConstructor); 11076 11077 return MoveConstructor; 11078 } 11079 11080 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 11081 CXXConstructorDecl *MoveConstructor) { 11082 assert((MoveConstructor->isDefaulted() && 11083 MoveConstructor->isMoveConstructor() && 11084 !MoveConstructor->doesThisDeclarationHaveABody() && 11085 !MoveConstructor->isDeleted()) && 11086 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 11087 11088 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 11089 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 11090 11091 SynthesizedFunctionScope Scope(*this, MoveConstructor); 11092 DiagnosticErrorTrap Trap(Diags); 11093 11094 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 11095 Trap.hasErrorOccurred()) { 11096 Diag(CurrentLocation, diag::note_member_synthesized_at) 11097 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 11098 MoveConstructor->setInvalidDecl(); 11099 } else { 11100 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 11101 ? MoveConstructor->getLocEnd() 11102 : MoveConstructor->getLocation(); 11103 Sema::CompoundScopeRAII CompoundScope(*this); 11104 MoveConstructor->setBody(ActOnCompoundStmt( 11105 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 11106 } 11107 11108 // The exception specification is needed because we are defining the 11109 // function. 11110 ResolveExceptionSpec(CurrentLocation, 11111 MoveConstructor->getType()->castAs<FunctionProtoType>()); 11112 11113 MoveConstructor->markUsed(Context); 11114 MarkVTableUsed(CurrentLocation, ClassDecl); 11115 11116 if (ASTMutationListener *L = getASTMutationListener()) { 11117 L->CompletedImplicitDefinition(MoveConstructor); 11118 } 11119 } 11120 11121 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 11122 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 11123 } 11124 11125 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 11126 SourceLocation CurrentLocation, 11127 CXXConversionDecl *Conv) { 11128 CXXRecordDecl *Lambda = Conv->getParent(); 11129 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 11130 // If we are defining a specialization of a conversion to function-ptr 11131 // cache the deduced template arguments for this specialization 11132 // so that we can use them to retrieve the corresponding call-operator 11133 // and static-invoker. 11134 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 11135 11136 // Retrieve the corresponding call-operator specialization. 11137 if (Lambda->isGenericLambda()) { 11138 assert(Conv->isFunctionTemplateSpecialization()); 11139 FunctionTemplateDecl *CallOpTemplate = 11140 CallOp->getDescribedFunctionTemplate(); 11141 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 11142 void *InsertPos = nullptr; 11143 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 11144 DeducedTemplateArgs->asArray(), 11145 InsertPos); 11146 assert(CallOpSpec && 11147 "Conversion operator must have a corresponding call operator"); 11148 CallOp = cast<CXXMethodDecl>(CallOpSpec); 11149 } 11150 // Mark the call operator referenced (and add to pending instantiations 11151 // if necessary). 11152 // For both the conversion and static-invoker template specializations 11153 // we construct their body's in this function, so no need to add them 11154 // to the PendingInstantiations. 11155 MarkFunctionReferenced(CurrentLocation, CallOp); 11156 11157 SynthesizedFunctionScope Scope(*this, Conv); 11158 DiagnosticErrorTrap Trap(Diags); 11159 11160 // Retrieve the static invoker... 11161 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 11162 // ... and get the corresponding specialization for a generic lambda. 11163 if (Lambda->isGenericLambda()) { 11164 assert(DeducedTemplateArgs && 11165 "Must have deduced template arguments from Conversion Operator"); 11166 FunctionTemplateDecl *InvokeTemplate = 11167 Invoker->getDescribedFunctionTemplate(); 11168 void *InsertPos = nullptr; 11169 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 11170 DeducedTemplateArgs->asArray(), 11171 InsertPos); 11172 assert(InvokeSpec && 11173 "Must have a corresponding static invoker specialization"); 11174 Invoker = cast<CXXMethodDecl>(InvokeSpec); 11175 } 11176 // Construct the body of the conversion function { return __invoke; }. 11177 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 11178 VK_LValue, Conv->getLocation()).get(); 11179 assert(FunctionRef && "Can't refer to __invoke function?"); 11180 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 11181 Conv->setBody(new (Context) CompoundStmt(Context, Return, 11182 Conv->getLocation(), 11183 Conv->getLocation())); 11184 11185 Conv->markUsed(Context); 11186 Conv->setReferenced(); 11187 11188 // Fill in the __invoke function with a dummy implementation. IR generation 11189 // will fill in the actual details. 11190 Invoker->markUsed(Context); 11191 Invoker->setReferenced(); 11192 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 11193 11194 if (ASTMutationListener *L = getASTMutationListener()) { 11195 L->CompletedImplicitDefinition(Conv); 11196 L->CompletedImplicitDefinition(Invoker); 11197 } 11198 } 11199 11200 11201 11202 void Sema::DefineImplicitLambdaToBlockPointerConversion( 11203 SourceLocation CurrentLocation, 11204 CXXConversionDecl *Conv) 11205 { 11206 assert(!Conv->getParent()->isGenericLambda()); 11207 11208 Conv->markUsed(Context); 11209 11210 SynthesizedFunctionScope Scope(*this, Conv); 11211 DiagnosticErrorTrap Trap(Diags); 11212 11213 // Copy-initialize the lambda object as needed to capture it. 11214 Expr *This = ActOnCXXThis(CurrentLocation).get(); 11215 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 11216 11217 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 11218 Conv->getLocation(), 11219 Conv, DerefThis); 11220 11221 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 11222 // behavior. Note that only the general conversion function does this 11223 // (since it's unusable otherwise); in the case where we inline the 11224 // block literal, it has block literal lifetime semantics. 11225 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 11226 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 11227 CK_CopyAndAutoreleaseBlockObject, 11228 BuildBlock.get(), nullptr, VK_RValue); 11229 11230 if (BuildBlock.isInvalid()) { 11231 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11232 Conv->setInvalidDecl(); 11233 return; 11234 } 11235 11236 // Create the return statement that returns the block from the conversion 11237 // function. 11238 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 11239 if (Return.isInvalid()) { 11240 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11241 Conv->setInvalidDecl(); 11242 return; 11243 } 11244 11245 // Set the body of the conversion function. 11246 Stmt *ReturnS = Return.get(); 11247 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 11248 Conv->getLocation(), 11249 Conv->getLocation())); 11250 11251 // We're done; notify the mutation listener, if any. 11252 if (ASTMutationListener *L = getASTMutationListener()) { 11253 L->CompletedImplicitDefinition(Conv); 11254 } 11255 } 11256 11257 /// \brief Determine whether the given list arguments contains exactly one 11258 /// "real" (non-default) argument. 11259 static bool hasOneRealArgument(MultiExprArg Args) { 11260 switch (Args.size()) { 11261 case 0: 11262 return false; 11263 11264 default: 11265 if (!Args[1]->isDefaultArgument()) 11266 return false; 11267 11268 // fall through 11269 case 1: 11270 return !Args[0]->isDefaultArgument(); 11271 } 11272 11273 return false; 11274 } 11275 11276 ExprResult 11277 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11278 CXXConstructorDecl *Constructor, 11279 MultiExprArg ExprArgs, 11280 bool HadMultipleCandidates, 11281 bool IsListInitialization, 11282 bool IsStdInitListInitialization, 11283 bool RequiresZeroInit, 11284 unsigned ConstructKind, 11285 SourceRange ParenRange) { 11286 bool Elidable = false; 11287 11288 // C++0x [class.copy]p34: 11289 // When certain criteria are met, an implementation is allowed to 11290 // omit the copy/move construction of a class object, even if the 11291 // copy/move constructor and/or destructor for the object have 11292 // side effects. [...] 11293 // - when a temporary class object that has not been bound to a 11294 // reference (12.2) would be copied/moved to a class object 11295 // with the same cv-unqualified type, the copy/move operation 11296 // can be omitted by constructing the temporary object 11297 // directly into the target of the omitted copy/move 11298 if (ConstructKind == CXXConstructExpr::CK_Complete && 11299 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 11300 Expr *SubExpr = ExprArgs[0]; 11301 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 11302 } 11303 11304 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 11305 Elidable, ExprArgs, HadMultipleCandidates, 11306 IsListInitialization, 11307 IsStdInitListInitialization, RequiresZeroInit, 11308 ConstructKind, ParenRange); 11309 } 11310 11311 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 11312 /// including handling of its default argument expressions. 11313 ExprResult 11314 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11315 CXXConstructorDecl *Constructor, bool Elidable, 11316 MultiExprArg ExprArgs, 11317 bool HadMultipleCandidates, 11318 bool IsListInitialization, 11319 bool IsStdInitListInitialization, 11320 bool RequiresZeroInit, 11321 unsigned ConstructKind, 11322 SourceRange ParenRange) { 11323 MarkFunctionReferenced(ConstructLoc, Constructor); 11324 return CXXConstructExpr::Create( 11325 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 11326 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 11327 RequiresZeroInit, 11328 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 11329 ParenRange); 11330 } 11331 11332 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 11333 assert(Field->hasInClassInitializer()); 11334 11335 // If we already have the in-class initializer nothing needs to be done. 11336 if (Field->getInClassInitializer()) 11337 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11338 11339 // Maybe we haven't instantiated the in-class initializer. Go check the 11340 // pattern FieldDecl to see if it has one. 11341 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 11342 11343 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 11344 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 11345 DeclContext::lookup_result Lookup = 11346 ClassPattern->lookup(Field->getDeclName()); 11347 assert(Lookup.size() == 1); 11348 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]); 11349 if (InstantiateInClassInitializer(Loc, Field, Pattern, 11350 getTemplateInstantiationArgs(Field))) 11351 return ExprError(); 11352 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11353 } 11354 11355 // DR1351: 11356 // If the brace-or-equal-initializer of a non-static data member 11357 // invokes a defaulted default constructor of its class or of an 11358 // enclosing class in a potentially evaluated subexpression, the 11359 // program is ill-formed. 11360 // 11361 // This resolution is unworkable: the exception specification of the 11362 // default constructor can be needed in an unevaluated context, in 11363 // particular, in the operand of a noexcept-expression, and we can be 11364 // unable to compute an exception specification for an enclosed class. 11365 // 11366 // Any attempt to resolve the exception specification of a defaulted default 11367 // constructor before the initializer is lexically complete will ultimately 11368 // come here at which point we can diagnose it. 11369 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 11370 if (OutermostClass == ParentRD) { 11371 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed) 11372 << ParentRD << Field; 11373 } else { 11374 Diag(Field->getLocEnd(), 11375 diag::err_in_class_initializer_not_yet_parsed_outer_class) 11376 << ParentRD << OutermostClass << Field; 11377 } 11378 11379 return ExprError(); 11380 } 11381 11382 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 11383 if (VD->isInvalidDecl()) return; 11384 11385 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 11386 if (ClassDecl->isInvalidDecl()) return; 11387 if (ClassDecl->hasIrrelevantDestructor()) return; 11388 if (ClassDecl->isDependentContext()) return; 11389 11390 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 11391 MarkFunctionReferenced(VD->getLocation(), Destructor); 11392 CheckDestructorAccess(VD->getLocation(), Destructor, 11393 PDiag(diag::err_access_dtor_var) 11394 << VD->getDeclName() 11395 << VD->getType()); 11396 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 11397 11398 if (Destructor->isTrivial()) return; 11399 if (!VD->hasGlobalStorage()) return; 11400 11401 // Emit warning for non-trivial dtor in global scope (a real global, 11402 // class-static, function-static). 11403 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 11404 11405 // TODO: this should be re-enabled for static locals by !CXAAtExit 11406 if (!VD->isStaticLocal()) 11407 Diag(VD->getLocation(), diag::warn_global_destructor); 11408 } 11409 11410 /// \brief Given a constructor and the set of arguments provided for the 11411 /// constructor, convert the arguments and add any required default arguments 11412 /// to form a proper call to this constructor. 11413 /// 11414 /// \returns true if an error occurred, false otherwise. 11415 bool 11416 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 11417 MultiExprArg ArgsPtr, 11418 SourceLocation Loc, 11419 SmallVectorImpl<Expr*> &ConvertedArgs, 11420 bool AllowExplicit, 11421 bool IsListInitialization) { 11422 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 11423 unsigned NumArgs = ArgsPtr.size(); 11424 Expr **Args = ArgsPtr.data(); 11425 11426 const FunctionProtoType *Proto 11427 = Constructor->getType()->getAs<FunctionProtoType>(); 11428 assert(Proto && "Constructor without a prototype?"); 11429 unsigned NumParams = Proto->getNumParams(); 11430 11431 // If too few arguments are available, we'll fill in the rest with defaults. 11432 if (NumArgs < NumParams) 11433 ConvertedArgs.reserve(NumParams); 11434 else 11435 ConvertedArgs.reserve(NumArgs); 11436 11437 VariadicCallType CallType = 11438 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 11439 SmallVector<Expr *, 8> AllArgs; 11440 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 11441 Proto, 0, 11442 llvm::makeArrayRef(Args, NumArgs), 11443 AllArgs, 11444 CallType, AllowExplicit, 11445 IsListInitialization); 11446 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 11447 11448 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 11449 11450 CheckConstructorCall(Constructor, 11451 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 11452 Proto, Loc); 11453 11454 return Invalid; 11455 } 11456 11457 static inline bool 11458 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 11459 const FunctionDecl *FnDecl) { 11460 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 11461 if (isa<NamespaceDecl>(DC)) { 11462 return SemaRef.Diag(FnDecl->getLocation(), 11463 diag::err_operator_new_delete_declared_in_namespace) 11464 << FnDecl->getDeclName(); 11465 } 11466 11467 if (isa<TranslationUnitDecl>(DC) && 11468 FnDecl->getStorageClass() == SC_Static) { 11469 return SemaRef.Diag(FnDecl->getLocation(), 11470 diag::err_operator_new_delete_declared_static) 11471 << FnDecl->getDeclName(); 11472 } 11473 11474 return false; 11475 } 11476 11477 static inline bool 11478 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 11479 CanQualType ExpectedResultType, 11480 CanQualType ExpectedFirstParamType, 11481 unsigned DependentParamTypeDiag, 11482 unsigned InvalidParamTypeDiag) { 11483 QualType ResultType = 11484 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 11485 11486 // Check that the result type is not dependent. 11487 if (ResultType->isDependentType()) 11488 return SemaRef.Diag(FnDecl->getLocation(), 11489 diag::err_operator_new_delete_dependent_result_type) 11490 << FnDecl->getDeclName() << ExpectedResultType; 11491 11492 // Check that the result type is what we expect. 11493 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 11494 return SemaRef.Diag(FnDecl->getLocation(), 11495 diag::err_operator_new_delete_invalid_result_type) 11496 << FnDecl->getDeclName() << ExpectedResultType; 11497 11498 // A function template must have at least 2 parameters. 11499 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 11500 return SemaRef.Diag(FnDecl->getLocation(), 11501 diag::err_operator_new_delete_template_too_few_parameters) 11502 << FnDecl->getDeclName(); 11503 11504 // The function decl must have at least 1 parameter. 11505 if (FnDecl->getNumParams() == 0) 11506 return SemaRef.Diag(FnDecl->getLocation(), 11507 diag::err_operator_new_delete_too_few_parameters) 11508 << FnDecl->getDeclName(); 11509 11510 // Check the first parameter type is not dependent. 11511 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 11512 if (FirstParamType->isDependentType()) 11513 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 11514 << FnDecl->getDeclName() << ExpectedFirstParamType; 11515 11516 // Check that the first parameter type is what we expect. 11517 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 11518 ExpectedFirstParamType) 11519 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 11520 << FnDecl->getDeclName() << ExpectedFirstParamType; 11521 11522 return false; 11523 } 11524 11525 static bool 11526 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 11527 // C++ [basic.stc.dynamic.allocation]p1: 11528 // A program is ill-formed if an allocation function is declared in a 11529 // namespace scope other than global scope or declared static in global 11530 // scope. 11531 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11532 return true; 11533 11534 CanQualType SizeTy = 11535 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 11536 11537 // C++ [basic.stc.dynamic.allocation]p1: 11538 // The return type shall be void*. The first parameter shall have type 11539 // std::size_t. 11540 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 11541 SizeTy, 11542 diag::err_operator_new_dependent_param_type, 11543 diag::err_operator_new_param_type)) 11544 return true; 11545 11546 // C++ [basic.stc.dynamic.allocation]p1: 11547 // The first parameter shall not have an associated default argument. 11548 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 11549 return SemaRef.Diag(FnDecl->getLocation(), 11550 diag::err_operator_new_default_arg) 11551 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 11552 11553 return false; 11554 } 11555 11556 static bool 11557 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 11558 // C++ [basic.stc.dynamic.deallocation]p1: 11559 // A program is ill-formed if deallocation functions are declared in a 11560 // namespace scope other than global scope or declared static in global 11561 // scope. 11562 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11563 return true; 11564 11565 // C++ [basic.stc.dynamic.deallocation]p2: 11566 // Each deallocation function shall return void and its first parameter 11567 // shall be void*. 11568 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 11569 SemaRef.Context.VoidPtrTy, 11570 diag::err_operator_delete_dependent_param_type, 11571 diag::err_operator_delete_param_type)) 11572 return true; 11573 11574 return false; 11575 } 11576 11577 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 11578 /// of this overloaded operator is well-formed. If so, returns false; 11579 /// otherwise, emits appropriate diagnostics and returns true. 11580 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 11581 assert(FnDecl && FnDecl->isOverloadedOperator() && 11582 "Expected an overloaded operator declaration"); 11583 11584 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 11585 11586 // C++ [over.oper]p5: 11587 // The allocation and deallocation functions, operator new, 11588 // operator new[], operator delete and operator delete[], are 11589 // described completely in 3.7.3. The attributes and restrictions 11590 // found in the rest of this subclause do not apply to them unless 11591 // explicitly stated in 3.7.3. 11592 if (Op == OO_Delete || Op == OO_Array_Delete) 11593 return CheckOperatorDeleteDeclaration(*this, FnDecl); 11594 11595 if (Op == OO_New || Op == OO_Array_New) 11596 return CheckOperatorNewDeclaration(*this, FnDecl); 11597 11598 // C++ [over.oper]p6: 11599 // An operator function shall either be a non-static member 11600 // function or be a non-member function and have at least one 11601 // parameter whose type is a class, a reference to a class, an 11602 // enumeration, or a reference to an enumeration. 11603 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 11604 if (MethodDecl->isStatic()) 11605 return Diag(FnDecl->getLocation(), 11606 diag::err_operator_overload_static) << FnDecl->getDeclName(); 11607 } else { 11608 bool ClassOrEnumParam = false; 11609 for (auto Param : FnDecl->params()) { 11610 QualType ParamType = Param->getType().getNonReferenceType(); 11611 if (ParamType->isDependentType() || ParamType->isRecordType() || 11612 ParamType->isEnumeralType()) { 11613 ClassOrEnumParam = true; 11614 break; 11615 } 11616 } 11617 11618 if (!ClassOrEnumParam) 11619 return Diag(FnDecl->getLocation(), 11620 diag::err_operator_overload_needs_class_or_enum) 11621 << FnDecl->getDeclName(); 11622 } 11623 11624 // C++ [over.oper]p8: 11625 // An operator function cannot have default arguments (8.3.6), 11626 // except where explicitly stated below. 11627 // 11628 // Only the function-call operator allows default arguments 11629 // (C++ [over.call]p1). 11630 if (Op != OO_Call) { 11631 for (auto Param : FnDecl->params()) { 11632 if (Param->hasDefaultArg()) 11633 return Diag(Param->getLocation(), 11634 diag::err_operator_overload_default_arg) 11635 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 11636 } 11637 } 11638 11639 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 11640 { false, false, false } 11641 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 11642 , { Unary, Binary, MemberOnly } 11643 #include "clang/Basic/OperatorKinds.def" 11644 }; 11645 11646 bool CanBeUnaryOperator = OperatorUses[Op][0]; 11647 bool CanBeBinaryOperator = OperatorUses[Op][1]; 11648 bool MustBeMemberOperator = OperatorUses[Op][2]; 11649 11650 // C++ [over.oper]p8: 11651 // [...] Operator functions cannot have more or fewer parameters 11652 // than the number required for the corresponding operator, as 11653 // described in the rest of this subclause. 11654 unsigned NumParams = FnDecl->getNumParams() 11655 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 11656 if (Op != OO_Call && 11657 ((NumParams == 1 && !CanBeUnaryOperator) || 11658 (NumParams == 2 && !CanBeBinaryOperator) || 11659 (NumParams < 1) || (NumParams > 2))) { 11660 // We have the wrong number of parameters. 11661 unsigned ErrorKind; 11662 if (CanBeUnaryOperator && CanBeBinaryOperator) { 11663 ErrorKind = 2; // 2 -> unary or binary. 11664 } else if (CanBeUnaryOperator) { 11665 ErrorKind = 0; // 0 -> unary 11666 } else { 11667 assert(CanBeBinaryOperator && 11668 "All non-call overloaded operators are unary or binary!"); 11669 ErrorKind = 1; // 1 -> binary 11670 } 11671 11672 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 11673 << FnDecl->getDeclName() << NumParams << ErrorKind; 11674 } 11675 11676 // Overloaded operators other than operator() cannot be variadic. 11677 if (Op != OO_Call && 11678 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 11679 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 11680 << FnDecl->getDeclName(); 11681 } 11682 11683 // Some operators must be non-static member functions. 11684 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 11685 return Diag(FnDecl->getLocation(), 11686 diag::err_operator_overload_must_be_member) 11687 << FnDecl->getDeclName(); 11688 } 11689 11690 // C++ [over.inc]p1: 11691 // The user-defined function called operator++ implements the 11692 // prefix and postfix ++ operator. If this function is a member 11693 // function with no parameters, or a non-member function with one 11694 // parameter of class or enumeration type, it defines the prefix 11695 // increment operator ++ for objects of that type. If the function 11696 // is a member function with one parameter (which shall be of type 11697 // int) or a non-member function with two parameters (the second 11698 // of which shall be of type int), it defines the postfix 11699 // increment operator ++ for objects of that type. 11700 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 11701 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 11702 QualType ParamType = LastParam->getType(); 11703 11704 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 11705 !ParamType->isDependentType()) 11706 return Diag(LastParam->getLocation(), 11707 diag::err_operator_overload_post_incdec_must_be_int) 11708 << LastParam->getType() << (Op == OO_MinusMinus); 11709 } 11710 11711 return false; 11712 } 11713 11714 /// CheckLiteralOperatorDeclaration - Check whether the declaration 11715 /// of this literal operator function is well-formed. If so, returns 11716 /// false; otherwise, emits appropriate diagnostics and returns true. 11717 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 11718 if (isa<CXXMethodDecl>(FnDecl)) { 11719 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 11720 << FnDecl->getDeclName(); 11721 return true; 11722 } 11723 11724 if (FnDecl->isExternC()) { 11725 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 11726 return true; 11727 } 11728 11729 bool Valid = false; 11730 11731 // This might be the definition of a literal operator template. 11732 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 11733 // This might be a specialization of a literal operator template. 11734 if (!TpDecl) 11735 TpDecl = FnDecl->getPrimaryTemplate(); 11736 11737 // template <char...> type operator "" name() and 11738 // template <class T, T...> type operator "" name() are the only valid 11739 // template signatures, and the only valid signatures with no parameters. 11740 if (TpDecl) { 11741 if (FnDecl->param_size() == 0) { 11742 // Must have one or two template parameters 11743 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 11744 if (Params->size() == 1) { 11745 NonTypeTemplateParmDecl *PmDecl = 11746 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 11747 11748 // The template parameter must be a char parameter pack. 11749 if (PmDecl && PmDecl->isTemplateParameterPack() && 11750 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 11751 Valid = true; 11752 } else if (Params->size() == 2) { 11753 TemplateTypeParmDecl *PmType = 11754 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 11755 NonTypeTemplateParmDecl *PmArgs = 11756 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 11757 11758 // The second template parameter must be a parameter pack with the 11759 // first template parameter as its type. 11760 if (PmType && PmArgs && 11761 !PmType->isTemplateParameterPack() && 11762 PmArgs->isTemplateParameterPack()) { 11763 const TemplateTypeParmType *TArgs = 11764 PmArgs->getType()->getAs<TemplateTypeParmType>(); 11765 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 11766 TArgs->getIndex() == PmType->getIndex()) { 11767 Valid = true; 11768 if (ActiveTemplateInstantiations.empty()) 11769 Diag(FnDecl->getLocation(), 11770 diag::ext_string_literal_operator_template); 11771 } 11772 } 11773 } 11774 } 11775 } else if (FnDecl->param_size()) { 11776 // Check the first parameter 11777 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 11778 11779 QualType T = (*Param)->getType().getUnqualifiedType(); 11780 11781 // unsigned long long int, long double, and any character type are allowed 11782 // as the only parameters. 11783 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 11784 Context.hasSameType(T, Context.LongDoubleTy) || 11785 Context.hasSameType(T, Context.CharTy) || 11786 Context.hasSameType(T, Context.WideCharTy) || 11787 Context.hasSameType(T, Context.Char16Ty) || 11788 Context.hasSameType(T, Context.Char32Ty)) { 11789 if (++Param == FnDecl->param_end()) 11790 Valid = true; 11791 goto FinishedParams; 11792 } 11793 11794 // Otherwise it must be a pointer to const; let's strip those qualifiers. 11795 const PointerType *PT = T->getAs<PointerType>(); 11796 if (!PT) 11797 goto FinishedParams; 11798 T = PT->getPointeeType(); 11799 if (!T.isConstQualified() || T.isVolatileQualified()) 11800 goto FinishedParams; 11801 T = T.getUnqualifiedType(); 11802 11803 // Move on to the second parameter; 11804 ++Param; 11805 11806 // If there is no second parameter, the first must be a const char * 11807 if (Param == FnDecl->param_end()) { 11808 if (Context.hasSameType(T, Context.CharTy)) 11809 Valid = true; 11810 goto FinishedParams; 11811 } 11812 11813 // const char *, const wchar_t*, const char16_t*, and const char32_t* 11814 // are allowed as the first parameter to a two-parameter function 11815 if (!(Context.hasSameType(T, Context.CharTy) || 11816 Context.hasSameType(T, Context.WideCharTy) || 11817 Context.hasSameType(T, Context.Char16Ty) || 11818 Context.hasSameType(T, Context.Char32Ty))) 11819 goto FinishedParams; 11820 11821 // The second and final parameter must be an std::size_t 11822 T = (*Param)->getType().getUnqualifiedType(); 11823 if (Context.hasSameType(T, Context.getSizeType()) && 11824 ++Param == FnDecl->param_end()) 11825 Valid = true; 11826 } 11827 11828 // FIXME: This diagnostic is absolutely terrible. 11829 FinishedParams: 11830 if (!Valid) { 11831 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 11832 << FnDecl->getDeclName(); 11833 return true; 11834 } 11835 11836 // A parameter-declaration-clause containing a default argument is not 11837 // equivalent to any of the permitted forms. 11838 for (auto Param : FnDecl->params()) { 11839 if (Param->hasDefaultArg()) { 11840 Diag(Param->getDefaultArgRange().getBegin(), 11841 diag::err_literal_operator_default_argument) 11842 << Param->getDefaultArgRange(); 11843 break; 11844 } 11845 } 11846 11847 StringRef LiteralName 11848 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11849 if (LiteralName[0] != '_') { 11850 // C++11 [usrlit.suffix]p1: 11851 // Literal suffix identifiers that do not start with an underscore 11852 // are reserved for future standardization. 11853 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11854 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11855 } 11856 11857 return false; 11858 } 11859 11860 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11861 /// linkage specification, including the language and (if present) 11862 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 11863 /// language string literal. LBraceLoc, if valid, provides the location of 11864 /// the '{' brace. Otherwise, this linkage specification does not 11865 /// have any braces. 11866 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11867 Expr *LangStr, 11868 SourceLocation LBraceLoc) { 11869 StringLiteral *Lit = cast<StringLiteral>(LangStr); 11870 if (!Lit->isAscii()) { 11871 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 11872 << LangStr->getSourceRange(); 11873 return nullptr; 11874 } 11875 11876 StringRef Lang = Lit->getString(); 11877 LinkageSpecDecl::LanguageIDs Language; 11878 if (Lang == "C") 11879 Language = LinkageSpecDecl::lang_c; 11880 else if (Lang == "C++") 11881 Language = LinkageSpecDecl::lang_cxx; 11882 else { 11883 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11884 << LangStr->getSourceRange(); 11885 return nullptr; 11886 } 11887 11888 // FIXME: Add all the various semantics of linkage specifications 11889 11890 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11891 LangStr->getExprLoc(), Language, 11892 LBraceLoc.isValid()); 11893 CurContext->addDecl(D); 11894 PushDeclContext(S, D); 11895 return D; 11896 } 11897 11898 /// ActOnFinishLinkageSpecification - Complete the definition of 11899 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11900 /// valid, it's the position of the closing '}' brace in a linkage 11901 /// specification that uses braces. 11902 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11903 Decl *LinkageSpec, 11904 SourceLocation RBraceLoc) { 11905 if (RBraceLoc.isValid()) { 11906 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11907 LSDecl->setRBraceLoc(RBraceLoc); 11908 } 11909 PopDeclContext(); 11910 return LinkageSpec; 11911 } 11912 11913 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11914 AttributeList *AttrList, 11915 SourceLocation SemiLoc) { 11916 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11917 // Attribute declarations appertain to empty declaration so we handle 11918 // them here. 11919 if (AttrList) 11920 ProcessDeclAttributeList(S, ED, AttrList); 11921 11922 CurContext->addDecl(ED); 11923 return ED; 11924 } 11925 11926 /// \brief Perform semantic analysis for the variable declaration that 11927 /// occurs within a C++ catch clause, returning the newly-created 11928 /// variable. 11929 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11930 TypeSourceInfo *TInfo, 11931 SourceLocation StartLoc, 11932 SourceLocation Loc, 11933 IdentifierInfo *Name) { 11934 bool Invalid = false; 11935 QualType ExDeclType = TInfo->getType(); 11936 11937 // Arrays and functions decay. 11938 if (ExDeclType->isArrayType()) 11939 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11940 else if (ExDeclType->isFunctionType()) 11941 ExDeclType = Context.getPointerType(ExDeclType); 11942 11943 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11944 // The exception-declaration shall not denote a pointer or reference to an 11945 // incomplete type, other than [cv] void*. 11946 // N2844 forbids rvalue references. 11947 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11948 Diag(Loc, diag::err_catch_rvalue_ref); 11949 Invalid = true; 11950 } 11951 11952 QualType BaseType = ExDeclType; 11953 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11954 unsigned DK = diag::err_catch_incomplete; 11955 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11956 BaseType = Ptr->getPointeeType(); 11957 Mode = 1; 11958 DK = diag::err_catch_incomplete_ptr; 11959 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11960 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11961 BaseType = Ref->getPointeeType(); 11962 Mode = 2; 11963 DK = diag::err_catch_incomplete_ref; 11964 } 11965 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11966 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11967 Invalid = true; 11968 11969 if (!Invalid && !ExDeclType->isDependentType() && 11970 RequireNonAbstractType(Loc, ExDeclType, 11971 diag::err_abstract_type_in_decl, 11972 AbstractVariableType)) 11973 Invalid = true; 11974 11975 // Only the non-fragile NeXT runtime currently supports C++ catches 11976 // of ObjC types, and no runtime supports catching ObjC types by value. 11977 if (!Invalid && getLangOpts().ObjC1) { 11978 QualType T = ExDeclType; 11979 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11980 T = RT->getPointeeType(); 11981 11982 if (T->isObjCObjectType()) { 11983 Diag(Loc, diag::err_objc_object_catch); 11984 Invalid = true; 11985 } else if (T->isObjCObjectPointerType()) { 11986 // FIXME: should this be a test for macosx-fragile specifically? 11987 if (getLangOpts().ObjCRuntime.isFragile()) 11988 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 11989 } 11990 } 11991 11992 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 11993 ExDeclType, TInfo, SC_None); 11994 ExDecl->setExceptionVariable(true); 11995 11996 // In ARC, infer 'retaining' for variables of retainable type. 11997 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 11998 Invalid = true; 11999 12000 if (!Invalid && !ExDeclType->isDependentType()) { 12001 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 12002 // Insulate this from anything else we might currently be parsing. 12003 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 12004 12005 // C++ [except.handle]p16: 12006 // The object declared in an exception-declaration or, if the 12007 // exception-declaration does not specify a name, a temporary (12.2) is 12008 // copy-initialized (8.5) from the exception object. [...] 12009 // The object is destroyed when the handler exits, after the destruction 12010 // of any automatic objects initialized within the handler. 12011 // 12012 // We just pretend to initialize the object with itself, then make sure 12013 // it can be destroyed later. 12014 QualType initType = Context.getExceptionObjectType(ExDeclType); 12015 12016 InitializedEntity entity = 12017 InitializedEntity::InitializeVariable(ExDecl); 12018 InitializationKind initKind = 12019 InitializationKind::CreateCopy(Loc, SourceLocation()); 12020 12021 Expr *opaqueValue = 12022 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 12023 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 12024 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 12025 if (result.isInvalid()) 12026 Invalid = true; 12027 else { 12028 // If the constructor used was non-trivial, set this as the 12029 // "initializer". 12030 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 12031 if (!construct->getConstructor()->isTrivial()) { 12032 Expr *init = MaybeCreateExprWithCleanups(construct); 12033 ExDecl->setInit(init); 12034 } 12035 12036 // And make sure it's destructable. 12037 FinalizeVarWithDestructor(ExDecl, recordType); 12038 } 12039 } 12040 } 12041 12042 if (Invalid) 12043 ExDecl->setInvalidDecl(); 12044 12045 return ExDecl; 12046 } 12047 12048 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 12049 /// handler. 12050 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 12051 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12052 bool Invalid = D.isInvalidType(); 12053 12054 // Check for unexpanded parameter packs. 12055 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12056 UPPC_ExceptionType)) { 12057 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12058 D.getIdentifierLoc()); 12059 Invalid = true; 12060 } 12061 12062 IdentifierInfo *II = D.getIdentifier(); 12063 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 12064 LookupOrdinaryName, 12065 ForRedeclaration)) { 12066 // The scope should be freshly made just for us. There is just no way 12067 // it contains any previous declaration, except for function parameters in 12068 // a function-try-block's catch statement. 12069 assert(!S->isDeclScope(PrevDecl)); 12070 if (isDeclInScope(PrevDecl, CurContext, S)) { 12071 Diag(D.getIdentifierLoc(), diag::err_redefinition) 12072 << D.getIdentifier(); 12073 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12074 Invalid = true; 12075 } else if (PrevDecl->isTemplateParameter()) 12076 // Maybe we will complain about the shadowed template parameter. 12077 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12078 } 12079 12080 if (D.getCXXScopeSpec().isSet() && !Invalid) { 12081 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 12082 << D.getCXXScopeSpec().getRange(); 12083 Invalid = true; 12084 } 12085 12086 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 12087 D.getLocStart(), 12088 D.getIdentifierLoc(), 12089 D.getIdentifier()); 12090 if (Invalid) 12091 ExDecl->setInvalidDecl(); 12092 12093 // Add the exception declaration into this scope. 12094 if (II) 12095 PushOnScopeChains(ExDecl, S); 12096 else 12097 CurContext->addDecl(ExDecl); 12098 12099 ProcessDeclAttributes(S, ExDecl, D); 12100 return ExDecl; 12101 } 12102 12103 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 12104 Expr *AssertExpr, 12105 Expr *AssertMessageExpr, 12106 SourceLocation RParenLoc) { 12107 StringLiteral *AssertMessage = 12108 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 12109 12110 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 12111 return nullptr; 12112 12113 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 12114 AssertMessage, RParenLoc, false); 12115 } 12116 12117 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 12118 Expr *AssertExpr, 12119 StringLiteral *AssertMessage, 12120 SourceLocation RParenLoc, 12121 bool Failed) { 12122 assert(AssertExpr != nullptr && "Expected non-null condition"); 12123 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 12124 !Failed) { 12125 // In a static_assert-declaration, the constant-expression shall be a 12126 // constant expression that can be contextually converted to bool. 12127 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 12128 if (Converted.isInvalid()) 12129 Failed = true; 12130 12131 llvm::APSInt Cond; 12132 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 12133 diag::err_static_assert_expression_is_not_constant, 12134 /*AllowFold=*/false).isInvalid()) 12135 Failed = true; 12136 12137 if (!Failed && !Cond) { 12138 SmallString<256> MsgBuffer; 12139 llvm::raw_svector_ostream Msg(MsgBuffer); 12140 if (AssertMessage) 12141 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 12142 Diag(StaticAssertLoc, diag::err_static_assert_failed) 12143 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 12144 Failed = true; 12145 } 12146 } 12147 12148 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 12149 AssertExpr, AssertMessage, RParenLoc, 12150 Failed); 12151 12152 CurContext->addDecl(Decl); 12153 return Decl; 12154 } 12155 12156 /// \brief Perform semantic analysis of the given friend type declaration. 12157 /// 12158 /// \returns A friend declaration that. 12159 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 12160 SourceLocation FriendLoc, 12161 TypeSourceInfo *TSInfo) { 12162 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 12163 12164 QualType T = TSInfo->getType(); 12165 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 12166 12167 // C++03 [class.friend]p2: 12168 // An elaborated-type-specifier shall be used in a friend declaration 12169 // for a class.* 12170 // 12171 // * The class-key of the elaborated-type-specifier is required. 12172 if (!ActiveTemplateInstantiations.empty()) { 12173 // Do not complain about the form of friend template types during 12174 // template instantiation; we will already have complained when the 12175 // template was declared. 12176 } else { 12177 if (!T->isElaboratedTypeSpecifier()) { 12178 // If we evaluated the type to a record type, suggest putting 12179 // a tag in front. 12180 if (const RecordType *RT = T->getAs<RecordType>()) { 12181 RecordDecl *RD = RT->getDecl(); 12182 12183 SmallString<16> InsertionText(" "); 12184 InsertionText += RD->getKindName(); 12185 12186 Diag(TypeRange.getBegin(), 12187 getLangOpts().CPlusPlus11 ? 12188 diag::warn_cxx98_compat_unelaborated_friend_type : 12189 diag::ext_unelaborated_friend_type) 12190 << (unsigned) RD->getTagKind() 12191 << T 12192 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 12193 InsertionText); 12194 } else { 12195 Diag(FriendLoc, 12196 getLangOpts().CPlusPlus11 ? 12197 diag::warn_cxx98_compat_nonclass_type_friend : 12198 diag::ext_nonclass_type_friend) 12199 << T 12200 << TypeRange; 12201 } 12202 } else if (T->getAs<EnumType>()) { 12203 Diag(FriendLoc, 12204 getLangOpts().CPlusPlus11 ? 12205 diag::warn_cxx98_compat_enum_friend : 12206 diag::ext_enum_friend) 12207 << T 12208 << TypeRange; 12209 } 12210 12211 // C++11 [class.friend]p3: 12212 // A friend declaration that does not declare a function shall have one 12213 // of the following forms: 12214 // friend elaborated-type-specifier ; 12215 // friend simple-type-specifier ; 12216 // friend typename-specifier ; 12217 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 12218 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 12219 } 12220 12221 // If the type specifier in a friend declaration designates a (possibly 12222 // cv-qualified) class type, that class is declared as a friend; otherwise, 12223 // the friend declaration is ignored. 12224 return FriendDecl::Create(Context, CurContext, 12225 TSInfo->getTypeLoc().getLocStart(), TSInfo, 12226 FriendLoc); 12227 } 12228 12229 /// Handle a friend tag declaration where the scope specifier was 12230 /// templated. 12231 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 12232 unsigned TagSpec, SourceLocation TagLoc, 12233 CXXScopeSpec &SS, 12234 IdentifierInfo *Name, 12235 SourceLocation NameLoc, 12236 AttributeList *Attr, 12237 MultiTemplateParamsArg TempParamLists) { 12238 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 12239 12240 bool isExplicitSpecialization = false; 12241 bool Invalid = false; 12242 12243 if (TemplateParameterList *TemplateParams = 12244 MatchTemplateParametersToScopeSpecifier( 12245 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 12246 isExplicitSpecialization, Invalid)) { 12247 if (TemplateParams->size() > 0) { 12248 // This is a declaration of a class template. 12249 if (Invalid) 12250 return nullptr; 12251 12252 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 12253 NameLoc, Attr, TemplateParams, AS_public, 12254 /*ModulePrivateLoc=*/SourceLocation(), 12255 FriendLoc, TempParamLists.size() - 1, 12256 TempParamLists.data()).get(); 12257 } else { 12258 // The "template<>" header is extraneous. 12259 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12260 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12261 isExplicitSpecialization = true; 12262 } 12263 } 12264 12265 if (Invalid) return nullptr; 12266 12267 bool isAllExplicitSpecializations = true; 12268 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 12269 if (TempParamLists[I]->size()) { 12270 isAllExplicitSpecializations = false; 12271 break; 12272 } 12273 } 12274 12275 // FIXME: don't ignore attributes. 12276 12277 // If it's explicit specializations all the way down, just forget 12278 // about the template header and build an appropriate non-templated 12279 // friend. TODO: for source fidelity, remember the headers. 12280 if (isAllExplicitSpecializations) { 12281 if (SS.isEmpty()) { 12282 bool Owned = false; 12283 bool IsDependent = false; 12284 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 12285 Attr, AS_public, 12286 /*ModulePrivateLoc=*/SourceLocation(), 12287 MultiTemplateParamsArg(), Owned, IsDependent, 12288 /*ScopedEnumKWLoc=*/SourceLocation(), 12289 /*ScopedEnumUsesClassTag=*/false, 12290 /*UnderlyingType=*/TypeResult(), 12291 /*IsTypeSpecifier=*/false); 12292 } 12293 12294 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12295 ElaboratedTypeKeyword Keyword 12296 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12297 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 12298 *Name, NameLoc); 12299 if (T.isNull()) 12300 return nullptr; 12301 12302 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12303 if (isa<DependentNameType>(T)) { 12304 DependentNameTypeLoc TL = 12305 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12306 TL.setElaboratedKeywordLoc(TagLoc); 12307 TL.setQualifierLoc(QualifierLoc); 12308 TL.setNameLoc(NameLoc); 12309 } else { 12310 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 12311 TL.setElaboratedKeywordLoc(TagLoc); 12312 TL.setQualifierLoc(QualifierLoc); 12313 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 12314 } 12315 12316 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12317 TSI, FriendLoc, TempParamLists); 12318 Friend->setAccess(AS_public); 12319 CurContext->addDecl(Friend); 12320 return Friend; 12321 } 12322 12323 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 12324 12325 12326 12327 // Handle the case of a templated-scope friend class. e.g. 12328 // template <class T> class A<T>::B; 12329 // FIXME: we don't support these right now. 12330 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 12331 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 12332 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12333 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 12334 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12335 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12336 TL.setElaboratedKeywordLoc(TagLoc); 12337 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 12338 TL.setNameLoc(NameLoc); 12339 12340 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12341 TSI, FriendLoc, TempParamLists); 12342 Friend->setAccess(AS_public); 12343 Friend->setUnsupportedFriend(true); 12344 CurContext->addDecl(Friend); 12345 return Friend; 12346 } 12347 12348 12349 /// Handle a friend type declaration. This works in tandem with 12350 /// ActOnTag. 12351 /// 12352 /// Notes on friend class templates: 12353 /// 12354 /// We generally treat friend class declarations as if they were 12355 /// declaring a class. So, for example, the elaborated type specifier 12356 /// in a friend declaration is required to obey the restrictions of a 12357 /// class-head (i.e. no typedefs in the scope chain), template 12358 /// parameters are required to match up with simple template-ids, &c. 12359 /// However, unlike when declaring a template specialization, it's 12360 /// okay to refer to a template specialization without an empty 12361 /// template parameter declaration, e.g. 12362 /// friend class A<T>::B<unsigned>; 12363 /// We permit this as a special case; if there are any template 12364 /// parameters present at all, require proper matching, i.e. 12365 /// template <> template \<class T> friend class A<int>::B; 12366 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 12367 MultiTemplateParamsArg TempParams) { 12368 SourceLocation Loc = DS.getLocStart(); 12369 12370 assert(DS.isFriendSpecified()); 12371 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12372 12373 // Try to convert the decl specifier to a type. This works for 12374 // friend templates because ActOnTag never produces a ClassTemplateDecl 12375 // for a TUK_Friend. 12376 Declarator TheDeclarator(DS, Declarator::MemberContext); 12377 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 12378 QualType T = TSI->getType(); 12379 if (TheDeclarator.isInvalidType()) 12380 return nullptr; 12381 12382 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 12383 return nullptr; 12384 12385 // This is definitely an error in C++98. It's probably meant to 12386 // be forbidden in C++0x, too, but the specification is just 12387 // poorly written. 12388 // 12389 // The problem is with declarations like the following: 12390 // template <T> friend A<T>::foo; 12391 // where deciding whether a class C is a friend or not now hinges 12392 // on whether there exists an instantiation of A that causes 12393 // 'foo' to equal C. There are restrictions on class-heads 12394 // (which we declare (by fiat) elaborated friend declarations to 12395 // be) that makes this tractable. 12396 // 12397 // FIXME: handle "template <> friend class A<T>;", which 12398 // is possibly well-formed? Who even knows? 12399 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 12400 Diag(Loc, diag::err_tagless_friend_type_template) 12401 << DS.getSourceRange(); 12402 return nullptr; 12403 } 12404 12405 // C++98 [class.friend]p1: A friend of a class is a function 12406 // or class that is not a member of the class . . . 12407 // This is fixed in DR77, which just barely didn't make the C++03 12408 // deadline. It's also a very silly restriction that seriously 12409 // affects inner classes and which nobody else seems to implement; 12410 // thus we never diagnose it, not even in -pedantic. 12411 // 12412 // But note that we could warn about it: it's always useless to 12413 // friend one of your own members (it's not, however, worthless to 12414 // friend a member of an arbitrary specialization of your template). 12415 12416 Decl *D; 12417 if (unsigned NumTempParamLists = TempParams.size()) 12418 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 12419 NumTempParamLists, 12420 TempParams.data(), 12421 TSI, 12422 DS.getFriendSpecLoc()); 12423 else 12424 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 12425 12426 if (!D) 12427 return nullptr; 12428 12429 D->setAccess(AS_public); 12430 CurContext->addDecl(D); 12431 12432 return D; 12433 } 12434 12435 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 12436 MultiTemplateParamsArg TemplateParams) { 12437 const DeclSpec &DS = D.getDeclSpec(); 12438 12439 assert(DS.isFriendSpecified()); 12440 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12441 12442 SourceLocation Loc = D.getIdentifierLoc(); 12443 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12444 12445 // C++ [class.friend]p1 12446 // A friend of a class is a function or class.... 12447 // Note that this sees through typedefs, which is intended. 12448 // It *doesn't* see through dependent types, which is correct 12449 // according to [temp.arg.type]p3: 12450 // If a declaration acquires a function type through a 12451 // type dependent on a template-parameter and this causes 12452 // a declaration that does not use the syntactic form of a 12453 // function declarator to have a function type, the program 12454 // is ill-formed. 12455 if (!TInfo->getType()->isFunctionType()) { 12456 Diag(Loc, diag::err_unexpected_friend); 12457 12458 // It might be worthwhile to try to recover by creating an 12459 // appropriate declaration. 12460 return nullptr; 12461 } 12462 12463 // C++ [namespace.memdef]p3 12464 // - If a friend declaration in a non-local class first declares a 12465 // class or function, the friend class or function is a member 12466 // of the innermost enclosing namespace. 12467 // - The name of the friend is not found by simple name lookup 12468 // until a matching declaration is provided in that namespace 12469 // scope (either before or after the class declaration granting 12470 // friendship). 12471 // - If a friend function is called, its name may be found by the 12472 // name lookup that considers functions from namespaces and 12473 // classes associated with the types of the function arguments. 12474 // - When looking for a prior declaration of a class or a function 12475 // declared as a friend, scopes outside the innermost enclosing 12476 // namespace scope are not considered. 12477 12478 CXXScopeSpec &SS = D.getCXXScopeSpec(); 12479 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 12480 DeclarationName Name = NameInfo.getName(); 12481 assert(Name); 12482 12483 // Check for unexpanded parameter packs. 12484 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 12485 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 12486 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 12487 return nullptr; 12488 12489 // The context we found the declaration in, or in which we should 12490 // create the declaration. 12491 DeclContext *DC; 12492 Scope *DCScope = S; 12493 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12494 ForRedeclaration); 12495 12496 // There are five cases here. 12497 // - There's no scope specifier and we're in a local class. Only look 12498 // for functions declared in the immediately-enclosing block scope. 12499 // We recover from invalid scope qualifiers as if they just weren't there. 12500 FunctionDecl *FunctionContainingLocalClass = nullptr; 12501 if ((SS.isInvalid() || !SS.isSet()) && 12502 (FunctionContainingLocalClass = 12503 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 12504 // C++11 [class.friend]p11: 12505 // If a friend declaration appears in a local class and the name 12506 // specified is an unqualified name, a prior declaration is 12507 // looked up without considering scopes that are outside the 12508 // innermost enclosing non-class scope. For a friend function 12509 // declaration, if there is no prior declaration, the program is 12510 // ill-formed. 12511 12512 // Find the innermost enclosing non-class scope. This is the block 12513 // scope containing the local class definition (or for a nested class, 12514 // the outer local class). 12515 DCScope = S->getFnParent(); 12516 12517 // Look up the function name in the scope. 12518 Previous.clear(LookupLocalFriendName); 12519 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 12520 12521 if (!Previous.empty()) { 12522 // All possible previous declarations must have the same context: 12523 // either they were declared at block scope or they are members of 12524 // one of the enclosing local classes. 12525 DC = Previous.getRepresentativeDecl()->getDeclContext(); 12526 } else { 12527 // This is ill-formed, but provide the context that we would have 12528 // declared the function in, if we were permitted to, for error recovery. 12529 DC = FunctionContainingLocalClass; 12530 } 12531 adjustContextForLocalExternDecl(DC); 12532 12533 // C++ [class.friend]p6: 12534 // A function can be defined in a friend declaration of a class if and 12535 // only if the class is a non-local class (9.8), the function name is 12536 // unqualified, and the function has namespace scope. 12537 if (D.isFunctionDefinition()) { 12538 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 12539 } 12540 12541 // - There's no scope specifier, in which case we just go to the 12542 // appropriate scope and look for a function or function template 12543 // there as appropriate. 12544 } else if (SS.isInvalid() || !SS.isSet()) { 12545 // C++11 [namespace.memdef]p3: 12546 // If the name in a friend declaration is neither qualified nor 12547 // a template-id and the declaration is a function or an 12548 // elaborated-type-specifier, the lookup to determine whether 12549 // the entity has been previously declared shall not consider 12550 // any scopes outside the innermost enclosing namespace. 12551 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 12552 12553 // Find the appropriate context according to the above. 12554 DC = CurContext; 12555 12556 // Skip class contexts. If someone can cite chapter and verse 12557 // for this behavior, that would be nice --- it's what GCC and 12558 // EDG do, and it seems like a reasonable intent, but the spec 12559 // really only says that checks for unqualified existing 12560 // declarations should stop at the nearest enclosing namespace, 12561 // not that they should only consider the nearest enclosing 12562 // namespace. 12563 while (DC->isRecord()) 12564 DC = DC->getParent(); 12565 12566 DeclContext *LookupDC = DC; 12567 while (LookupDC->isTransparentContext()) 12568 LookupDC = LookupDC->getParent(); 12569 12570 while (true) { 12571 LookupQualifiedName(Previous, LookupDC); 12572 12573 if (!Previous.empty()) { 12574 DC = LookupDC; 12575 break; 12576 } 12577 12578 if (isTemplateId) { 12579 if (isa<TranslationUnitDecl>(LookupDC)) break; 12580 } else { 12581 if (LookupDC->isFileContext()) break; 12582 } 12583 LookupDC = LookupDC->getParent(); 12584 } 12585 12586 DCScope = getScopeForDeclContext(S, DC); 12587 12588 // - There's a non-dependent scope specifier, in which case we 12589 // compute it and do a previous lookup there for a function 12590 // or function template. 12591 } else if (!SS.getScopeRep()->isDependent()) { 12592 DC = computeDeclContext(SS); 12593 if (!DC) return nullptr; 12594 12595 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 12596 12597 LookupQualifiedName(Previous, DC); 12598 12599 // Ignore things found implicitly in the wrong scope. 12600 // TODO: better diagnostics for this case. Suggesting the right 12601 // qualified scope would be nice... 12602 LookupResult::Filter F = Previous.makeFilter(); 12603 while (F.hasNext()) { 12604 NamedDecl *D = F.next(); 12605 if (!DC->InEnclosingNamespaceSetOf( 12606 D->getDeclContext()->getRedeclContext())) 12607 F.erase(); 12608 } 12609 F.done(); 12610 12611 if (Previous.empty()) { 12612 D.setInvalidType(); 12613 Diag(Loc, diag::err_qualified_friend_not_found) 12614 << Name << TInfo->getType(); 12615 return nullptr; 12616 } 12617 12618 // C++ [class.friend]p1: A friend of a class is a function or 12619 // class that is not a member of the class . . . 12620 if (DC->Equals(CurContext)) 12621 Diag(DS.getFriendSpecLoc(), 12622 getLangOpts().CPlusPlus11 ? 12623 diag::warn_cxx98_compat_friend_is_member : 12624 diag::err_friend_is_member); 12625 12626 if (D.isFunctionDefinition()) { 12627 // C++ [class.friend]p6: 12628 // A function can be defined in a friend declaration of a class if and 12629 // only if the class is a non-local class (9.8), the function name is 12630 // unqualified, and the function has namespace scope. 12631 SemaDiagnosticBuilder DB 12632 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 12633 12634 DB << SS.getScopeRep(); 12635 if (DC->isFileContext()) 12636 DB << FixItHint::CreateRemoval(SS.getRange()); 12637 SS.clear(); 12638 } 12639 12640 // - There's a scope specifier that does not match any template 12641 // parameter lists, in which case we use some arbitrary context, 12642 // create a method or method template, and wait for instantiation. 12643 // - There's a scope specifier that does match some template 12644 // parameter lists, which we don't handle right now. 12645 } else { 12646 if (D.isFunctionDefinition()) { 12647 // C++ [class.friend]p6: 12648 // A function can be defined in a friend declaration of a class if and 12649 // only if the class is a non-local class (9.8), the function name is 12650 // unqualified, and the function has namespace scope. 12651 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 12652 << SS.getScopeRep(); 12653 } 12654 12655 DC = CurContext; 12656 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 12657 } 12658 12659 if (!DC->isRecord()) { 12660 // This implies that it has to be an operator or function. 12661 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 12662 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 12663 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 12664 Diag(Loc, diag::err_introducing_special_friend) << 12665 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 12666 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 12667 return nullptr; 12668 } 12669 } 12670 12671 // FIXME: This is an egregious hack to cope with cases where the scope stack 12672 // does not contain the declaration context, i.e., in an out-of-line 12673 // definition of a class. 12674 Scope FakeDCScope(S, Scope::DeclScope, Diags); 12675 if (!DCScope) { 12676 FakeDCScope.setEntity(DC); 12677 DCScope = &FakeDCScope; 12678 } 12679 12680 bool AddToScope = true; 12681 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 12682 TemplateParams, AddToScope); 12683 if (!ND) return nullptr; 12684 12685 assert(ND->getLexicalDeclContext() == CurContext); 12686 12687 // If we performed typo correction, we might have added a scope specifier 12688 // and changed the decl context. 12689 DC = ND->getDeclContext(); 12690 12691 // Add the function declaration to the appropriate lookup tables, 12692 // adjusting the redeclarations list as necessary. We don't 12693 // want to do this yet if the friending class is dependent. 12694 // 12695 // Also update the scope-based lookup if the target context's 12696 // lookup context is in lexical scope. 12697 if (!CurContext->isDependentContext()) { 12698 DC = DC->getRedeclContext(); 12699 DC->makeDeclVisibleInContext(ND); 12700 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12701 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 12702 } 12703 12704 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 12705 D.getIdentifierLoc(), ND, 12706 DS.getFriendSpecLoc()); 12707 FrD->setAccess(AS_public); 12708 CurContext->addDecl(FrD); 12709 12710 if (ND->isInvalidDecl()) { 12711 FrD->setInvalidDecl(); 12712 } else { 12713 if (DC->isRecord()) CheckFriendAccess(ND); 12714 12715 FunctionDecl *FD; 12716 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 12717 FD = FTD->getTemplatedDecl(); 12718 else 12719 FD = cast<FunctionDecl>(ND); 12720 12721 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 12722 // default argument expression, that declaration shall be a definition 12723 // and shall be the only declaration of the function or function 12724 // template in the translation unit. 12725 if (functionDeclHasDefaultArgument(FD)) { 12726 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 12727 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 12728 Diag(OldFD->getLocation(), diag::note_previous_declaration); 12729 } else if (!D.isFunctionDefinition()) 12730 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 12731 } 12732 12733 // Mark templated-scope function declarations as unsupported. 12734 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 12735 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 12736 << SS.getScopeRep() << SS.getRange() 12737 << cast<CXXRecordDecl>(CurContext); 12738 FrD->setUnsupportedFriend(true); 12739 } 12740 } 12741 12742 return ND; 12743 } 12744 12745 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 12746 AdjustDeclIfTemplate(Dcl); 12747 12748 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 12749 if (!Fn) { 12750 Diag(DelLoc, diag::err_deleted_non_function); 12751 return; 12752 } 12753 12754 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 12755 // Don't consider the implicit declaration we generate for explicit 12756 // specializations. FIXME: Do not generate these implicit declarations. 12757 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 12758 Prev->getPreviousDecl()) && 12759 !Prev->isDefined()) { 12760 Diag(DelLoc, diag::err_deleted_decl_not_first); 12761 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 12762 Prev->isImplicit() ? diag::note_previous_implicit_declaration 12763 : diag::note_previous_declaration); 12764 } 12765 // If the declaration wasn't the first, we delete the function anyway for 12766 // recovery. 12767 Fn = Fn->getCanonicalDecl(); 12768 } 12769 12770 // dllimport/dllexport cannot be deleted. 12771 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 12772 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 12773 Fn->setInvalidDecl(); 12774 } 12775 12776 if (Fn->isDeleted()) 12777 return; 12778 12779 // See if we're deleting a function which is already known to override a 12780 // non-deleted virtual function. 12781 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 12782 bool IssuedDiagnostic = false; 12783 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 12784 E = MD->end_overridden_methods(); 12785 I != E; ++I) { 12786 if (!(*MD->begin_overridden_methods())->isDeleted()) { 12787 if (!IssuedDiagnostic) { 12788 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 12789 IssuedDiagnostic = true; 12790 } 12791 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 12792 } 12793 } 12794 } 12795 12796 // C++11 [basic.start.main]p3: 12797 // A program that defines main as deleted [...] is ill-formed. 12798 if (Fn->isMain()) 12799 Diag(DelLoc, diag::err_deleted_main); 12800 12801 Fn->setDeletedAsWritten(); 12802 } 12803 12804 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 12805 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 12806 12807 if (MD) { 12808 if (MD->getParent()->isDependentType()) { 12809 MD->setDefaulted(); 12810 MD->setExplicitlyDefaulted(); 12811 return; 12812 } 12813 12814 CXXSpecialMember Member = getSpecialMember(MD); 12815 if (Member == CXXInvalid) { 12816 if (!MD->isInvalidDecl()) 12817 Diag(DefaultLoc, diag::err_default_special_members); 12818 return; 12819 } 12820 12821 MD->setDefaulted(); 12822 MD->setExplicitlyDefaulted(); 12823 12824 // If this definition appears within the record, do the checking when 12825 // the record is complete. 12826 const FunctionDecl *Primary = MD; 12827 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 12828 // Find the uninstantiated declaration that actually had the '= default' 12829 // on it. 12830 Pattern->isDefined(Primary); 12831 12832 // If the method was defaulted on its first declaration, we will have 12833 // already performed the checking in CheckCompletedCXXClass. Such a 12834 // declaration doesn't trigger an implicit definition. 12835 if (Primary == Primary->getCanonicalDecl()) 12836 return; 12837 12838 CheckExplicitlyDefaultedSpecialMember(MD); 12839 12840 if (MD->isInvalidDecl()) 12841 return; 12842 12843 switch (Member) { 12844 case CXXDefaultConstructor: 12845 DefineImplicitDefaultConstructor(DefaultLoc, 12846 cast<CXXConstructorDecl>(MD)); 12847 break; 12848 case CXXCopyConstructor: 12849 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12850 break; 12851 case CXXCopyAssignment: 12852 DefineImplicitCopyAssignment(DefaultLoc, MD); 12853 break; 12854 case CXXDestructor: 12855 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12856 break; 12857 case CXXMoveConstructor: 12858 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12859 break; 12860 case CXXMoveAssignment: 12861 DefineImplicitMoveAssignment(DefaultLoc, MD); 12862 break; 12863 case CXXInvalid: 12864 llvm_unreachable("Invalid special member."); 12865 } 12866 } else { 12867 Diag(DefaultLoc, diag::err_default_special_members); 12868 } 12869 } 12870 12871 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12872 for (Stmt *SubStmt : S->children()) { 12873 if (!SubStmt) 12874 continue; 12875 if (isa<ReturnStmt>(SubStmt)) 12876 Self.Diag(SubStmt->getLocStart(), 12877 diag::err_return_in_constructor_handler); 12878 if (!isa<Expr>(SubStmt)) 12879 SearchForReturnInStmt(Self, SubStmt); 12880 } 12881 } 12882 12883 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12884 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12885 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12886 SearchForReturnInStmt(*this, Handler); 12887 } 12888 } 12889 12890 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12891 const CXXMethodDecl *Old) { 12892 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12893 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12894 12895 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12896 12897 // If the calling conventions match, everything is fine 12898 if (NewCC == OldCC) 12899 return false; 12900 12901 // If the calling conventions mismatch because the new function is static, 12902 // suppress the calling convention mismatch error; the error about static 12903 // function override (err_static_overrides_virtual from 12904 // Sema::CheckFunctionDeclaration) is more clear. 12905 if (New->getStorageClass() == SC_Static) 12906 return false; 12907 12908 Diag(New->getLocation(), 12909 diag::err_conflicting_overriding_cc_attributes) 12910 << New->getDeclName() << New->getType() << Old->getType(); 12911 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12912 return true; 12913 } 12914 12915 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12916 const CXXMethodDecl *Old) { 12917 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12918 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12919 12920 if (Context.hasSameType(NewTy, OldTy) || 12921 NewTy->isDependentType() || OldTy->isDependentType()) 12922 return false; 12923 12924 // Check if the return types are covariant 12925 QualType NewClassTy, OldClassTy; 12926 12927 /// Both types must be pointers or references to classes. 12928 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12929 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12930 NewClassTy = NewPT->getPointeeType(); 12931 OldClassTy = OldPT->getPointeeType(); 12932 } 12933 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12934 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12935 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12936 NewClassTy = NewRT->getPointeeType(); 12937 OldClassTy = OldRT->getPointeeType(); 12938 } 12939 } 12940 } 12941 12942 // The return types aren't either both pointers or references to a class type. 12943 if (NewClassTy.isNull()) { 12944 Diag(New->getLocation(), 12945 diag::err_different_return_type_for_overriding_virtual_function) 12946 << New->getDeclName() << NewTy << OldTy 12947 << New->getReturnTypeSourceRange(); 12948 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12949 << Old->getReturnTypeSourceRange(); 12950 12951 return true; 12952 } 12953 12954 // C++ [class.virtual]p6: 12955 // If the return type of D::f differs from the return type of B::f, the 12956 // class type in the return type of D::f shall be complete at the point of 12957 // declaration of D::f or shall be the class type D. 12958 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12959 if (!RT->isBeingDefined() && 12960 RequireCompleteType(New->getLocation(), NewClassTy, 12961 diag::err_covariant_return_incomplete, 12962 New->getDeclName())) 12963 return true; 12964 } 12965 12966 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12967 // Check if the new class derives from the old class. 12968 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12969 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 12970 << New->getDeclName() << NewTy << OldTy 12971 << New->getReturnTypeSourceRange(); 12972 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12973 << Old->getReturnTypeSourceRange(); 12974 return true; 12975 } 12976 12977 // Check if we the conversion from derived to base is valid. 12978 if (CheckDerivedToBaseConversion( 12979 NewClassTy, OldClassTy, 12980 diag::err_covariant_return_inaccessible_base, 12981 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12982 New->getLocation(), New->getReturnTypeSourceRange(), 12983 New->getDeclName(), nullptr)) { 12984 // FIXME: this note won't trigger for delayed access control 12985 // diagnostics, and it's impossible to get an undelayed error 12986 // here from access control during the original parse because 12987 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 12988 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12989 << Old->getReturnTypeSourceRange(); 12990 return true; 12991 } 12992 } 12993 12994 // The qualifiers of the return types must be the same. 12995 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 12996 Diag(New->getLocation(), 12997 diag::err_covariant_return_type_different_qualifications) 12998 << New->getDeclName() << NewTy << OldTy 12999 << New->getReturnTypeSourceRange(); 13000 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13001 << Old->getReturnTypeSourceRange(); 13002 return true; 13003 }; 13004 13005 13006 // The new class type must have the same or less qualifiers as the old type. 13007 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 13008 Diag(New->getLocation(), 13009 diag::err_covariant_return_type_class_type_more_qualified) 13010 << New->getDeclName() << NewTy << OldTy 13011 << New->getReturnTypeSourceRange(); 13012 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13013 << Old->getReturnTypeSourceRange(); 13014 return true; 13015 }; 13016 13017 return false; 13018 } 13019 13020 /// \brief Mark the given method pure. 13021 /// 13022 /// \param Method the method to be marked pure. 13023 /// 13024 /// \param InitRange the source range that covers the "0" initializer. 13025 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 13026 SourceLocation EndLoc = InitRange.getEnd(); 13027 if (EndLoc.isValid()) 13028 Method->setRangeEnd(EndLoc); 13029 13030 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 13031 Method->setPure(); 13032 return false; 13033 } 13034 13035 if (!Method->isInvalidDecl()) 13036 Diag(Method->getLocation(), diag::err_non_virtual_pure) 13037 << Method->getDeclName() << InitRange; 13038 return true; 13039 } 13040 13041 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 13042 if (D->getFriendObjectKind()) 13043 Diag(D->getLocation(), diag::err_pure_friend); 13044 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 13045 CheckPureMethod(M, ZeroLoc); 13046 else 13047 Diag(D->getLocation(), diag::err_illegal_initializer); 13048 } 13049 13050 /// \brief Determine whether the given declaration is a static data member. 13051 static bool isStaticDataMember(const Decl *D) { 13052 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 13053 return Var->isStaticDataMember(); 13054 13055 return false; 13056 } 13057 13058 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 13059 /// an initializer for the out-of-line declaration 'Dcl'. The scope 13060 /// is a fresh scope pushed for just this purpose. 13061 /// 13062 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 13063 /// static data member of class X, names should be looked up in the scope of 13064 /// class X. 13065 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 13066 // If there is no declaration, there was an error parsing it. 13067 if (!D || D->isInvalidDecl()) 13068 return; 13069 13070 // We will always have a nested name specifier here, but this declaration 13071 // might not be out of line if the specifier names the current namespace: 13072 // extern int n; 13073 // int ::n = 0; 13074 if (D->isOutOfLine()) 13075 EnterDeclaratorContext(S, D->getDeclContext()); 13076 13077 // If we are parsing the initializer for a static data member, push a 13078 // new expression evaluation context that is associated with this static 13079 // data member. 13080 if (isStaticDataMember(D)) 13081 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 13082 } 13083 13084 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 13085 /// initializer for the out-of-line declaration 'D'. 13086 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 13087 // If there is no declaration, there was an error parsing it. 13088 if (!D || D->isInvalidDecl()) 13089 return; 13090 13091 if (isStaticDataMember(D)) 13092 PopExpressionEvaluationContext(); 13093 13094 if (D->isOutOfLine()) 13095 ExitDeclaratorContext(S); 13096 } 13097 13098 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 13099 /// C++ if/switch/while/for statement. 13100 /// e.g: "if (int x = f()) {...}" 13101 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 13102 // C++ 6.4p2: 13103 // The declarator shall not specify a function or an array. 13104 // The type-specifier-seq shall not contain typedef and shall not declare a 13105 // new class or enumeration. 13106 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 13107 "Parser allowed 'typedef' as storage class of condition decl."); 13108 13109 Decl *Dcl = ActOnDeclarator(S, D); 13110 if (!Dcl) 13111 return true; 13112 13113 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 13114 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 13115 << D.getSourceRange(); 13116 return true; 13117 } 13118 13119 return Dcl; 13120 } 13121 13122 void Sema::LoadExternalVTableUses() { 13123 if (!ExternalSource) 13124 return; 13125 13126 SmallVector<ExternalVTableUse, 4> VTables; 13127 ExternalSource->ReadUsedVTables(VTables); 13128 SmallVector<VTableUse, 4> NewUses; 13129 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 13130 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 13131 = VTablesUsed.find(VTables[I].Record); 13132 // Even if a definition wasn't required before, it may be required now. 13133 if (Pos != VTablesUsed.end()) { 13134 if (!Pos->second && VTables[I].DefinitionRequired) 13135 Pos->second = true; 13136 continue; 13137 } 13138 13139 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 13140 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 13141 } 13142 13143 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 13144 } 13145 13146 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 13147 bool DefinitionRequired) { 13148 // Ignore any vtable uses in unevaluated operands or for classes that do 13149 // not have a vtable. 13150 if (!Class->isDynamicClass() || Class->isDependentContext() || 13151 CurContext->isDependentContext() || isUnevaluatedContext()) 13152 return; 13153 13154 // Try to insert this class into the map. 13155 LoadExternalVTableUses(); 13156 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13157 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 13158 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 13159 if (!Pos.second) { 13160 // If we already had an entry, check to see if we are promoting this vtable 13161 // to require a definition. If so, we need to reappend to the VTableUses 13162 // list, since we may have already processed the first entry. 13163 if (DefinitionRequired && !Pos.first->second) { 13164 Pos.first->second = true; 13165 } else { 13166 // Otherwise, we can early exit. 13167 return; 13168 } 13169 } else { 13170 // The Microsoft ABI requires that we perform the destructor body 13171 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 13172 // the deleting destructor is emitted with the vtable, not with the 13173 // destructor definition as in the Itanium ABI. 13174 // If it has a definition, we do the check at that point instead. 13175 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 13176 Class->hasUserDeclaredDestructor() && 13177 !Class->getDestructor()->isDefined() && 13178 !Class->getDestructor()->isDeleted()) { 13179 CXXDestructorDecl *DD = Class->getDestructor(); 13180 ContextRAII SavedContext(*this, DD); 13181 CheckDestructor(DD); 13182 } 13183 } 13184 13185 // Local classes need to have their virtual members marked 13186 // immediately. For all other classes, we mark their virtual members 13187 // at the end of the translation unit. 13188 if (Class->isLocalClass()) 13189 MarkVirtualMembersReferenced(Loc, Class); 13190 else 13191 VTableUses.push_back(std::make_pair(Class, Loc)); 13192 } 13193 13194 bool Sema::DefineUsedVTables() { 13195 LoadExternalVTableUses(); 13196 if (VTableUses.empty()) 13197 return false; 13198 13199 // Note: The VTableUses vector could grow as a result of marking 13200 // the members of a class as "used", so we check the size each 13201 // time through the loop and prefer indices (which are stable) to 13202 // iterators (which are not). 13203 bool DefinedAnything = false; 13204 for (unsigned I = 0; I != VTableUses.size(); ++I) { 13205 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 13206 if (!Class) 13207 continue; 13208 13209 SourceLocation Loc = VTableUses[I].second; 13210 13211 bool DefineVTable = true; 13212 13213 // If this class has a key function, but that key function is 13214 // defined in another translation unit, we don't need to emit the 13215 // vtable even though we're using it. 13216 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 13217 if (KeyFunction && !KeyFunction->hasBody()) { 13218 // The key function is in another translation unit. 13219 DefineVTable = false; 13220 TemplateSpecializationKind TSK = 13221 KeyFunction->getTemplateSpecializationKind(); 13222 assert(TSK != TSK_ExplicitInstantiationDefinition && 13223 TSK != TSK_ImplicitInstantiation && 13224 "Instantiations don't have key functions"); 13225 (void)TSK; 13226 } else if (!KeyFunction) { 13227 // If we have a class with no key function that is the subject 13228 // of an explicit instantiation declaration, suppress the 13229 // vtable; it will live with the explicit instantiation 13230 // definition. 13231 bool IsExplicitInstantiationDeclaration 13232 = Class->getTemplateSpecializationKind() 13233 == TSK_ExplicitInstantiationDeclaration; 13234 for (auto R : Class->redecls()) { 13235 TemplateSpecializationKind TSK 13236 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 13237 if (TSK == TSK_ExplicitInstantiationDeclaration) 13238 IsExplicitInstantiationDeclaration = true; 13239 else if (TSK == TSK_ExplicitInstantiationDefinition) { 13240 IsExplicitInstantiationDeclaration = false; 13241 break; 13242 } 13243 } 13244 13245 if (IsExplicitInstantiationDeclaration) 13246 DefineVTable = false; 13247 } 13248 13249 // The exception specifications for all virtual members may be needed even 13250 // if we are not providing an authoritative form of the vtable in this TU. 13251 // We may choose to emit it available_externally anyway. 13252 if (!DefineVTable) { 13253 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 13254 continue; 13255 } 13256 13257 // Mark all of the virtual members of this class as referenced, so 13258 // that we can build a vtable. Then, tell the AST consumer that a 13259 // vtable for this class is required. 13260 DefinedAnything = true; 13261 MarkVirtualMembersReferenced(Loc, Class); 13262 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13263 if (VTablesUsed[Canonical]) 13264 Consumer.HandleVTable(Class); 13265 13266 // Optionally warn if we're emitting a weak vtable. 13267 if (Class->isExternallyVisible() && 13268 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 13269 const FunctionDecl *KeyFunctionDef = nullptr; 13270 if (!KeyFunction || 13271 (KeyFunction->hasBody(KeyFunctionDef) && 13272 KeyFunctionDef->isInlined())) 13273 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 13274 TSK_ExplicitInstantiationDefinition 13275 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 13276 << Class; 13277 } 13278 } 13279 VTableUses.clear(); 13280 13281 return DefinedAnything; 13282 } 13283 13284 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 13285 const CXXRecordDecl *RD) { 13286 for (const auto *I : RD->methods()) 13287 if (I->isVirtual() && !I->isPure()) 13288 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 13289 } 13290 13291 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 13292 const CXXRecordDecl *RD) { 13293 // Mark all functions which will appear in RD's vtable as used. 13294 CXXFinalOverriderMap FinalOverriders; 13295 RD->getFinalOverriders(FinalOverriders); 13296 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 13297 E = FinalOverriders.end(); 13298 I != E; ++I) { 13299 for (OverridingMethods::const_iterator OI = I->second.begin(), 13300 OE = I->second.end(); 13301 OI != OE; ++OI) { 13302 assert(OI->second.size() > 0 && "no final overrider"); 13303 CXXMethodDecl *Overrider = OI->second.front().Method; 13304 13305 // C++ [basic.def.odr]p2: 13306 // [...] A virtual member function is used if it is not pure. [...] 13307 if (!Overrider->isPure()) 13308 MarkFunctionReferenced(Loc, Overrider); 13309 } 13310 } 13311 13312 // Only classes that have virtual bases need a VTT. 13313 if (RD->getNumVBases() == 0) 13314 return; 13315 13316 for (const auto &I : RD->bases()) { 13317 const CXXRecordDecl *Base = 13318 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 13319 if (Base->getNumVBases() == 0) 13320 continue; 13321 MarkVirtualMembersReferenced(Loc, Base); 13322 } 13323 } 13324 13325 /// SetIvarInitializers - This routine builds initialization ASTs for the 13326 /// Objective-C implementation whose ivars need be initialized. 13327 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 13328 if (!getLangOpts().CPlusPlus) 13329 return; 13330 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 13331 SmallVector<ObjCIvarDecl*, 8> ivars; 13332 CollectIvarsToConstructOrDestruct(OID, ivars); 13333 if (ivars.empty()) 13334 return; 13335 SmallVector<CXXCtorInitializer*, 32> AllToInit; 13336 for (unsigned i = 0; i < ivars.size(); i++) { 13337 FieldDecl *Field = ivars[i]; 13338 if (Field->isInvalidDecl()) 13339 continue; 13340 13341 CXXCtorInitializer *Member; 13342 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 13343 InitializationKind InitKind = 13344 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 13345 13346 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 13347 ExprResult MemberInit = 13348 InitSeq.Perform(*this, InitEntity, InitKind, None); 13349 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 13350 // Note, MemberInit could actually come back empty if no initialization 13351 // is required (e.g., because it would call a trivial default constructor) 13352 if (!MemberInit.get() || MemberInit.isInvalid()) 13353 continue; 13354 13355 Member = 13356 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 13357 SourceLocation(), 13358 MemberInit.getAs<Expr>(), 13359 SourceLocation()); 13360 AllToInit.push_back(Member); 13361 13362 // Be sure that the destructor is accessible and is marked as referenced. 13363 if (const RecordType *RecordTy = 13364 Context.getBaseElementType(Field->getType()) 13365 ->getAs<RecordType>()) { 13366 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 13367 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 13368 MarkFunctionReferenced(Field->getLocation(), Destructor); 13369 CheckDestructorAccess(Field->getLocation(), Destructor, 13370 PDiag(diag::err_access_dtor_ivar) 13371 << Context.getBaseElementType(Field->getType())); 13372 } 13373 } 13374 } 13375 ObjCImplementation->setIvarInitializers(Context, 13376 AllToInit.data(), AllToInit.size()); 13377 } 13378 } 13379 13380 static 13381 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 13382 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 13383 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 13384 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 13385 Sema &S) { 13386 if (Ctor->isInvalidDecl()) 13387 return; 13388 13389 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 13390 13391 // Target may not be determinable yet, for instance if this is a dependent 13392 // call in an uninstantiated template. 13393 if (Target) { 13394 const FunctionDecl *FNTarget = nullptr; 13395 (void)Target->hasBody(FNTarget); 13396 Target = const_cast<CXXConstructorDecl*>( 13397 cast_or_null<CXXConstructorDecl>(FNTarget)); 13398 } 13399 13400 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 13401 // Avoid dereferencing a null pointer here. 13402 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 13403 13404 if (!Current.insert(Canonical).second) 13405 return; 13406 13407 // We know that beyond here, we aren't chaining into a cycle. 13408 if (!Target || !Target->isDelegatingConstructor() || 13409 Target->isInvalidDecl() || Valid.count(TCanonical)) { 13410 Valid.insert(Current.begin(), Current.end()); 13411 Current.clear(); 13412 // We've hit a cycle. 13413 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 13414 Current.count(TCanonical)) { 13415 // If we haven't diagnosed this cycle yet, do so now. 13416 if (!Invalid.count(TCanonical)) { 13417 S.Diag((*Ctor->init_begin())->getSourceLocation(), 13418 diag::warn_delegating_ctor_cycle) 13419 << Ctor; 13420 13421 // Don't add a note for a function delegating directly to itself. 13422 if (TCanonical != Canonical) 13423 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 13424 13425 CXXConstructorDecl *C = Target; 13426 while (C->getCanonicalDecl() != Canonical) { 13427 const FunctionDecl *FNTarget = nullptr; 13428 (void)C->getTargetConstructor()->hasBody(FNTarget); 13429 assert(FNTarget && "Ctor cycle through bodiless function"); 13430 13431 C = const_cast<CXXConstructorDecl*>( 13432 cast<CXXConstructorDecl>(FNTarget)); 13433 S.Diag(C->getLocation(), diag::note_which_delegates_to); 13434 } 13435 } 13436 13437 Invalid.insert(Current.begin(), Current.end()); 13438 Current.clear(); 13439 } else { 13440 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 13441 } 13442 } 13443 13444 13445 void Sema::CheckDelegatingCtorCycles() { 13446 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 13447 13448 for (DelegatingCtorDeclsType::iterator 13449 I = DelegatingCtorDecls.begin(ExternalSource), 13450 E = DelegatingCtorDecls.end(); 13451 I != E; ++I) 13452 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 13453 13454 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 13455 CE = Invalid.end(); 13456 CI != CE; ++CI) 13457 (*CI)->setInvalidDecl(); 13458 } 13459 13460 namespace { 13461 /// \brief AST visitor that finds references to the 'this' expression. 13462 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 13463 Sema &S; 13464 13465 public: 13466 explicit FindCXXThisExpr(Sema &S) : S(S) { } 13467 13468 bool VisitCXXThisExpr(CXXThisExpr *E) { 13469 S.Diag(E->getLocation(), diag::err_this_static_member_func) 13470 << E->isImplicit(); 13471 return false; 13472 } 13473 }; 13474 } 13475 13476 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 13477 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13478 if (!TSInfo) 13479 return false; 13480 13481 TypeLoc TL = TSInfo->getTypeLoc(); 13482 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13483 if (!ProtoTL) 13484 return false; 13485 13486 // C++11 [expr.prim.general]p3: 13487 // [The expression this] shall not appear before the optional 13488 // cv-qualifier-seq and it shall not appear within the declaration of a 13489 // static member function (although its type and value category are defined 13490 // within a static member function as they are within a non-static member 13491 // function). [ Note: this is because declaration matching does not occur 13492 // until the complete declarator is known. - end note ] 13493 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13494 FindCXXThisExpr Finder(*this); 13495 13496 // If the return type came after the cv-qualifier-seq, check it now. 13497 if (Proto->hasTrailingReturn() && 13498 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 13499 return true; 13500 13501 // Check the exception specification. 13502 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 13503 return true; 13504 13505 return checkThisInStaticMemberFunctionAttributes(Method); 13506 } 13507 13508 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 13509 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13510 if (!TSInfo) 13511 return false; 13512 13513 TypeLoc TL = TSInfo->getTypeLoc(); 13514 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13515 if (!ProtoTL) 13516 return false; 13517 13518 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13519 FindCXXThisExpr Finder(*this); 13520 13521 switch (Proto->getExceptionSpecType()) { 13522 case EST_Unparsed: 13523 case EST_Uninstantiated: 13524 case EST_Unevaluated: 13525 case EST_BasicNoexcept: 13526 case EST_DynamicNone: 13527 case EST_MSAny: 13528 case EST_None: 13529 break; 13530 13531 case EST_ComputedNoexcept: 13532 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 13533 return true; 13534 13535 case EST_Dynamic: 13536 for (const auto &E : Proto->exceptions()) { 13537 if (!Finder.TraverseType(E)) 13538 return true; 13539 } 13540 break; 13541 } 13542 13543 return false; 13544 } 13545 13546 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 13547 FindCXXThisExpr Finder(*this); 13548 13549 // Check attributes. 13550 for (const auto *A : Method->attrs()) { 13551 // FIXME: This should be emitted by tblgen. 13552 Expr *Arg = nullptr; 13553 ArrayRef<Expr *> Args; 13554 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 13555 Arg = G->getArg(); 13556 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 13557 Arg = G->getArg(); 13558 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 13559 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 13560 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 13561 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 13562 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 13563 Arg = ETLF->getSuccessValue(); 13564 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 13565 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 13566 Arg = STLF->getSuccessValue(); 13567 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 13568 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 13569 Arg = LR->getArg(); 13570 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 13571 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 13572 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 13573 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13574 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 13575 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13576 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 13577 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13578 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 13579 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13580 13581 if (Arg && !Finder.TraverseStmt(Arg)) 13582 return true; 13583 13584 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 13585 if (!Finder.TraverseStmt(Args[I])) 13586 return true; 13587 } 13588 } 13589 13590 return false; 13591 } 13592 13593 void Sema::checkExceptionSpecification( 13594 bool IsTopLevel, ExceptionSpecificationType EST, 13595 ArrayRef<ParsedType> DynamicExceptions, 13596 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 13597 SmallVectorImpl<QualType> &Exceptions, 13598 FunctionProtoType::ExceptionSpecInfo &ESI) { 13599 Exceptions.clear(); 13600 ESI.Type = EST; 13601 if (EST == EST_Dynamic) { 13602 Exceptions.reserve(DynamicExceptions.size()); 13603 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 13604 // FIXME: Preserve type source info. 13605 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 13606 13607 if (IsTopLevel) { 13608 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 13609 collectUnexpandedParameterPacks(ET, Unexpanded); 13610 if (!Unexpanded.empty()) { 13611 DiagnoseUnexpandedParameterPacks( 13612 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 13613 Unexpanded); 13614 continue; 13615 } 13616 } 13617 13618 // Check that the type is valid for an exception spec, and 13619 // drop it if not. 13620 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 13621 Exceptions.push_back(ET); 13622 } 13623 ESI.Exceptions = Exceptions; 13624 return; 13625 } 13626 13627 if (EST == EST_ComputedNoexcept) { 13628 // If an error occurred, there's no expression here. 13629 if (NoexceptExpr) { 13630 assert((NoexceptExpr->isTypeDependent() || 13631 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 13632 Context.BoolTy) && 13633 "Parser should have made sure that the expression is boolean"); 13634 if (IsTopLevel && NoexceptExpr && 13635 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 13636 ESI.Type = EST_BasicNoexcept; 13637 return; 13638 } 13639 13640 if (!NoexceptExpr->isValueDependent()) 13641 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 13642 diag::err_noexcept_needs_constant_expression, 13643 /*AllowFold*/ false).get(); 13644 ESI.NoexceptExpr = NoexceptExpr; 13645 } 13646 return; 13647 } 13648 } 13649 13650 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 13651 ExceptionSpecificationType EST, 13652 SourceRange SpecificationRange, 13653 ArrayRef<ParsedType> DynamicExceptions, 13654 ArrayRef<SourceRange> DynamicExceptionRanges, 13655 Expr *NoexceptExpr) { 13656 if (!MethodD) 13657 return; 13658 13659 // Dig out the method we're referring to. 13660 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 13661 MethodD = FunTmpl->getTemplatedDecl(); 13662 13663 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 13664 if (!Method) 13665 return; 13666 13667 // Check the exception specification. 13668 llvm::SmallVector<QualType, 4> Exceptions; 13669 FunctionProtoType::ExceptionSpecInfo ESI; 13670 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 13671 DynamicExceptionRanges, NoexceptExpr, Exceptions, 13672 ESI); 13673 13674 // Update the exception specification on the function type. 13675 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 13676 13677 if (Method->isStatic()) 13678 checkThisInStaticMemberFunctionExceptionSpec(Method); 13679 13680 if (Method->isVirtual()) { 13681 // Check overrides, which we previously had to delay. 13682 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(), 13683 OEnd = Method->end_overridden_methods(); 13684 O != OEnd; ++O) 13685 CheckOverridingFunctionExceptionSpec(Method, *O); 13686 } 13687 } 13688 13689 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 13690 /// 13691 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 13692 SourceLocation DeclStart, 13693 Declarator &D, Expr *BitWidth, 13694 InClassInitStyle InitStyle, 13695 AccessSpecifier AS, 13696 AttributeList *MSPropertyAttr) { 13697 IdentifierInfo *II = D.getIdentifier(); 13698 if (!II) { 13699 Diag(DeclStart, diag::err_anonymous_property); 13700 return nullptr; 13701 } 13702 SourceLocation Loc = D.getIdentifierLoc(); 13703 13704 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13705 QualType T = TInfo->getType(); 13706 if (getLangOpts().CPlusPlus) { 13707 CheckExtraCXXDefaultArguments(D); 13708 13709 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13710 UPPC_DataMemberType)) { 13711 D.setInvalidType(); 13712 T = Context.IntTy; 13713 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13714 } 13715 } 13716 13717 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13718 13719 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13720 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13721 diag::err_invalid_thread) 13722 << DeclSpec::getSpecifierName(TSCS); 13723 13724 // Check to see if this name was declared as a member previously 13725 NamedDecl *PrevDecl = nullptr; 13726 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13727 LookupName(Previous, S); 13728 switch (Previous.getResultKind()) { 13729 case LookupResult::Found: 13730 case LookupResult::FoundUnresolvedValue: 13731 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13732 break; 13733 13734 case LookupResult::FoundOverloaded: 13735 PrevDecl = Previous.getRepresentativeDecl(); 13736 break; 13737 13738 case LookupResult::NotFound: 13739 case LookupResult::NotFoundInCurrentInstantiation: 13740 case LookupResult::Ambiguous: 13741 break; 13742 } 13743 13744 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13745 // Maybe we will complain about the shadowed template parameter. 13746 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13747 // Just pretend that we didn't see the previous declaration. 13748 PrevDecl = nullptr; 13749 } 13750 13751 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13752 PrevDecl = nullptr; 13753 13754 SourceLocation TSSL = D.getLocStart(); 13755 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 13756 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 13757 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 13758 ProcessDeclAttributes(TUScope, NewPD, D); 13759 NewPD->setAccess(AS); 13760 13761 if (NewPD->isInvalidDecl()) 13762 Record->setInvalidDecl(); 13763 13764 if (D.getDeclSpec().isModulePrivateSpecified()) 13765 NewPD->setModulePrivate(); 13766 13767 if (NewPD->isInvalidDecl() && PrevDecl) { 13768 // Don't introduce NewFD into scope; there's already something 13769 // with the same name in the same scope. 13770 } else if (II) { 13771 PushOnScopeChains(NewPD, S); 13772 } else 13773 Record->addDecl(NewPD); 13774 13775 return NewPD; 13776 } 13777