1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for C++ declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTConsumer.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/ASTLambda.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/ComparisonCategories.h" 20 #include "clang/AST/EvaluatedExprVisitor.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/RecordLayout.h" 23 #include "clang/AST/RecursiveASTVisitor.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/AST/TypeLoc.h" 26 #include "clang/AST/TypeOrdering.h" 27 #include "clang/Basic/AttributeCommonInfo.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/SemaInternal.h" 40 #include "clang/Sema/Template.h" 41 #include "llvm/ADT/STLExtras.h" 42 #include "llvm/ADT/SmallString.h" 43 #include "llvm/ADT/StringExtras.h" 44 #include <map> 45 #include <set> 46 47 using namespace clang; 48 49 //===----------------------------------------------------------------------===// 50 // CheckDefaultArgumentVisitor 51 //===----------------------------------------------------------------------===// 52 53 namespace { 54 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 55 /// the default argument of a parameter to determine whether it 56 /// contains any ill-formed subexpressions. For example, this will 57 /// diagnose the use of local variables or parameters within the 58 /// default argument expression. 59 class CheckDefaultArgumentVisitor 60 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 61 Expr *DefaultArg; 62 Sema *S; 63 64 public: 65 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 66 : DefaultArg(defarg), S(s) {} 67 68 bool VisitExpr(Expr *Node); 69 bool VisitDeclRefExpr(DeclRefExpr *DRE); 70 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 71 bool VisitLambdaExpr(LambdaExpr *Lambda); 72 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 73 }; 74 75 /// VisitExpr - Visit all of the children of this expression. 76 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 77 bool IsInvalid = false; 78 for (Stmt *SubStmt : Node->children()) 79 IsInvalid |= Visit(SubStmt); 80 return IsInvalid; 81 } 82 83 /// VisitDeclRefExpr - Visit a reference to a declaration, to 84 /// determine whether this declaration can be used in the default 85 /// argument expression. 86 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 87 NamedDecl *Decl = DRE->getDecl(); 88 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 89 // C++ [dcl.fct.default]p9 90 // Default arguments are evaluated each time the function is 91 // called. The order of evaluation of function arguments is 92 // unspecified. Consequently, parameters of a function shall not 93 // be used in default argument expressions, even if they are not 94 // evaluated. Parameters of a function declared before a default 95 // argument expression are in scope and can hide namespace and 96 // class member names. 97 return S->Diag(DRE->getBeginLoc(), 98 diag::err_param_default_argument_references_param) 99 << Param->getDeclName() << DefaultArg->getSourceRange(); 100 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 101 // C++ [dcl.fct.default]p7 102 // Local variables shall not be used in default argument 103 // expressions. 104 if (VDecl->isLocalVarDecl()) 105 return S->Diag(DRE->getBeginLoc(), 106 diag::err_param_default_argument_references_local) 107 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 108 } 109 110 return false; 111 } 112 113 /// VisitCXXThisExpr - Visit a C++ "this" expression. 114 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 115 // C++ [dcl.fct.default]p8: 116 // The keyword this shall not be used in a default argument of a 117 // member function. 118 return S->Diag(ThisE->getBeginLoc(), 119 diag::err_param_default_argument_references_this) 120 << ThisE->getSourceRange(); 121 } 122 123 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 124 bool Invalid = false; 125 for (PseudoObjectExpr::semantics_iterator 126 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 127 Expr *E = *i; 128 129 // Look through bindings. 130 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 131 E = OVE->getSourceExpr(); 132 assert(E && "pseudo-object binding without source expression?"); 133 } 134 135 Invalid |= Visit(E); 136 } 137 return Invalid; 138 } 139 140 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 141 // C++11 [expr.lambda.prim]p13: 142 // A lambda-expression appearing in a default argument shall not 143 // implicitly or explicitly capture any entity. 144 if (Lambda->capture_begin() == Lambda->capture_end()) 145 return false; 146 147 return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); 148 } 149 } 150 151 void 152 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 153 const CXXMethodDecl *Method) { 154 // If we have an MSAny spec already, don't bother. 155 if (!Method || ComputedEST == EST_MSAny) 156 return; 157 158 const FunctionProtoType *Proto 159 = Method->getType()->getAs<FunctionProtoType>(); 160 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 161 if (!Proto) 162 return; 163 164 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 165 166 // If we have a throw-all spec at this point, ignore the function. 167 if (ComputedEST == EST_None) 168 return; 169 170 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 171 EST = EST_BasicNoexcept; 172 173 switch (EST) { 174 case EST_Unparsed: 175 case EST_Uninstantiated: 176 case EST_Unevaluated: 177 llvm_unreachable("should not see unresolved exception specs here"); 178 179 // If this function can throw any exceptions, make a note of that. 180 case EST_MSAny: 181 case EST_None: 182 // FIXME: Whichever we see last of MSAny and None determines our result. 183 // We should make a consistent, order-independent choice here. 184 ClearExceptions(); 185 ComputedEST = EST; 186 return; 187 case EST_NoexceptFalse: 188 ClearExceptions(); 189 ComputedEST = EST_None; 190 return; 191 // FIXME: If the call to this decl is using any of its default arguments, we 192 // need to search them for potentially-throwing calls. 193 // If this function has a basic noexcept, it doesn't affect the outcome. 194 case EST_BasicNoexcept: 195 case EST_NoexceptTrue: 196 case EST_NoThrow: 197 return; 198 // If we're still at noexcept(true) and there's a throw() callee, 199 // change to that specification. 200 case EST_DynamicNone: 201 if (ComputedEST == EST_BasicNoexcept) 202 ComputedEST = EST_DynamicNone; 203 return; 204 case EST_DependentNoexcept: 205 llvm_unreachable( 206 "should not generate implicit declarations for dependent cases"); 207 case EST_Dynamic: 208 break; 209 } 210 assert(EST == EST_Dynamic && "EST case not considered earlier."); 211 assert(ComputedEST != EST_None && 212 "Shouldn't collect exceptions when throw-all is guaranteed."); 213 ComputedEST = EST_Dynamic; 214 // Record the exceptions in this function's exception specification. 215 for (const auto &E : Proto->exceptions()) 216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 217 Exceptions.push_back(E); 218 } 219 220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 221 if (!E || ComputedEST == EST_MSAny) 222 return; 223 224 // FIXME: 225 // 226 // C++0x [except.spec]p14: 227 // [An] implicit exception-specification specifies the type-id T if and 228 // only if T is allowed by the exception-specification of a function directly 229 // invoked by f's implicit definition; f shall allow all exceptions if any 230 // function it directly invokes allows all exceptions, and f shall allow no 231 // exceptions if every function it directly invokes allows no exceptions. 232 // 233 // Note in particular that if an implicit exception-specification is generated 234 // for a function containing a throw-expression, that specification can still 235 // be noexcept(true). 236 // 237 // Note also that 'directly invoked' is not defined in the standard, and there 238 // is no indication that we should only consider potentially-evaluated calls. 239 // 240 // Ultimately we should implement the intent of the standard: the exception 241 // specification should be the set of exceptions which can be thrown by the 242 // implicit definition. For now, we assume that any non-nothrow expression can 243 // throw any exception. 244 245 if (Self->canThrow(E)) 246 ComputedEST = EST_None; 247 } 248 249 bool 250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 251 SourceLocation EqualLoc) { 252 if (RequireCompleteType(Param->getLocation(), Param->getType(), 253 diag::err_typecheck_decl_incomplete_type)) { 254 Param->setInvalidDecl(); 255 return true; 256 } 257 258 // C++ [dcl.fct.default]p5 259 // A default argument expression is implicitly converted (clause 260 // 4) to the parameter type. The default argument expression has 261 // the same semantic constraints as the initializer expression in 262 // a declaration of a variable of the parameter type, using the 263 // copy-initialization semantics (8.5). 264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 265 Param); 266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 267 EqualLoc); 268 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 270 if (Result.isInvalid()) 271 return true; 272 Arg = Result.getAs<Expr>(); 273 274 CheckCompletedExpr(Arg, EqualLoc); 275 Arg = MaybeCreateExprWithCleanups(Arg); 276 277 // Okay: add the default argument to the parameter 278 Param->setDefaultArg(Arg); 279 280 // We have already instantiated this parameter; provide each of the 281 // instantiations with the uninstantiated default argument. 282 UnparsedDefaultArgInstantiationsMap::iterator InstPos 283 = UnparsedDefaultArgInstantiations.find(Param); 284 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 287 288 // We're done tracking this parameter's instantiations. 289 UnparsedDefaultArgInstantiations.erase(InstPos); 290 } 291 292 return false; 293 } 294 295 /// ActOnParamDefaultArgument - Check whether the default argument 296 /// provided for a function parameter is well-formed. If so, attach it 297 /// to the parameter declaration. 298 void 299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 300 Expr *DefaultArg) { 301 if (!param || !DefaultArg) 302 return; 303 304 ParmVarDecl *Param = cast<ParmVarDecl>(param); 305 UnparsedDefaultArgLocs.erase(Param); 306 307 // Default arguments are only permitted in C++ 308 if (!getLangOpts().CPlusPlus) { 309 Diag(EqualLoc, diag::err_param_default_argument) 310 << DefaultArg->getSourceRange(); 311 Param->setInvalidDecl(); 312 return; 313 } 314 315 // Check for unexpanded parameter packs. 316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 317 Param->setInvalidDecl(); 318 return; 319 } 320 321 // C++11 [dcl.fct.default]p3 322 // A default argument expression [...] shall not be specified for a 323 // parameter pack. 324 if (Param->isParameterPack()) { 325 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 326 << DefaultArg->getSourceRange(); 327 return; 328 } 329 330 // Check that the default argument is well-formed 331 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 332 if (DefaultArgChecker.Visit(DefaultArg)) { 333 Param->setInvalidDecl(); 334 return; 335 } 336 337 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 338 } 339 340 /// ActOnParamUnparsedDefaultArgument - We've seen a default 341 /// argument for a function parameter, but we can't parse it yet 342 /// because we're inside a class definition. Note that this default 343 /// argument will be parsed later. 344 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 345 SourceLocation EqualLoc, 346 SourceLocation ArgLoc) { 347 if (!param) 348 return; 349 350 ParmVarDecl *Param = cast<ParmVarDecl>(param); 351 Param->setUnparsedDefaultArg(); 352 UnparsedDefaultArgLocs[Param] = ArgLoc; 353 } 354 355 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 356 /// the default argument for the parameter param failed. 357 void Sema::ActOnParamDefaultArgumentError(Decl *param, 358 SourceLocation EqualLoc) { 359 if (!param) 360 return; 361 362 ParmVarDecl *Param = cast<ParmVarDecl>(param); 363 Param->setInvalidDecl(); 364 UnparsedDefaultArgLocs.erase(Param); 365 Param->setDefaultArg(new(Context) 366 OpaqueValueExpr(EqualLoc, 367 Param->getType().getNonReferenceType(), 368 VK_RValue)); 369 } 370 371 /// CheckExtraCXXDefaultArguments - Check for any extra default 372 /// arguments in the declarator, which is not a function declaration 373 /// or definition and therefore is not permitted to have default 374 /// arguments. This routine should be invoked for every declarator 375 /// that is not a function declaration or definition. 376 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 377 // C++ [dcl.fct.default]p3 378 // A default argument expression shall be specified only in the 379 // parameter-declaration-clause of a function declaration or in a 380 // template-parameter (14.1). It shall not be specified for a 381 // parameter pack. If it is specified in a 382 // parameter-declaration-clause, it shall not occur within a 383 // declarator or abstract-declarator of a parameter-declaration. 384 bool MightBeFunction = D.isFunctionDeclarationContext(); 385 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 386 DeclaratorChunk &chunk = D.getTypeObject(i); 387 if (chunk.Kind == DeclaratorChunk::Function) { 388 if (MightBeFunction) { 389 // This is a function declaration. It can have default arguments, but 390 // keep looking in case its return type is a function type with default 391 // arguments. 392 MightBeFunction = false; 393 continue; 394 } 395 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 396 ++argIdx) { 397 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 398 if (Param->hasUnparsedDefaultArg()) { 399 std::unique_ptr<CachedTokens> Toks = 400 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 401 SourceRange SR; 402 if (Toks->size() > 1) 403 SR = SourceRange((*Toks)[1].getLocation(), 404 Toks->back().getLocation()); 405 else 406 SR = UnparsedDefaultArgLocs[Param]; 407 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 408 << SR; 409 } else if (Param->getDefaultArg()) { 410 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 411 << Param->getDefaultArg()->getSourceRange(); 412 Param->setDefaultArg(nullptr); 413 } 414 } 415 } else if (chunk.Kind != DeclaratorChunk::Paren) { 416 MightBeFunction = false; 417 } 418 } 419 } 420 421 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 422 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 423 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 424 if (!PVD->hasDefaultArg()) 425 return false; 426 if (!PVD->hasInheritedDefaultArg()) 427 return true; 428 } 429 return false; 430 } 431 432 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 433 /// function, once we already know that they have the same 434 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 435 /// error, false otherwise. 436 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 437 Scope *S) { 438 bool Invalid = false; 439 440 // The declaration context corresponding to the scope is the semantic 441 // parent, unless this is a local function declaration, in which case 442 // it is that surrounding function. 443 DeclContext *ScopeDC = New->isLocalExternDecl() 444 ? New->getLexicalDeclContext() 445 : New->getDeclContext(); 446 447 // Find the previous declaration for the purpose of default arguments. 448 FunctionDecl *PrevForDefaultArgs = Old; 449 for (/**/; PrevForDefaultArgs; 450 // Don't bother looking back past the latest decl if this is a local 451 // extern declaration; nothing else could work. 452 PrevForDefaultArgs = New->isLocalExternDecl() 453 ? nullptr 454 : PrevForDefaultArgs->getPreviousDecl()) { 455 // Ignore hidden declarations. 456 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 457 continue; 458 459 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 460 !New->isCXXClassMember()) { 461 // Ignore default arguments of old decl if they are not in 462 // the same scope and this is not an out-of-line definition of 463 // a member function. 464 continue; 465 } 466 467 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 468 // If only one of these is a local function declaration, then they are 469 // declared in different scopes, even though isDeclInScope may think 470 // they're in the same scope. (If both are local, the scope check is 471 // sufficient, and if neither is local, then they are in the same scope.) 472 continue; 473 } 474 475 // We found the right previous declaration. 476 break; 477 } 478 479 // C++ [dcl.fct.default]p4: 480 // For non-template functions, default arguments can be added in 481 // later declarations of a function in the same 482 // scope. Declarations in different scopes have completely 483 // distinct sets of default arguments. That is, declarations in 484 // inner scopes do not acquire default arguments from 485 // declarations in outer scopes, and vice versa. In a given 486 // function declaration, all parameters subsequent to a 487 // parameter with a default argument shall have default 488 // arguments supplied in this or previous declarations. A 489 // default argument shall not be redefined by a later 490 // declaration (not even to the same value). 491 // 492 // C++ [dcl.fct.default]p6: 493 // Except for member functions of class templates, the default arguments 494 // in a member function definition that appears outside of the class 495 // definition are added to the set of default arguments provided by the 496 // member function declaration in the class definition. 497 for (unsigned p = 0, NumParams = PrevForDefaultArgs 498 ? PrevForDefaultArgs->getNumParams() 499 : 0; 500 p < NumParams; ++p) { 501 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 502 ParmVarDecl *NewParam = New->getParamDecl(p); 503 504 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 505 bool NewParamHasDfl = NewParam->hasDefaultArg(); 506 507 if (OldParamHasDfl && NewParamHasDfl) { 508 unsigned DiagDefaultParamID = 509 diag::err_param_default_argument_redefinition; 510 511 // MSVC accepts that default parameters be redefined for member functions 512 // of template class. The new default parameter's value is ignored. 513 Invalid = true; 514 if (getLangOpts().MicrosoftExt) { 515 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 516 if (MD && MD->getParent()->getDescribedClassTemplate()) { 517 // Merge the old default argument into the new parameter. 518 NewParam->setHasInheritedDefaultArg(); 519 if (OldParam->hasUninstantiatedDefaultArg()) 520 NewParam->setUninstantiatedDefaultArg( 521 OldParam->getUninstantiatedDefaultArg()); 522 else 523 NewParam->setDefaultArg(OldParam->getInit()); 524 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 525 Invalid = false; 526 } 527 } 528 529 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 530 // hint here. Alternatively, we could walk the type-source information 531 // for NewParam to find the last source location in the type... but it 532 // isn't worth the effort right now. This is the kind of test case that 533 // is hard to get right: 534 // int f(int); 535 // void g(int (*fp)(int) = f); 536 // void g(int (*fp)(int) = &f); 537 Diag(NewParam->getLocation(), DiagDefaultParamID) 538 << NewParam->getDefaultArgRange(); 539 540 // Look for the function declaration where the default argument was 541 // actually written, which may be a declaration prior to Old. 542 for (auto Older = PrevForDefaultArgs; 543 OldParam->hasInheritedDefaultArg(); /**/) { 544 Older = Older->getPreviousDecl(); 545 OldParam = Older->getParamDecl(p); 546 } 547 548 Diag(OldParam->getLocation(), diag::note_previous_definition) 549 << OldParam->getDefaultArgRange(); 550 } else if (OldParamHasDfl) { 551 // Merge the old default argument into the new parameter unless the new 552 // function is a friend declaration in a template class. In the latter 553 // case the default arguments will be inherited when the friend 554 // declaration will be instantiated. 555 if (New->getFriendObjectKind() == Decl::FOK_None || 556 !New->getLexicalDeclContext()->isDependentContext()) { 557 // It's important to use getInit() here; getDefaultArg() 558 // strips off any top-level ExprWithCleanups. 559 NewParam->setHasInheritedDefaultArg(); 560 if (OldParam->hasUnparsedDefaultArg()) 561 NewParam->setUnparsedDefaultArg(); 562 else if (OldParam->hasUninstantiatedDefaultArg()) 563 NewParam->setUninstantiatedDefaultArg( 564 OldParam->getUninstantiatedDefaultArg()); 565 else 566 NewParam->setDefaultArg(OldParam->getInit()); 567 } 568 } else if (NewParamHasDfl) { 569 if (New->getDescribedFunctionTemplate()) { 570 // Paragraph 4, quoted above, only applies to non-template functions. 571 Diag(NewParam->getLocation(), 572 diag::err_param_default_argument_template_redecl) 573 << NewParam->getDefaultArgRange(); 574 Diag(PrevForDefaultArgs->getLocation(), 575 diag::note_template_prev_declaration) 576 << false; 577 } else if (New->getTemplateSpecializationKind() 578 != TSK_ImplicitInstantiation && 579 New->getTemplateSpecializationKind() != TSK_Undeclared) { 580 // C++ [temp.expr.spec]p21: 581 // Default function arguments shall not be specified in a declaration 582 // or a definition for one of the following explicit specializations: 583 // - the explicit specialization of a function template; 584 // - the explicit specialization of a member function template; 585 // - the explicit specialization of a member function of a class 586 // template where the class template specialization to which the 587 // member function specialization belongs is implicitly 588 // instantiated. 589 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 590 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 591 << New->getDeclName() 592 << NewParam->getDefaultArgRange(); 593 } else if (New->getDeclContext()->isDependentContext()) { 594 // C++ [dcl.fct.default]p6 (DR217): 595 // Default arguments for a member function of a class template shall 596 // be specified on the initial declaration of the member function 597 // within the class template. 598 // 599 // Reading the tea leaves a bit in DR217 and its reference to DR205 600 // leads me to the conclusion that one cannot add default function 601 // arguments for an out-of-line definition of a member function of a 602 // dependent type. 603 int WhichKind = 2; 604 if (CXXRecordDecl *Record 605 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 606 if (Record->getDescribedClassTemplate()) 607 WhichKind = 0; 608 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 609 WhichKind = 1; 610 else 611 WhichKind = 2; 612 } 613 614 Diag(NewParam->getLocation(), 615 diag::err_param_default_argument_member_template_redecl) 616 << WhichKind 617 << NewParam->getDefaultArgRange(); 618 } 619 } 620 } 621 622 // DR1344: If a default argument is added outside a class definition and that 623 // default argument makes the function a special member function, the program 624 // is ill-formed. This can only happen for constructors. 625 if (isa<CXXConstructorDecl>(New) && 626 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 627 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 628 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 629 if (NewSM != OldSM) { 630 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 631 assert(NewParam->hasDefaultArg()); 632 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 633 << NewParam->getDefaultArgRange() << NewSM; 634 Diag(Old->getLocation(), diag::note_previous_declaration); 635 } 636 } 637 638 const FunctionDecl *Def; 639 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 640 // template has a constexpr specifier then all its declarations shall 641 // contain the constexpr specifier. 642 if (New->getConstexprKind() != Old->getConstexprKind()) { 643 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 644 << New << New->getConstexprKind() << Old->getConstexprKind(); 645 Diag(Old->getLocation(), diag::note_previous_declaration); 646 Invalid = true; 647 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 648 Old->isDefined(Def) && 649 // If a friend function is inlined but does not have 'inline' 650 // specifier, it is a definition. Do not report attribute conflict 651 // in this case, redefinition will be diagnosed later. 652 (New->isInlineSpecified() || 653 New->getFriendObjectKind() == Decl::FOK_None)) { 654 // C++11 [dcl.fcn.spec]p4: 655 // If the definition of a function appears in a translation unit before its 656 // first declaration as inline, the program is ill-formed. 657 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 658 Diag(Def->getLocation(), diag::note_previous_definition); 659 Invalid = true; 660 } 661 662 // C++17 [temp.deduct.guide]p3: 663 // Two deduction guide declarations in the same translation unit 664 // for the same class template shall not have equivalent 665 // parameter-declaration-clauses. 666 if (isa<CXXDeductionGuideDecl>(New) && 667 !New->isFunctionTemplateSpecialization()) { 668 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 669 Diag(Old->getLocation(), diag::note_previous_declaration); 670 } 671 672 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 673 // argument expression, that declaration shall be a definition and shall be 674 // the only declaration of the function or function template in the 675 // translation unit. 676 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 677 functionDeclHasDefaultArgument(Old)) { 678 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 679 Diag(Old->getLocation(), diag::note_previous_declaration); 680 Invalid = true; 681 } 682 683 return Invalid; 684 } 685 686 NamedDecl * 687 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 688 MultiTemplateParamsArg TemplateParamLists) { 689 assert(D.isDecompositionDeclarator()); 690 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 691 692 // The syntax only allows a decomposition declarator as a simple-declaration, 693 // a for-range-declaration, or a condition in Clang, but we parse it in more 694 // cases than that. 695 if (!D.mayHaveDecompositionDeclarator()) { 696 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 697 << Decomp.getSourceRange(); 698 return nullptr; 699 } 700 701 if (!TemplateParamLists.empty()) { 702 // FIXME: There's no rule against this, but there are also no rules that 703 // would actually make it usable, so we reject it for now. 704 Diag(TemplateParamLists.front()->getTemplateLoc(), 705 diag::err_decomp_decl_template); 706 return nullptr; 707 } 708 709 Diag(Decomp.getLSquareLoc(), 710 !getLangOpts().CPlusPlus17 711 ? diag::ext_decomp_decl 712 : D.getContext() == DeclaratorContext::ConditionContext 713 ? diag::ext_decomp_decl_cond 714 : diag::warn_cxx14_compat_decomp_decl) 715 << Decomp.getSourceRange(); 716 717 // The semantic context is always just the current context. 718 DeclContext *const DC = CurContext; 719 720 // C++17 [dcl.dcl]/8: 721 // The decl-specifier-seq shall contain only the type-specifier auto 722 // and cv-qualifiers. 723 // C++2a [dcl.dcl]/8: 724 // If decl-specifier-seq contains any decl-specifier other than static, 725 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 726 auto &DS = D.getDeclSpec(); 727 { 728 SmallVector<StringRef, 8> BadSpecifiers; 729 SmallVector<SourceLocation, 8> BadSpecifierLocs; 730 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 731 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 732 if (auto SCS = DS.getStorageClassSpec()) { 733 if (SCS == DeclSpec::SCS_static) { 734 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 735 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 736 } else { 737 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 738 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 739 } 740 } 741 if (auto TSCS = DS.getThreadStorageClassSpec()) { 742 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 743 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 744 } 745 if (DS.hasConstexprSpecifier()) { 746 BadSpecifiers.push_back( 747 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 748 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 749 } 750 if (DS.isInlineSpecified()) { 751 BadSpecifiers.push_back("inline"); 752 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 753 } 754 if (!BadSpecifiers.empty()) { 755 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 756 Err << (int)BadSpecifiers.size() 757 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 758 // Don't add FixItHints to remove the specifiers; we do still respect 759 // them when building the underlying variable. 760 for (auto Loc : BadSpecifierLocs) 761 Err << SourceRange(Loc, Loc); 762 } else if (!CPlusPlus20Specifiers.empty()) { 763 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 764 getLangOpts().CPlusPlus2a 765 ? diag::warn_cxx17_compat_decomp_decl_spec 766 : diag::ext_decomp_decl_spec); 767 Warn << (int)CPlusPlus20Specifiers.size() 768 << llvm::join(CPlusPlus20Specifiers.begin(), 769 CPlusPlus20Specifiers.end(), " "); 770 for (auto Loc : CPlusPlus20SpecifierLocs) 771 Warn << SourceRange(Loc, Loc); 772 } 773 // We can't recover from it being declared as a typedef. 774 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 775 return nullptr; 776 } 777 778 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 779 QualType R = TInfo->getType(); 780 781 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 782 UPPC_DeclarationType)) 783 D.setInvalidType(); 784 785 // The syntax only allows a single ref-qualifier prior to the decomposition 786 // declarator. No other declarator chunks are permitted. Also check the type 787 // specifier here. 788 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 789 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 790 (D.getNumTypeObjects() == 1 && 791 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 792 Diag(Decomp.getLSquareLoc(), 793 (D.hasGroupingParens() || 794 (D.getNumTypeObjects() && 795 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 796 ? diag::err_decomp_decl_parens 797 : diag::err_decomp_decl_type) 798 << R; 799 800 // In most cases, there's no actual problem with an explicitly-specified 801 // type, but a function type won't work here, and ActOnVariableDeclarator 802 // shouldn't be called for such a type. 803 if (R->isFunctionType()) 804 D.setInvalidType(); 805 } 806 807 // Build the BindingDecls. 808 SmallVector<BindingDecl*, 8> Bindings; 809 810 // Build the BindingDecls. 811 for (auto &B : D.getDecompositionDeclarator().bindings()) { 812 // Check for name conflicts. 813 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 814 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 815 ForVisibleRedeclaration); 816 LookupName(Previous, S, 817 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 818 819 // It's not permitted to shadow a template parameter name. 820 if (Previous.isSingleResult() && 821 Previous.getFoundDecl()->isTemplateParameter()) { 822 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 823 Previous.getFoundDecl()); 824 Previous.clear(); 825 } 826 827 bool ConsiderLinkage = DC->isFunctionOrMethod() && 828 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 829 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 830 /*AllowInlineNamespace*/false); 831 if (!Previous.empty()) { 832 auto *Old = Previous.getRepresentativeDecl(); 833 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 834 Diag(Old->getLocation(), diag::note_previous_definition); 835 } 836 837 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 838 PushOnScopeChains(BD, S, true); 839 Bindings.push_back(BD); 840 ParsingInitForAutoVars.insert(BD); 841 } 842 843 // There are no prior lookup results for the variable itself, because it 844 // is unnamed. 845 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 846 Decomp.getLSquareLoc()); 847 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 848 ForVisibleRedeclaration); 849 850 // Build the variable that holds the non-decomposed object. 851 bool AddToScope = true; 852 NamedDecl *New = 853 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 854 MultiTemplateParamsArg(), AddToScope, Bindings); 855 if (AddToScope) { 856 S->AddDecl(New); 857 CurContext->addHiddenDecl(New); 858 } 859 860 if (isInOpenMPDeclareTargetContext()) 861 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 862 863 return New; 864 } 865 866 static bool checkSimpleDecomposition( 867 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 868 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 869 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 870 if ((int64_t)Bindings.size() != NumElems) { 871 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 872 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 873 << (NumElems < Bindings.size()); 874 return true; 875 } 876 877 unsigned I = 0; 878 for (auto *B : Bindings) { 879 SourceLocation Loc = B->getLocation(); 880 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 881 if (E.isInvalid()) 882 return true; 883 E = GetInit(Loc, E.get(), I++); 884 if (E.isInvalid()) 885 return true; 886 B->setBinding(ElemType, E.get()); 887 } 888 889 return false; 890 } 891 892 static bool checkArrayLikeDecomposition(Sema &S, 893 ArrayRef<BindingDecl *> Bindings, 894 ValueDecl *Src, QualType DecompType, 895 const llvm::APSInt &NumElems, 896 QualType ElemType) { 897 return checkSimpleDecomposition( 898 S, Bindings, Src, DecompType, NumElems, ElemType, 899 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 900 ExprResult E = S.ActOnIntegerConstant(Loc, I); 901 if (E.isInvalid()) 902 return ExprError(); 903 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 904 }); 905 } 906 907 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 908 ValueDecl *Src, QualType DecompType, 909 const ConstantArrayType *CAT) { 910 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 911 llvm::APSInt(CAT->getSize()), 912 CAT->getElementType()); 913 } 914 915 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 916 ValueDecl *Src, QualType DecompType, 917 const VectorType *VT) { 918 return checkArrayLikeDecomposition( 919 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 920 S.Context.getQualifiedType(VT->getElementType(), 921 DecompType.getQualifiers())); 922 } 923 924 static bool checkComplexDecomposition(Sema &S, 925 ArrayRef<BindingDecl *> Bindings, 926 ValueDecl *Src, QualType DecompType, 927 const ComplexType *CT) { 928 return checkSimpleDecomposition( 929 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 930 S.Context.getQualifiedType(CT->getElementType(), 931 DecompType.getQualifiers()), 932 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 933 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 934 }); 935 } 936 937 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 938 TemplateArgumentListInfo &Args) { 939 SmallString<128> SS; 940 llvm::raw_svector_ostream OS(SS); 941 bool First = true; 942 for (auto &Arg : Args.arguments()) { 943 if (!First) 944 OS << ", "; 945 Arg.getArgument().print(PrintingPolicy, OS); 946 First = false; 947 } 948 return OS.str(); 949 } 950 951 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 952 SourceLocation Loc, StringRef Trait, 953 TemplateArgumentListInfo &Args, 954 unsigned DiagID) { 955 auto DiagnoseMissing = [&] { 956 if (DiagID) 957 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 958 Args); 959 return true; 960 }; 961 962 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 963 NamespaceDecl *Std = S.getStdNamespace(); 964 if (!Std) 965 return DiagnoseMissing(); 966 967 // Look up the trait itself, within namespace std. We can diagnose various 968 // problems with this lookup even if we've been asked to not diagnose a 969 // missing specialization, because this can only fail if the user has been 970 // declaring their own names in namespace std or we don't support the 971 // standard library implementation in use. 972 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 973 Loc, Sema::LookupOrdinaryName); 974 if (!S.LookupQualifiedName(Result, Std)) 975 return DiagnoseMissing(); 976 if (Result.isAmbiguous()) 977 return true; 978 979 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 980 if (!TraitTD) { 981 Result.suppressDiagnostics(); 982 NamedDecl *Found = *Result.begin(); 983 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 984 S.Diag(Found->getLocation(), diag::note_declared_at); 985 return true; 986 } 987 988 // Build the template-id. 989 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 990 if (TraitTy.isNull()) 991 return true; 992 if (!S.isCompleteType(Loc, TraitTy)) { 993 if (DiagID) 994 S.RequireCompleteType( 995 Loc, TraitTy, DiagID, 996 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 997 return true; 998 } 999 1000 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1001 assert(RD && "specialization of class template is not a class?"); 1002 1003 // Look up the member of the trait type. 1004 S.LookupQualifiedName(TraitMemberLookup, RD); 1005 return TraitMemberLookup.isAmbiguous(); 1006 } 1007 1008 static TemplateArgumentLoc 1009 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1010 uint64_t I) { 1011 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1012 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1013 } 1014 1015 static TemplateArgumentLoc 1016 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1017 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1018 } 1019 1020 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1021 1022 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1023 llvm::APSInt &Size) { 1024 EnterExpressionEvaluationContext ContextRAII( 1025 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1026 1027 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1028 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1029 1030 // Form template argument list for tuple_size<T>. 1031 TemplateArgumentListInfo Args(Loc, Loc); 1032 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1033 1034 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1035 // it's not tuple-like. 1036 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1037 R.empty()) 1038 return IsTupleLike::NotTupleLike; 1039 1040 // If we get this far, we've committed to the tuple interpretation, but 1041 // we can still fail if there actually isn't a usable ::value. 1042 1043 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1044 LookupResult &R; 1045 TemplateArgumentListInfo &Args; 1046 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1047 : R(R), Args(Args) {} 1048 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1049 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1050 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1051 } 1052 } Diagnoser(R, Args); 1053 1054 ExprResult E = 1055 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1056 if (E.isInvalid()) 1057 return IsTupleLike::Error; 1058 1059 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1060 if (E.isInvalid()) 1061 return IsTupleLike::Error; 1062 1063 return IsTupleLike::TupleLike; 1064 } 1065 1066 /// \return std::tuple_element<I, T>::type. 1067 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1068 unsigned I, QualType T) { 1069 // Form template argument list for tuple_element<I, T>. 1070 TemplateArgumentListInfo Args(Loc, Loc); 1071 Args.addArgument( 1072 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1073 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1074 1075 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1076 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1077 if (lookupStdTypeTraitMember( 1078 S, R, Loc, "tuple_element", Args, 1079 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1080 return QualType(); 1081 1082 auto *TD = R.getAsSingle<TypeDecl>(); 1083 if (!TD) { 1084 R.suppressDiagnostics(); 1085 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1086 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1087 if (!R.empty()) 1088 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1089 return QualType(); 1090 } 1091 1092 return S.Context.getTypeDeclType(TD); 1093 } 1094 1095 namespace { 1096 struct BindingDiagnosticTrap { 1097 Sema &S; 1098 DiagnosticErrorTrap Trap; 1099 BindingDecl *BD; 1100 1101 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1102 : S(S), Trap(S.Diags), BD(BD) {} 1103 ~BindingDiagnosticTrap() { 1104 if (Trap.hasErrorOccurred()) 1105 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1106 } 1107 }; 1108 } 1109 1110 static bool checkTupleLikeDecomposition(Sema &S, 1111 ArrayRef<BindingDecl *> Bindings, 1112 VarDecl *Src, QualType DecompType, 1113 const llvm::APSInt &TupleSize) { 1114 if ((int64_t)Bindings.size() != TupleSize) { 1115 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1116 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1117 << (TupleSize < Bindings.size()); 1118 return true; 1119 } 1120 1121 if (Bindings.empty()) 1122 return false; 1123 1124 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1125 1126 // [dcl.decomp]p3: 1127 // The unqualified-id get is looked up in the scope of E by class member 1128 // access lookup ... 1129 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1130 bool UseMemberGet = false; 1131 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1132 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1133 S.LookupQualifiedName(MemberGet, RD); 1134 if (MemberGet.isAmbiguous()) 1135 return true; 1136 // ... and if that finds at least one declaration that is a function 1137 // template whose first template parameter is a non-type parameter ... 1138 for (NamedDecl *D : MemberGet) { 1139 if (FunctionTemplateDecl *FTD = 1140 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1141 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1142 if (TPL->size() != 0 && 1143 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1144 // ... the initializer is e.get<i>(). 1145 UseMemberGet = true; 1146 break; 1147 } 1148 } 1149 } 1150 } 1151 1152 unsigned I = 0; 1153 for (auto *B : Bindings) { 1154 BindingDiagnosticTrap Trap(S, B); 1155 SourceLocation Loc = B->getLocation(); 1156 1157 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1158 if (E.isInvalid()) 1159 return true; 1160 1161 // e is an lvalue if the type of the entity is an lvalue reference and 1162 // an xvalue otherwise 1163 if (!Src->getType()->isLValueReferenceType()) 1164 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1165 E.get(), nullptr, VK_XValue); 1166 1167 TemplateArgumentListInfo Args(Loc, Loc); 1168 Args.addArgument( 1169 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1170 1171 if (UseMemberGet) { 1172 // if [lookup of member get] finds at least one declaration, the 1173 // initializer is e.get<i-1>(). 1174 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1175 CXXScopeSpec(), SourceLocation(), nullptr, 1176 MemberGet, &Args, nullptr); 1177 if (E.isInvalid()) 1178 return true; 1179 1180 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1181 } else { 1182 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1183 // in the associated namespaces. 1184 Expr *Get = UnresolvedLookupExpr::Create( 1185 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1186 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1187 UnresolvedSetIterator(), UnresolvedSetIterator()); 1188 1189 Expr *Arg = E.get(); 1190 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1191 } 1192 if (E.isInvalid()) 1193 return true; 1194 Expr *Init = E.get(); 1195 1196 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1197 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1198 if (T.isNull()) 1199 return true; 1200 1201 // each vi is a variable of type "reference to T" initialized with the 1202 // initializer, where the reference is an lvalue reference if the 1203 // initializer is an lvalue and an rvalue reference otherwise 1204 QualType RefType = 1205 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1206 if (RefType.isNull()) 1207 return true; 1208 auto *RefVD = VarDecl::Create( 1209 S.Context, Src->getDeclContext(), Loc, Loc, 1210 B->getDeclName().getAsIdentifierInfo(), RefType, 1211 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1212 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1213 RefVD->setTSCSpec(Src->getTSCSpec()); 1214 RefVD->setImplicit(); 1215 if (Src->isInlineSpecified()) 1216 RefVD->setInlineSpecified(); 1217 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1218 1219 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1220 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1221 InitializationSequence Seq(S, Entity, Kind, Init); 1222 E = Seq.Perform(S, Entity, Kind, Init); 1223 if (E.isInvalid()) 1224 return true; 1225 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1226 if (E.isInvalid()) 1227 return true; 1228 RefVD->setInit(E.get()); 1229 if (!E.get()->isValueDependent()) 1230 RefVD->checkInitIsICE(); 1231 1232 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1233 DeclarationNameInfo(B->getDeclName(), Loc), 1234 RefVD); 1235 if (E.isInvalid()) 1236 return true; 1237 1238 B->setBinding(T, E.get()); 1239 I++; 1240 } 1241 1242 return false; 1243 } 1244 1245 /// Find the base class to decompose in a built-in decomposition of a class type. 1246 /// This base class search is, unfortunately, not quite like any other that we 1247 /// perform anywhere else in C++. 1248 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1249 const CXXRecordDecl *RD, 1250 CXXCastPath &BasePath) { 1251 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1252 CXXBasePath &Path) { 1253 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1254 }; 1255 1256 const CXXRecordDecl *ClassWithFields = nullptr; 1257 AccessSpecifier AS = AS_public; 1258 if (RD->hasDirectFields()) 1259 // [dcl.decomp]p4: 1260 // Otherwise, all of E's non-static data members shall be public direct 1261 // members of E ... 1262 ClassWithFields = RD; 1263 else { 1264 // ... or of ... 1265 CXXBasePaths Paths; 1266 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1267 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1268 // If no classes have fields, just decompose RD itself. (This will work 1269 // if and only if zero bindings were provided.) 1270 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1271 } 1272 1273 CXXBasePath *BestPath = nullptr; 1274 for (auto &P : Paths) { 1275 if (!BestPath) 1276 BestPath = &P; 1277 else if (!S.Context.hasSameType(P.back().Base->getType(), 1278 BestPath->back().Base->getType())) { 1279 // ... the same ... 1280 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1281 << false << RD << BestPath->back().Base->getType() 1282 << P.back().Base->getType(); 1283 return DeclAccessPair(); 1284 } else if (P.Access < BestPath->Access) { 1285 BestPath = &P; 1286 } 1287 } 1288 1289 // ... unambiguous ... 1290 QualType BaseType = BestPath->back().Base->getType(); 1291 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1292 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1293 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1294 return DeclAccessPair(); 1295 } 1296 1297 // ... [accessible, implied by other rules] base class of E. 1298 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1299 *BestPath, diag::err_decomp_decl_inaccessible_base); 1300 AS = BestPath->Access; 1301 1302 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1303 S.BuildBasePathArray(Paths, BasePath); 1304 } 1305 1306 // The above search did not check whether the selected class itself has base 1307 // classes with fields, so check that now. 1308 CXXBasePaths Paths; 1309 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1310 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1311 << (ClassWithFields == RD) << RD << ClassWithFields 1312 << Paths.front().back().Base->getType(); 1313 return DeclAccessPair(); 1314 } 1315 1316 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1317 } 1318 1319 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1320 ValueDecl *Src, QualType DecompType, 1321 const CXXRecordDecl *OrigRD) { 1322 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1323 diag::err_incomplete_type)) 1324 return true; 1325 1326 CXXCastPath BasePath; 1327 DeclAccessPair BasePair = 1328 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1329 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1330 if (!RD) 1331 return true; 1332 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1333 DecompType.getQualifiers()); 1334 1335 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1336 unsigned NumFields = 1337 std::count_if(RD->field_begin(), RD->field_end(), 1338 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1339 assert(Bindings.size() != NumFields); 1340 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1341 << DecompType << (unsigned)Bindings.size() << NumFields 1342 << (NumFields < Bindings.size()); 1343 return true; 1344 }; 1345 1346 // all of E's non-static data members shall be [...] well-formed 1347 // when named as e.name in the context of the structured binding, 1348 // E shall not have an anonymous union member, ... 1349 unsigned I = 0; 1350 for (auto *FD : RD->fields()) { 1351 if (FD->isUnnamedBitfield()) 1352 continue; 1353 1354 if (FD->isAnonymousStructOrUnion()) { 1355 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1356 << DecompType << FD->getType()->isUnionType(); 1357 S.Diag(FD->getLocation(), diag::note_declared_at); 1358 return true; 1359 } 1360 1361 // We have a real field to bind. 1362 if (I >= Bindings.size()) 1363 return DiagnoseBadNumberOfBindings(); 1364 auto *B = Bindings[I++]; 1365 SourceLocation Loc = B->getLocation(); 1366 1367 // The field must be accessible in the context of the structured binding. 1368 // We already checked that the base class is accessible. 1369 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1370 // const_cast here. 1371 S.CheckStructuredBindingMemberAccess( 1372 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1373 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1374 BasePair.getAccess(), FD->getAccess()))); 1375 1376 // Initialize the binding to Src.FD. 1377 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1378 if (E.isInvalid()) 1379 return true; 1380 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1381 VK_LValue, &BasePath); 1382 if (E.isInvalid()) 1383 return true; 1384 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1385 CXXScopeSpec(), FD, 1386 DeclAccessPair::make(FD, FD->getAccess()), 1387 DeclarationNameInfo(FD->getDeclName(), Loc)); 1388 if (E.isInvalid()) 1389 return true; 1390 1391 // If the type of the member is T, the referenced type is cv T, where cv is 1392 // the cv-qualification of the decomposition expression. 1393 // 1394 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1395 // 'const' to the type of the field. 1396 Qualifiers Q = DecompType.getQualifiers(); 1397 if (FD->isMutable()) 1398 Q.removeConst(); 1399 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1400 } 1401 1402 if (I != Bindings.size()) 1403 return DiagnoseBadNumberOfBindings(); 1404 1405 return false; 1406 } 1407 1408 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1409 QualType DecompType = DD->getType(); 1410 1411 // If the type of the decomposition is dependent, then so is the type of 1412 // each binding. 1413 if (DecompType->isDependentType()) { 1414 for (auto *B : DD->bindings()) 1415 B->setType(Context.DependentTy); 1416 return; 1417 } 1418 1419 DecompType = DecompType.getNonReferenceType(); 1420 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1421 1422 // C++1z [dcl.decomp]/2: 1423 // If E is an array type [...] 1424 // As an extension, we also support decomposition of built-in complex and 1425 // vector types. 1426 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1427 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1428 DD->setInvalidDecl(); 1429 return; 1430 } 1431 if (auto *VT = DecompType->getAs<VectorType>()) { 1432 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1433 DD->setInvalidDecl(); 1434 return; 1435 } 1436 if (auto *CT = DecompType->getAs<ComplexType>()) { 1437 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1438 DD->setInvalidDecl(); 1439 return; 1440 } 1441 1442 // C++1z [dcl.decomp]/3: 1443 // if the expression std::tuple_size<E>::value is a well-formed integral 1444 // constant expression, [...] 1445 llvm::APSInt TupleSize(32); 1446 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1447 case IsTupleLike::Error: 1448 DD->setInvalidDecl(); 1449 return; 1450 1451 case IsTupleLike::TupleLike: 1452 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1453 DD->setInvalidDecl(); 1454 return; 1455 1456 case IsTupleLike::NotTupleLike: 1457 break; 1458 } 1459 1460 // C++1z [dcl.dcl]/8: 1461 // [E shall be of array or non-union class type] 1462 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1463 if (!RD || RD->isUnion()) { 1464 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1465 << DD << !RD << DecompType; 1466 DD->setInvalidDecl(); 1467 return; 1468 } 1469 1470 // C++1z [dcl.decomp]/4: 1471 // all of E's non-static data members shall be [...] direct members of 1472 // E or of the same unambiguous public base class of E, ... 1473 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1474 DD->setInvalidDecl(); 1475 } 1476 1477 /// Merge the exception specifications of two variable declarations. 1478 /// 1479 /// This is called when there's a redeclaration of a VarDecl. The function 1480 /// checks if the redeclaration might have an exception specification and 1481 /// validates compatibility and merges the specs if necessary. 1482 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1483 // Shortcut if exceptions are disabled. 1484 if (!getLangOpts().CXXExceptions) 1485 return; 1486 1487 assert(Context.hasSameType(New->getType(), Old->getType()) && 1488 "Should only be called if types are otherwise the same."); 1489 1490 QualType NewType = New->getType(); 1491 QualType OldType = Old->getType(); 1492 1493 // We're only interested in pointers and references to functions, as well 1494 // as pointers to member functions. 1495 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1496 NewType = R->getPointeeType(); 1497 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 1498 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1499 NewType = P->getPointeeType(); 1500 OldType = OldType->getAs<PointerType>()->getPointeeType(); 1501 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1502 NewType = M->getPointeeType(); 1503 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 1504 } 1505 1506 if (!NewType->isFunctionProtoType()) 1507 return; 1508 1509 // There's lots of special cases for functions. For function pointers, system 1510 // libraries are hopefully not as broken so that we don't need these 1511 // workarounds. 1512 if (CheckEquivalentExceptionSpec( 1513 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1514 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1515 New->setInvalidDecl(); 1516 } 1517 } 1518 1519 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1520 /// function declaration are well-formed according to C++ 1521 /// [dcl.fct.default]. 1522 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1523 unsigned NumParams = FD->getNumParams(); 1524 unsigned p; 1525 1526 // Find first parameter with a default argument 1527 for (p = 0; p < NumParams; ++p) { 1528 ParmVarDecl *Param = FD->getParamDecl(p); 1529 if (Param->hasDefaultArg()) 1530 break; 1531 } 1532 1533 // C++11 [dcl.fct.default]p4: 1534 // In a given function declaration, each parameter subsequent to a parameter 1535 // with a default argument shall have a default argument supplied in this or 1536 // a previous declaration or shall be a function parameter pack. A default 1537 // argument shall not be redefined by a later declaration (not even to the 1538 // same value). 1539 unsigned LastMissingDefaultArg = 0; 1540 for (; p < NumParams; ++p) { 1541 ParmVarDecl *Param = FD->getParamDecl(p); 1542 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1543 if (Param->isInvalidDecl()) 1544 /* We already complained about this parameter. */; 1545 else if (Param->getIdentifier()) 1546 Diag(Param->getLocation(), 1547 diag::err_param_default_argument_missing_name) 1548 << Param->getIdentifier(); 1549 else 1550 Diag(Param->getLocation(), 1551 diag::err_param_default_argument_missing); 1552 1553 LastMissingDefaultArg = p; 1554 } 1555 } 1556 1557 if (LastMissingDefaultArg > 0) { 1558 // Some default arguments were missing. Clear out all of the 1559 // default arguments up to (and including) the last missing 1560 // default argument, so that we leave the function parameters 1561 // in a semantically valid state. 1562 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1563 ParmVarDecl *Param = FD->getParamDecl(p); 1564 if (Param->hasDefaultArg()) { 1565 Param->setDefaultArg(nullptr); 1566 } 1567 } 1568 } 1569 } 1570 1571 /// Check that the given type is a literal type. Issue a diagnostic if not, 1572 /// if Kind is Diagnose. 1573 /// \return \c true if a problem has been found (and optionally diagnosed). 1574 template <typename... Ts> 1575 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1576 SourceLocation Loc, QualType T, unsigned DiagID, 1577 Ts &&...DiagArgs) { 1578 if (T->isDependentType()) 1579 return false; 1580 1581 switch (Kind) { 1582 case Sema::CheckConstexprKind::Diagnose: 1583 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1584 std::forward<Ts>(DiagArgs)...); 1585 1586 case Sema::CheckConstexprKind::CheckValid: 1587 return !T->isLiteralType(SemaRef.Context); 1588 } 1589 1590 llvm_unreachable("unknown CheckConstexprKind"); 1591 } 1592 1593 // CheckConstexprParameterTypes - Check whether a function's parameter types 1594 // are all literal types. If so, return true. If not, produce a suitable 1595 // diagnostic and return false. 1596 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1597 const FunctionDecl *FD, 1598 Sema::CheckConstexprKind Kind) { 1599 unsigned ArgIndex = 0; 1600 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 1601 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1602 e = FT->param_type_end(); 1603 i != e; ++i, ++ArgIndex) { 1604 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1605 SourceLocation ParamLoc = PD->getLocation(); 1606 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1607 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1608 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1609 FD->isConsteval())) 1610 return false; 1611 } 1612 return true; 1613 } 1614 1615 /// Get diagnostic %select index for tag kind for 1616 /// record diagnostic message. 1617 /// WARNING: Indexes apply to particular diagnostics only! 1618 /// 1619 /// \returns diagnostic %select index. 1620 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1621 switch (Tag) { 1622 case TTK_Struct: return 0; 1623 case TTK_Interface: return 1; 1624 case TTK_Class: return 2; 1625 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1626 } 1627 } 1628 1629 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1630 Stmt *Body, 1631 Sema::CheckConstexprKind Kind); 1632 1633 // Check whether a function declaration satisfies the requirements of a 1634 // constexpr function definition or a constexpr constructor definition. If so, 1635 // return true. If not, produce appropriate diagnostics (unless asked not to by 1636 // Kind) and return false. 1637 // 1638 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1639 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1640 CheckConstexprKind Kind) { 1641 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1642 if (MD && MD->isInstance()) { 1643 // C++11 [dcl.constexpr]p4: 1644 // The definition of a constexpr constructor shall satisfy the following 1645 // constraints: 1646 // - the class shall not have any virtual base classes; 1647 // 1648 // FIXME: This only applies to constructors, not arbitrary member 1649 // functions. 1650 const CXXRecordDecl *RD = MD->getParent(); 1651 if (RD->getNumVBases()) { 1652 if (Kind == CheckConstexprKind::CheckValid) 1653 return false; 1654 1655 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1656 << isa<CXXConstructorDecl>(NewFD) 1657 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1658 for (const auto &I : RD->vbases()) 1659 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1660 << I.getSourceRange(); 1661 return false; 1662 } 1663 } 1664 1665 if (!isa<CXXConstructorDecl>(NewFD)) { 1666 // C++11 [dcl.constexpr]p3: 1667 // The definition of a constexpr function shall satisfy the following 1668 // constraints: 1669 // - it shall not be virtual; (removed in C++20) 1670 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1671 if (Method && Method->isVirtual()) { 1672 if (getLangOpts().CPlusPlus2a) { 1673 if (Kind == CheckConstexprKind::Diagnose) 1674 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1675 } else { 1676 if (Kind == CheckConstexprKind::CheckValid) 1677 return false; 1678 1679 Method = Method->getCanonicalDecl(); 1680 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1681 1682 // If it's not obvious why this function is virtual, find an overridden 1683 // function which uses the 'virtual' keyword. 1684 const CXXMethodDecl *WrittenVirtual = Method; 1685 while (!WrittenVirtual->isVirtualAsWritten()) 1686 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1687 if (WrittenVirtual != Method) 1688 Diag(WrittenVirtual->getLocation(), 1689 diag::note_overridden_virtual_function); 1690 return false; 1691 } 1692 } 1693 1694 // - its return type shall be a literal type; 1695 QualType RT = NewFD->getReturnType(); 1696 if (CheckLiteralType(*this, Kind, NewFD->getLocation(), RT, 1697 diag::err_constexpr_non_literal_return, 1698 NewFD->isConsteval())) 1699 return false; 1700 } 1701 1702 // - each of its parameter types shall be a literal type; 1703 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1704 return false; 1705 1706 Stmt *Body = NewFD->getBody(); 1707 assert(Body && 1708 "CheckConstexprFunctionDefinition called on function with no body"); 1709 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1710 } 1711 1712 /// Check the given declaration statement is legal within a constexpr function 1713 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1714 /// 1715 /// \return true if the body is OK (maybe only as an extension), false if we 1716 /// have diagnosed a problem. 1717 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1718 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1719 Sema::CheckConstexprKind Kind) { 1720 // C++11 [dcl.constexpr]p3 and p4: 1721 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1722 // contain only 1723 for (const auto *DclIt : DS->decls()) { 1724 switch (DclIt->getKind()) { 1725 case Decl::StaticAssert: 1726 case Decl::Using: 1727 case Decl::UsingShadow: 1728 case Decl::UsingDirective: 1729 case Decl::UnresolvedUsingTypename: 1730 case Decl::UnresolvedUsingValue: 1731 // - static_assert-declarations 1732 // - using-declarations, 1733 // - using-directives, 1734 continue; 1735 1736 case Decl::Typedef: 1737 case Decl::TypeAlias: { 1738 // - typedef declarations and alias-declarations that do not define 1739 // classes or enumerations, 1740 const auto *TN = cast<TypedefNameDecl>(DclIt); 1741 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1742 // Don't allow variably-modified types in constexpr functions. 1743 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1744 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1745 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1746 << TL.getSourceRange() << TL.getType() 1747 << isa<CXXConstructorDecl>(Dcl); 1748 } 1749 return false; 1750 } 1751 continue; 1752 } 1753 1754 case Decl::Enum: 1755 case Decl::CXXRecord: 1756 // C++1y allows types to be defined, not just declared. 1757 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1758 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1759 SemaRef.Diag(DS->getBeginLoc(), 1760 SemaRef.getLangOpts().CPlusPlus14 1761 ? diag::warn_cxx11_compat_constexpr_type_definition 1762 : diag::ext_constexpr_type_definition) 1763 << isa<CXXConstructorDecl>(Dcl); 1764 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1765 return false; 1766 } 1767 } 1768 continue; 1769 1770 case Decl::EnumConstant: 1771 case Decl::IndirectField: 1772 case Decl::ParmVar: 1773 // These can only appear with other declarations which are banned in 1774 // C++11 and permitted in C++1y, so ignore them. 1775 continue; 1776 1777 case Decl::Var: 1778 case Decl::Decomposition: { 1779 // C++1y [dcl.constexpr]p3 allows anything except: 1780 // a definition of a variable of non-literal type or of static or 1781 // thread storage duration or for which no initialization is performed. 1782 const auto *VD = cast<VarDecl>(DclIt); 1783 if (VD->isThisDeclarationADefinition()) { 1784 if (VD->isStaticLocal()) { 1785 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1786 SemaRef.Diag(VD->getLocation(), 1787 diag::err_constexpr_local_var_static) 1788 << isa<CXXConstructorDecl>(Dcl) 1789 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1790 } 1791 return false; 1792 } 1793 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1794 diag::err_constexpr_local_var_non_literal_type, 1795 isa<CXXConstructorDecl>(Dcl))) 1796 return false; 1797 if (!VD->getType()->isDependentType() && 1798 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1799 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1800 SemaRef.Diag(VD->getLocation(), 1801 diag::err_constexpr_local_var_no_init) 1802 << isa<CXXConstructorDecl>(Dcl); 1803 } 1804 return false; 1805 } 1806 } 1807 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1808 SemaRef.Diag(VD->getLocation(), 1809 SemaRef.getLangOpts().CPlusPlus14 1810 ? diag::warn_cxx11_compat_constexpr_local_var 1811 : diag::ext_constexpr_local_var) 1812 << isa<CXXConstructorDecl>(Dcl); 1813 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1814 return false; 1815 } 1816 continue; 1817 } 1818 1819 case Decl::NamespaceAlias: 1820 case Decl::Function: 1821 // These are disallowed in C++11 and permitted in C++1y. Allow them 1822 // everywhere as an extension. 1823 if (!Cxx1yLoc.isValid()) 1824 Cxx1yLoc = DS->getBeginLoc(); 1825 continue; 1826 1827 default: 1828 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1829 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1830 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1831 } 1832 return false; 1833 } 1834 } 1835 1836 return true; 1837 } 1838 1839 /// Check that the given field is initialized within a constexpr constructor. 1840 /// 1841 /// \param Dcl The constexpr constructor being checked. 1842 /// \param Field The field being checked. This may be a member of an anonymous 1843 /// struct or union nested within the class being checked. 1844 /// \param Inits All declarations, including anonymous struct/union members and 1845 /// indirect members, for which any initialization was provided. 1846 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1847 /// multiple notes for different members to the same error. 1848 /// \param Kind Whether we're diagnosing a constructor as written or determining 1849 /// whether the formal requirements are satisfied. 1850 /// \return \c false if we're checking for validity and the constructor does 1851 /// not satisfy the requirements on a constexpr constructor. 1852 static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1853 const FunctionDecl *Dcl, 1854 FieldDecl *Field, 1855 llvm::SmallSet<Decl*, 16> &Inits, 1856 bool &Diagnosed, 1857 Sema::CheckConstexprKind Kind) { 1858 if (Field->isInvalidDecl()) 1859 return true; 1860 1861 if (Field->isUnnamedBitfield()) 1862 return true; 1863 1864 // Anonymous unions with no variant members and empty anonymous structs do not 1865 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1866 // indirect fields don't need initializing. 1867 if (Field->isAnonymousStructOrUnion() && 1868 (Field->getType()->isUnionType() 1869 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1870 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1871 return true; 1872 1873 if (!Inits.count(Field)) { 1874 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1875 if (!Diagnosed) { 1876 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 1877 Diagnosed = true; 1878 } 1879 SemaRef.Diag(Field->getLocation(), 1880 diag::note_constexpr_ctor_missing_init); 1881 } else { 1882 return false; 1883 } 1884 } else if (Field->isAnonymousStructOrUnion()) { 1885 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1886 for (auto *I : RD->fields()) 1887 // If an anonymous union contains an anonymous struct of which any member 1888 // is initialized, all members must be initialized. 1889 if (!RD->isUnion() || Inits.count(I)) 1890 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 1891 Kind)) 1892 return false; 1893 } 1894 return true; 1895 } 1896 1897 /// Check the provided statement is allowed in a constexpr function 1898 /// definition. 1899 static bool 1900 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1901 SmallVectorImpl<SourceLocation> &ReturnStmts, 1902 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 1903 Sema::CheckConstexprKind Kind) { 1904 // - its function-body shall be [...] a compound-statement that contains only 1905 switch (S->getStmtClass()) { 1906 case Stmt::NullStmtClass: 1907 // - null statements, 1908 return true; 1909 1910 case Stmt::DeclStmtClass: 1911 // - static_assert-declarations 1912 // - using-declarations, 1913 // - using-directives, 1914 // - typedef declarations and alias-declarations that do not define 1915 // classes or enumerations, 1916 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 1917 return false; 1918 return true; 1919 1920 case Stmt::ReturnStmtClass: 1921 // - and exactly one return statement; 1922 if (isa<CXXConstructorDecl>(Dcl)) { 1923 // C++1y allows return statements in constexpr constructors. 1924 if (!Cxx1yLoc.isValid()) 1925 Cxx1yLoc = S->getBeginLoc(); 1926 return true; 1927 } 1928 1929 ReturnStmts.push_back(S->getBeginLoc()); 1930 return true; 1931 1932 case Stmt::CompoundStmtClass: { 1933 // C++1y allows compound-statements. 1934 if (!Cxx1yLoc.isValid()) 1935 Cxx1yLoc = S->getBeginLoc(); 1936 1937 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1938 for (auto *BodyIt : CompStmt->body()) { 1939 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1940 Cxx1yLoc, Cxx2aLoc, Kind)) 1941 return false; 1942 } 1943 return true; 1944 } 1945 1946 case Stmt::AttributedStmtClass: 1947 if (!Cxx1yLoc.isValid()) 1948 Cxx1yLoc = S->getBeginLoc(); 1949 return true; 1950 1951 case Stmt::IfStmtClass: { 1952 // C++1y allows if-statements. 1953 if (!Cxx1yLoc.isValid()) 1954 Cxx1yLoc = S->getBeginLoc(); 1955 1956 IfStmt *If = cast<IfStmt>(S); 1957 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1958 Cxx1yLoc, Cxx2aLoc, Kind)) 1959 return false; 1960 if (If->getElse() && 1961 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1962 Cxx1yLoc, Cxx2aLoc, Kind)) 1963 return false; 1964 return true; 1965 } 1966 1967 case Stmt::WhileStmtClass: 1968 case Stmt::DoStmtClass: 1969 case Stmt::ForStmtClass: 1970 case Stmt::CXXForRangeStmtClass: 1971 case Stmt::ContinueStmtClass: 1972 // C++1y allows all of these. We don't allow them as extensions in C++11, 1973 // because they don't make sense without variable mutation. 1974 if (!SemaRef.getLangOpts().CPlusPlus14) 1975 break; 1976 if (!Cxx1yLoc.isValid()) 1977 Cxx1yLoc = S->getBeginLoc(); 1978 for (Stmt *SubStmt : S->children()) 1979 if (SubStmt && 1980 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1981 Cxx1yLoc, Cxx2aLoc, Kind)) 1982 return false; 1983 return true; 1984 1985 case Stmt::SwitchStmtClass: 1986 case Stmt::CaseStmtClass: 1987 case Stmt::DefaultStmtClass: 1988 case Stmt::BreakStmtClass: 1989 // C++1y allows switch-statements, and since they don't need variable 1990 // mutation, we can reasonably allow them in C++11 as an extension. 1991 if (!Cxx1yLoc.isValid()) 1992 Cxx1yLoc = S->getBeginLoc(); 1993 for (Stmt *SubStmt : S->children()) 1994 if (SubStmt && 1995 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1996 Cxx1yLoc, Cxx2aLoc, Kind)) 1997 return false; 1998 return true; 1999 2000 case Stmt::GCCAsmStmtClass: 2001 case Stmt::MSAsmStmtClass: 2002 // C++2a allows inline assembly statements. 2003 case Stmt::CXXTryStmtClass: 2004 if (Cxx2aLoc.isInvalid()) 2005 Cxx2aLoc = S->getBeginLoc(); 2006 for (Stmt *SubStmt : S->children()) { 2007 if (SubStmt && 2008 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2009 Cxx1yLoc, Cxx2aLoc, Kind)) 2010 return false; 2011 } 2012 return true; 2013 2014 case Stmt::CXXCatchStmtClass: 2015 // Do not bother checking the language mode (already covered by the 2016 // try block check). 2017 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2018 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2019 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2020 return false; 2021 return true; 2022 2023 default: 2024 if (!isa<Expr>(S)) 2025 break; 2026 2027 // C++1y allows expression-statements. 2028 if (!Cxx1yLoc.isValid()) 2029 Cxx1yLoc = S->getBeginLoc(); 2030 return true; 2031 } 2032 2033 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2034 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2035 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2036 } 2037 return false; 2038 } 2039 2040 /// Check the body for the given constexpr function declaration only contains 2041 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2042 /// 2043 /// \return true if the body is OK, false if we have found or diagnosed a 2044 /// problem. 2045 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2046 Stmt *Body, 2047 Sema::CheckConstexprKind Kind) { 2048 SmallVector<SourceLocation, 4> ReturnStmts; 2049 2050 if (isa<CXXTryStmt>(Body)) { 2051 // C++11 [dcl.constexpr]p3: 2052 // The definition of a constexpr function shall satisfy the following 2053 // constraints: [...] 2054 // - its function-body shall be = delete, = default, or a 2055 // compound-statement 2056 // 2057 // C++11 [dcl.constexpr]p4: 2058 // In the definition of a constexpr constructor, [...] 2059 // - its function-body shall not be a function-try-block; 2060 // 2061 // This restriction is lifted in C++2a, as long as inner statements also 2062 // apply the general constexpr rules. 2063 switch (Kind) { 2064 case Sema::CheckConstexprKind::CheckValid: 2065 if (!SemaRef.getLangOpts().CPlusPlus2a) 2066 return false; 2067 break; 2068 2069 case Sema::CheckConstexprKind::Diagnose: 2070 SemaRef.Diag(Body->getBeginLoc(), 2071 !SemaRef.getLangOpts().CPlusPlus2a 2072 ? diag::ext_constexpr_function_try_block_cxx2a 2073 : diag::warn_cxx17_compat_constexpr_function_try_block) 2074 << isa<CXXConstructorDecl>(Dcl); 2075 break; 2076 } 2077 } 2078 2079 // - its function-body shall be [...] a compound-statement that contains only 2080 // [... list of cases ...] 2081 // 2082 // Note that walking the children here is enough to properly check for 2083 // CompoundStmt and CXXTryStmt body. 2084 SourceLocation Cxx1yLoc, Cxx2aLoc; 2085 for (Stmt *SubStmt : Body->children()) { 2086 if (SubStmt && 2087 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2088 Cxx1yLoc, Cxx2aLoc, Kind)) 2089 return false; 2090 } 2091 2092 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2093 // If this is only valid as an extension, report that we don't satisfy the 2094 // constraints of the current language. 2095 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2a) || 2096 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2097 return false; 2098 } else if (Cxx2aLoc.isValid()) { 2099 SemaRef.Diag(Cxx2aLoc, 2100 SemaRef.getLangOpts().CPlusPlus2a 2101 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2102 : diag::ext_constexpr_body_invalid_stmt_cxx2a) 2103 << isa<CXXConstructorDecl>(Dcl); 2104 } else if (Cxx1yLoc.isValid()) { 2105 SemaRef.Diag(Cxx1yLoc, 2106 SemaRef.getLangOpts().CPlusPlus14 2107 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2108 : diag::ext_constexpr_body_invalid_stmt) 2109 << isa<CXXConstructorDecl>(Dcl); 2110 } 2111 2112 if (const CXXConstructorDecl *Constructor 2113 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2114 const CXXRecordDecl *RD = Constructor->getParent(); 2115 // DR1359: 2116 // - every non-variant non-static data member and base class sub-object 2117 // shall be initialized; 2118 // DR1460: 2119 // - if the class is a union having variant members, exactly one of them 2120 // shall be initialized; 2121 if (RD->isUnion()) { 2122 if (Constructor->getNumCtorInitializers() == 0 && 2123 RD->hasVariantMembers()) { 2124 if (Kind == Sema::CheckConstexprKind::Diagnose) 2125 SemaRef.Diag(Dcl->getLocation(), 2126 diag::err_constexpr_union_ctor_no_init); 2127 return false; 2128 } 2129 } else if (!Constructor->isDependentContext() && 2130 !Constructor->isDelegatingConstructor()) { 2131 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2132 2133 // Skip detailed checking if we have enough initializers, and we would 2134 // allow at most one initializer per member. 2135 bool AnyAnonStructUnionMembers = false; 2136 unsigned Fields = 0; 2137 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2138 E = RD->field_end(); I != E; ++I, ++Fields) { 2139 if (I->isAnonymousStructOrUnion()) { 2140 AnyAnonStructUnionMembers = true; 2141 break; 2142 } 2143 } 2144 // DR1460: 2145 // - if the class is a union-like class, but is not a union, for each of 2146 // its anonymous union members having variant members, exactly one of 2147 // them shall be initialized; 2148 if (AnyAnonStructUnionMembers || 2149 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2150 // Check initialization of non-static data members. Base classes are 2151 // always initialized so do not need to be checked. Dependent bases 2152 // might not have initializers in the member initializer list. 2153 llvm::SmallSet<Decl*, 16> Inits; 2154 for (const auto *I: Constructor->inits()) { 2155 if (FieldDecl *FD = I->getMember()) 2156 Inits.insert(FD); 2157 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2158 Inits.insert(ID->chain_begin(), ID->chain_end()); 2159 } 2160 2161 bool Diagnosed = false; 2162 for (auto *I : RD->fields()) 2163 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2164 Kind)) 2165 return false; 2166 } 2167 } 2168 } else { 2169 if (ReturnStmts.empty()) { 2170 // C++1y doesn't require constexpr functions to contain a 'return' 2171 // statement. We still do, unless the return type might be void, because 2172 // otherwise if there's no return statement, the function cannot 2173 // be used in a core constant expression. 2174 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2175 (Dcl->getReturnType()->isVoidType() || 2176 Dcl->getReturnType()->isDependentType()); 2177 switch (Kind) { 2178 case Sema::CheckConstexprKind::Diagnose: 2179 SemaRef.Diag(Dcl->getLocation(), 2180 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2181 : diag::err_constexpr_body_no_return) 2182 << Dcl->isConsteval(); 2183 if (!OK) 2184 return false; 2185 break; 2186 2187 case Sema::CheckConstexprKind::CheckValid: 2188 // The formal requirements don't include this rule in C++14, even 2189 // though the "must be able to produce a constant expression" rules 2190 // still imply it in some cases. 2191 if (!SemaRef.getLangOpts().CPlusPlus14) 2192 return false; 2193 break; 2194 } 2195 } else if (ReturnStmts.size() > 1) { 2196 switch (Kind) { 2197 case Sema::CheckConstexprKind::Diagnose: 2198 SemaRef.Diag( 2199 ReturnStmts.back(), 2200 SemaRef.getLangOpts().CPlusPlus14 2201 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2202 : diag::ext_constexpr_body_multiple_return); 2203 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2204 SemaRef.Diag(ReturnStmts[I], 2205 diag::note_constexpr_body_previous_return); 2206 break; 2207 2208 case Sema::CheckConstexprKind::CheckValid: 2209 if (!SemaRef.getLangOpts().CPlusPlus14) 2210 return false; 2211 break; 2212 } 2213 } 2214 } 2215 2216 // C++11 [dcl.constexpr]p5: 2217 // if no function argument values exist such that the function invocation 2218 // substitution would produce a constant expression, the program is 2219 // ill-formed; no diagnostic required. 2220 // C++11 [dcl.constexpr]p3: 2221 // - every constructor call and implicit conversion used in initializing the 2222 // return value shall be one of those allowed in a constant expression. 2223 // C++11 [dcl.constexpr]p4: 2224 // - every constructor involved in initializing non-static data members and 2225 // base class sub-objects shall be a constexpr constructor. 2226 // 2227 // Note that this rule is distinct from the "requirements for a constexpr 2228 // function", so is not checked in CheckValid mode. 2229 SmallVector<PartialDiagnosticAt, 8> Diags; 2230 if (Kind == Sema::CheckConstexprKind::Diagnose && 2231 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2232 SemaRef.Diag(Dcl->getLocation(), 2233 diag::ext_constexpr_function_never_constant_expr) 2234 << isa<CXXConstructorDecl>(Dcl); 2235 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2236 SemaRef.Diag(Diags[I].first, Diags[I].second); 2237 // Don't return false here: we allow this for compatibility in 2238 // system headers. 2239 } 2240 2241 return true; 2242 } 2243 2244 /// Get the class that is directly named by the current context. This is the 2245 /// class for which an unqualified-id in this scope could name a constructor 2246 /// or destructor. 2247 /// 2248 /// If the scope specifier denotes a class, this will be that class. 2249 /// If the scope specifier is empty, this will be the class whose 2250 /// member-specification we are currently within. Otherwise, there 2251 /// is no such class. 2252 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2253 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2254 2255 if (SS && SS->isInvalid()) 2256 return nullptr; 2257 2258 if (SS && SS->isNotEmpty()) { 2259 DeclContext *DC = computeDeclContext(*SS, true); 2260 return dyn_cast_or_null<CXXRecordDecl>(DC); 2261 } 2262 2263 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2264 } 2265 2266 /// isCurrentClassName - Determine whether the identifier II is the 2267 /// name of the class type currently being defined. In the case of 2268 /// nested classes, this will only return true if II is the name of 2269 /// the innermost class. 2270 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2271 const CXXScopeSpec *SS) { 2272 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2273 return CurDecl && &II == CurDecl->getIdentifier(); 2274 } 2275 2276 /// Determine whether the identifier II is a typo for the name of 2277 /// the class type currently being defined. If so, update it to the identifier 2278 /// that should have been used. 2279 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2280 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2281 2282 if (!getLangOpts().SpellChecking) 2283 return false; 2284 2285 CXXRecordDecl *CurDecl; 2286 if (SS && SS->isSet() && !SS->isInvalid()) { 2287 DeclContext *DC = computeDeclContext(*SS, true); 2288 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2289 } else 2290 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2291 2292 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2293 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2294 < II->getLength()) { 2295 II = CurDecl->getIdentifier(); 2296 return true; 2297 } 2298 2299 return false; 2300 } 2301 2302 /// Determine whether the given class is a base class of the given 2303 /// class, including looking at dependent bases. 2304 static bool findCircularInheritance(const CXXRecordDecl *Class, 2305 const CXXRecordDecl *Current) { 2306 SmallVector<const CXXRecordDecl*, 8> Queue; 2307 2308 Class = Class->getCanonicalDecl(); 2309 while (true) { 2310 for (const auto &I : Current->bases()) { 2311 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2312 if (!Base) 2313 continue; 2314 2315 Base = Base->getDefinition(); 2316 if (!Base) 2317 continue; 2318 2319 if (Base->getCanonicalDecl() == Class) 2320 return true; 2321 2322 Queue.push_back(Base); 2323 } 2324 2325 if (Queue.empty()) 2326 return false; 2327 2328 Current = Queue.pop_back_val(); 2329 } 2330 2331 return false; 2332 } 2333 2334 /// Check the validity of a C++ base class specifier. 2335 /// 2336 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2337 /// and returns NULL otherwise. 2338 CXXBaseSpecifier * 2339 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2340 SourceRange SpecifierRange, 2341 bool Virtual, AccessSpecifier Access, 2342 TypeSourceInfo *TInfo, 2343 SourceLocation EllipsisLoc) { 2344 QualType BaseType = TInfo->getType(); 2345 2346 // C++ [class.union]p1: 2347 // A union shall not have base classes. 2348 if (Class->isUnion()) { 2349 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2350 << SpecifierRange; 2351 return nullptr; 2352 } 2353 2354 if (EllipsisLoc.isValid() && 2355 !TInfo->getType()->containsUnexpandedParameterPack()) { 2356 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2357 << TInfo->getTypeLoc().getSourceRange(); 2358 EllipsisLoc = SourceLocation(); 2359 } 2360 2361 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2362 2363 if (BaseType->isDependentType()) { 2364 // Make sure that we don't have circular inheritance among our dependent 2365 // bases. For non-dependent bases, the check for completeness below handles 2366 // this. 2367 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2368 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2369 ((BaseDecl = BaseDecl->getDefinition()) && 2370 findCircularInheritance(Class, BaseDecl))) { 2371 Diag(BaseLoc, diag::err_circular_inheritance) 2372 << BaseType << Context.getTypeDeclType(Class); 2373 2374 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2375 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2376 << BaseType; 2377 2378 return nullptr; 2379 } 2380 } 2381 2382 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2383 Class->getTagKind() == TTK_Class, 2384 Access, TInfo, EllipsisLoc); 2385 } 2386 2387 // Base specifiers must be record types. 2388 if (!BaseType->isRecordType()) { 2389 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2390 return nullptr; 2391 } 2392 2393 // C++ [class.union]p1: 2394 // A union shall not be used as a base class. 2395 if (BaseType->isUnionType()) { 2396 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2397 return nullptr; 2398 } 2399 2400 // For the MS ABI, propagate DLL attributes to base class templates. 2401 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2402 if (Attr *ClassAttr = getDLLAttr(Class)) { 2403 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2404 BaseType->getAsCXXRecordDecl())) { 2405 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2406 BaseLoc); 2407 } 2408 } 2409 } 2410 2411 // C++ [class.derived]p2: 2412 // The class-name in a base-specifier shall not be an incompletely 2413 // defined class. 2414 if (RequireCompleteType(BaseLoc, BaseType, 2415 diag::err_incomplete_base_class, SpecifierRange)) { 2416 Class->setInvalidDecl(); 2417 return nullptr; 2418 } 2419 2420 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2421 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 2422 assert(BaseDecl && "Record type has no declaration"); 2423 BaseDecl = BaseDecl->getDefinition(); 2424 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2425 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2426 assert(CXXBaseDecl && "Base type is not a C++ type"); 2427 2428 // Microsoft docs say: 2429 // "If a base-class has a code_seg attribute, derived classes must have the 2430 // same attribute." 2431 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2432 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2433 if ((DerivedCSA || BaseCSA) && 2434 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2435 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2436 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2437 << CXXBaseDecl; 2438 return nullptr; 2439 } 2440 2441 // A class which contains a flexible array member is not suitable for use as a 2442 // base class: 2443 // - If the layout determines that a base comes before another base, 2444 // the flexible array member would index into the subsequent base. 2445 // - If the layout determines that base comes before the derived class, 2446 // the flexible array member would index into the derived class. 2447 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2448 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2449 << CXXBaseDecl->getDeclName(); 2450 return nullptr; 2451 } 2452 2453 // C++ [class]p3: 2454 // If a class is marked final and it appears as a base-type-specifier in 2455 // base-clause, the program is ill-formed. 2456 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2457 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2458 << CXXBaseDecl->getDeclName() 2459 << FA->isSpelledAsSealed(); 2460 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2461 << CXXBaseDecl->getDeclName() << FA->getRange(); 2462 return nullptr; 2463 } 2464 2465 if (BaseDecl->isInvalidDecl()) 2466 Class->setInvalidDecl(); 2467 2468 // Create the base specifier. 2469 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2470 Class->getTagKind() == TTK_Class, 2471 Access, TInfo, EllipsisLoc); 2472 } 2473 2474 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2475 /// one entry in the base class list of a class specifier, for 2476 /// example: 2477 /// class foo : public bar, virtual private baz { 2478 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2479 BaseResult 2480 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2481 ParsedAttributes &Attributes, 2482 bool Virtual, AccessSpecifier Access, 2483 ParsedType basetype, SourceLocation BaseLoc, 2484 SourceLocation EllipsisLoc) { 2485 if (!classdecl) 2486 return true; 2487 2488 AdjustDeclIfTemplate(classdecl); 2489 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2490 if (!Class) 2491 return true; 2492 2493 // We haven't yet attached the base specifiers. 2494 Class->setIsParsingBaseSpecifiers(); 2495 2496 // We do not support any C++11 attributes on base-specifiers yet. 2497 // Diagnose any attributes we see. 2498 for (const ParsedAttr &AL : Attributes) { 2499 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2500 continue; 2501 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2502 ? (unsigned)diag::warn_unknown_attribute_ignored 2503 : (unsigned)diag::err_base_specifier_attribute) 2504 << AL; 2505 } 2506 2507 TypeSourceInfo *TInfo = nullptr; 2508 GetTypeFromParser(basetype, &TInfo); 2509 2510 if (EllipsisLoc.isInvalid() && 2511 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2512 UPPC_BaseType)) 2513 return true; 2514 2515 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2516 Virtual, Access, TInfo, 2517 EllipsisLoc)) 2518 return BaseSpec; 2519 else 2520 Class->setInvalidDecl(); 2521 2522 return true; 2523 } 2524 2525 /// Use small set to collect indirect bases. As this is only used 2526 /// locally, there's no need to abstract the small size parameter. 2527 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2528 2529 /// Recursively add the bases of Type. Don't add Type itself. 2530 static void 2531 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2532 const QualType &Type) 2533 { 2534 // Even though the incoming type is a base, it might not be 2535 // a class -- it could be a template parm, for instance. 2536 if (auto Rec = Type->getAs<RecordType>()) { 2537 auto Decl = Rec->getAsCXXRecordDecl(); 2538 2539 // Iterate over its bases. 2540 for (const auto &BaseSpec : Decl->bases()) { 2541 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2542 .getUnqualifiedType(); 2543 if (Set.insert(Base).second) 2544 // If we've not already seen it, recurse. 2545 NoteIndirectBases(Context, Set, Base); 2546 } 2547 } 2548 } 2549 2550 /// Performs the actual work of attaching the given base class 2551 /// specifiers to a C++ class. 2552 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2553 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2554 if (Bases.empty()) 2555 return false; 2556 2557 // Used to keep track of which base types we have already seen, so 2558 // that we can properly diagnose redundant direct base types. Note 2559 // that the key is always the unqualified canonical type of the base 2560 // class. 2561 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2562 2563 // Used to track indirect bases so we can see if a direct base is 2564 // ambiguous. 2565 IndirectBaseSet IndirectBaseTypes; 2566 2567 // Copy non-redundant base specifiers into permanent storage. 2568 unsigned NumGoodBases = 0; 2569 bool Invalid = false; 2570 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2571 QualType NewBaseType 2572 = Context.getCanonicalType(Bases[idx]->getType()); 2573 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2574 2575 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2576 if (KnownBase) { 2577 // C++ [class.mi]p3: 2578 // A class shall not be specified as a direct base class of a 2579 // derived class more than once. 2580 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2581 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2582 2583 // Delete the duplicate base class specifier; we're going to 2584 // overwrite its pointer later. 2585 Context.Deallocate(Bases[idx]); 2586 2587 Invalid = true; 2588 } else { 2589 // Okay, add this new base class. 2590 KnownBase = Bases[idx]; 2591 Bases[NumGoodBases++] = Bases[idx]; 2592 2593 // Note this base's direct & indirect bases, if there could be ambiguity. 2594 if (Bases.size() > 1) 2595 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2596 2597 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2598 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2599 if (Class->isInterface() && 2600 (!RD->isInterfaceLike() || 2601 KnownBase->getAccessSpecifier() != AS_public)) { 2602 // The Microsoft extension __interface does not permit bases that 2603 // are not themselves public interfaces. 2604 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2605 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2606 << RD->getSourceRange(); 2607 Invalid = true; 2608 } 2609 if (RD->hasAttr<WeakAttr>()) 2610 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2611 } 2612 } 2613 } 2614 2615 // Attach the remaining base class specifiers to the derived class. 2616 Class->setBases(Bases.data(), NumGoodBases); 2617 2618 // Check that the only base classes that are duplicate are virtual. 2619 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2620 // Check whether this direct base is inaccessible due to ambiguity. 2621 QualType BaseType = Bases[idx]->getType(); 2622 2623 // Skip all dependent types in templates being used as base specifiers. 2624 // Checks below assume that the base specifier is a CXXRecord. 2625 if (BaseType->isDependentType()) 2626 continue; 2627 2628 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2629 .getUnqualifiedType(); 2630 2631 if (IndirectBaseTypes.count(CanonicalBase)) { 2632 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2633 /*DetectVirtual=*/true); 2634 bool found 2635 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2636 assert(found); 2637 (void)found; 2638 2639 if (Paths.isAmbiguous(CanonicalBase)) 2640 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2641 << BaseType << getAmbiguousPathsDisplayString(Paths) 2642 << Bases[idx]->getSourceRange(); 2643 else 2644 assert(Bases[idx]->isVirtual()); 2645 } 2646 2647 // Delete the base class specifier, since its data has been copied 2648 // into the CXXRecordDecl. 2649 Context.Deallocate(Bases[idx]); 2650 } 2651 2652 return Invalid; 2653 } 2654 2655 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2656 /// class, after checking whether there are any duplicate base 2657 /// classes. 2658 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2659 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2660 if (!ClassDecl || Bases.empty()) 2661 return; 2662 2663 AdjustDeclIfTemplate(ClassDecl); 2664 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2665 } 2666 2667 /// Determine whether the type \p Derived is a C++ class that is 2668 /// derived from the type \p Base. 2669 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2670 if (!getLangOpts().CPlusPlus) 2671 return false; 2672 2673 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2674 if (!DerivedRD) 2675 return false; 2676 2677 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2678 if (!BaseRD) 2679 return false; 2680 2681 // If either the base or the derived type is invalid, don't try to 2682 // check whether one is derived from the other. 2683 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2684 return false; 2685 2686 // FIXME: In a modules build, do we need the entire path to be visible for us 2687 // to be able to use the inheritance relationship? 2688 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2689 return false; 2690 2691 return DerivedRD->isDerivedFrom(BaseRD); 2692 } 2693 2694 /// Determine whether the type \p Derived is a C++ class that is 2695 /// derived from the type \p Base. 2696 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2697 CXXBasePaths &Paths) { 2698 if (!getLangOpts().CPlusPlus) 2699 return false; 2700 2701 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2702 if (!DerivedRD) 2703 return false; 2704 2705 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2706 if (!BaseRD) 2707 return false; 2708 2709 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2710 return false; 2711 2712 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2713 } 2714 2715 static void BuildBasePathArray(const CXXBasePath &Path, 2716 CXXCastPath &BasePathArray) { 2717 // We first go backward and check if we have a virtual base. 2718 // FIXME: It would be better if CXXBasePath had the base specifier for 2719 // the nearest virtual base. 2720 unsigned Start = 0; 2721 for (unsigned I = Path.size(); I != 0; --I) { 2722 if (Path[I - 1].Base->isVirtual()) { 2723 Start = I - 1; 2724 break; 2725 } 2726 } 2727 2728 // Now add all bases. 2729 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2730 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2731 } 2732 2733 2734 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2735 CXXCastPath &BasePathArray) { 2736 assert(BasePathArray.empty() && "Base path array must be empty!"); 2737 assert(Paths.isRecordingPaths() && "Must record paths!"); 2738 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2739 } 2740 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2741 /// conversion (where Derived and Base are class types) is 2742 /// well-formed, meaning that the conversion is unambiguous (and 2743 /// that all of the base classes are accessible). Returns true 2744 /// and emits a diagnostic if the code is ill-formed, returns false 2745 /// otherwise. Loc is the location where this routine should point to 2746 /// if there is an error, and Range is the source range to highlight 2747 /// if there is an error. 2748 /// 2749 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2750 /// diagnostic for the respective type of error will be suppressed, but the 2751 /// check for ill-formed code will still be performed. 2752 bool 2753 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2754 unsigned InaccessibleBaseID, 2755 unsigned AmbigiousBaseConvID, 2756 SourceLocation Loc, SourceRange Range, 2757 DeclarationName Name, 2758 CXXCastPath *BasePath, 2759 bool IgnoreAccess) { 2760 // First, determine whether the path from Derived to Base is 2761 // ambiguous. This is slightly more expensive than checking whether 2762 // the Derived to Base conversion exists, because here we need to 2763 // explore multiple paths to determine if there is an ambiguity. 2764 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2765 /*DetectVirtual=*/false); 2766 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2767 if (!DerivationOkay) 2768 return true; 2769 2770 const CXXBasePath *Path = nullptr; 2771 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2772 Path = &Paths.front(); 2773 2774 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2775 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2776 // user to access such bases. 2777 if (!Path && getLangOpts().MSVCCompat) { 2778 for (const CXXBasePath &PossiblePath : Paths) { 2779 if (PossiblePath.size() == 1) { 2780 Path = &PossiblePath; 2781 if (AmbigiousBaseConvID) 2782 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2783 << Base << Derived << Range; 2784 break; 2785 } 2786 } 2787 } 2788 2789 if (Path) { 2790 if (!IgnoreAccess) { 2791 // Check that the base class can be accessed. 2792 switch ( 2793 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2794 case AR_inaccessible: 2795 return true; 2796 case AR_accessible: 2797 case AR_dependent: 2798 case AR_delayed: 2799 break; 2800 } 2801 } 2802 2803 // Build a base path if necessary. 2804 if (BasePath) 2805 ::BuildBasePathArray(*Path, *BasePath); 2806 return false; 2807 } 2808 2809 if (AmbigiousBaseConvID) { 2810 // We know that the derived-to-base conversion is ambiguous, and 2811 // we're going to produce a diagnostic. Perform the derived-to-base 2812 // search just one more time to compute all of the possible paths so 2813 // that we can print them out. This is more expensive than any of 2814 // the previous derived-to-base checks we've done, but at this point 2815 // performance isn't as much of an issue. 2816 Paths.clear(); 2817 Paths.setRecordingPaths(true); 2818 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2819 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2820 (void)StillOkay; 2821 2822 // Build up a textual representation of the ambiguous paths, e.g., 2823 // D -> B -> A, that will be used to illustrate the ambiguous 2824 // conversions in the diagnostic. We only print one of the paths 2825 // to each base class subobject. 2826 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2827 2828 Diag(Loc, AmbigiousBaseConvID) 2829 << Derived << Base << PathDisplayStr << Range << Name; 2830 } 2831 return true; 2832 } 2833 2834 bool 2835 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2836 SourceLocation Loc, SourceRange Range, 2837 CXXCastPath *BasePath, 2838 bool IgnoreAccess) { 2839 return CheckDerivedToBaseConversion( 2840 Derived, Base, diag::err_upcast_to_inaccessible_base, 2841 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2842 BasePath, IgnoreAccess); 2843 } 2844 2845 2846 /// Builds a string representing ambiguous paths from a 2847 /// specific derived class to different subobjects of the same base 2848 /// class. 2849 /// 2850 /// This function builds a string that can be used in error messages 2851 /// to show the different paths that one can take through the 2852 /// inheritance hierarchy to go from the derived class to different 2853 /// subobjects of a base class. The result looks something like this: 2854 /// @code 2855 /// struct D -> struct B -> struct A 2856 /// struct D -> struct C -> struct A 2857 /// @endcode 2858 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2859 std::string PathDisplayStr; 2860 std::set<unsigned> DisplayedPaths; 2861 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2862 Path != Paths.end(); ++Path) { 2863 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2864 // We haven't displayed a path to this particular base 2865 // class subobject yet. 2866 PathDisplayStr += "\n "; 2867 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2868 for (CXXBasePath::const_iterator Element = Path->begin(); 2869 Element != Path->end(); ++Element) 2870 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2871 } 2872 } 2873 2874 return PathDisplayStr; 2875 } 2876 2877 //===----------------------------------------------------------------------===// 2878 // C++ class member Handling 2879 //===----------------------------------------------------------------------===// 2880 2881 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2882 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 2883 SourceLocation ColonLoc, 2884 const ParsedAttributesView &Attrs) { 2885 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2886 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2887 ASLoc, ColonLoc); 2888 CurContext->addHiddenDecl(ASDecl); 2889 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2890 } 2891 2892 /// CheckOverrideControl - Check C++11 override control semantics. 2893 void Sema::CheckOverrideControl(NamedDecl *D) { 2894 if (D->isInvalidDecl()) 2895 return; 2896 2897 // We only care about "override" and "final" declarations. 2898 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2899 return; 2900 2901 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2902 2903 // We can't check dependent instance methods. 2904 if (MD && MD->isInstance() && 2905 (MD->getParent()->hasAnyDependentBases() || 2906 MD->getType()->isDependentType())) 2907 return; 2908 2909 if (MD && !MD->isVirtual()) { 2910 // If we have a non-virtual method, check if if hides a virtual method. 2911 // (In that case, it's most likely the method has the wrong type.) 2912 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2913 FindHiddenVirtualMethods(MD, OverloadedMethods); 2914 2915 if (!OverloadedMethods.empty()) { 2916 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2917 Diag(OA->getLocation(), 2918 diag::override_keyword_hides_virtual_member_function) 2919 << "override" << (OverloadedMethods.size() > 1); 2920 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2921 Diag(FA->getLocation(), 2922 diag::override_keyword_hides_virtual_member_function) 2923 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2924 << (OverloadedMethods.size() > 1); 2925 } 2926 NoteHiddenVirtualMethods(MD, OverloadedMethods); 2927 MD->setInvalidDecl(); 2928 return; 2929 } 2930 // Fall through into the general case diagnostic. 2931 // FIXME: We might want to attempt typo correction here. 2932 } 2933 2934 if (!MD || !MD->isVirtual()) { 2935 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2936 Diag(OA->getLocation(), 2937 diag::override_keyword_only_allowed_on_virtual_member_functions) 2938 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 2939 D->dropAttr<OverrideAttr>(); 2940 } 2941 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2942 Diag(FA->getLocation(), 2943 diag::override_keyword_only_allowed_on_virtual_member_functions) 2944 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2945 << FixItHint::CreateRemoval(FA->getLocation()); 2946 D->dropAttr<FinalAttr>(); 2947 } 2948 return; 2949 } 2950 2951 // C++11 [class.virtual]p5: 2952 // If a function is marked with the virt-specifier override and 2953 // does not override a member function of a base class, the program is 2954 // ill-formed. 2955 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 2956 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 2957 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 2958 << MD->getDeclName(); 2959 } 2960 2961 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 2962 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 2963 return; 2964 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2965 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 2966 return; 2967 2968 SourceLocation Loc = MD->getLocation(); 2969 SourceLocation SpellingLoc = Loc; 2970 if (getSourceManager().isMacroArgExpansion(Loc)) 2971 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 2972 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 2973 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 2974 return; 2975 2976 if (MD->size_overridden_methods() > 0) { 2977 unsigned DiagID = isa<CXXDestructorDecl>(MD) 2978 ? diag::warn_destructor_marked_not_override_overriding 2979 : diag::warn_function_marked_not_override_overriding; 2980 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 2981 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 2982 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 2983 } 2984 } 2985 2986 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 2987 /// function overrides a virtual member function marked 'final', according to 2988 /// C++11 [class.virtual]p4. 2989 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 2990 const CXXMethodDecl *Old) { 2991 FinalAttr *FA = Old->getAttr<FinalAttr>(); 2992 if (!FA) 2993 return false; 2994 2995 Diag(New->getLocation(), diag::err_final_function_overridden) 2996 << New->getDeclName() 2997 << FA->isSpelledAsSealed(); 2998 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 2999 return true; 3000 } 3001 3002 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3003 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3004 // FIXME: Destruction of ObjC lifetime types has side-effects. 3005 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3006 return !RD->isCompleteDefinition() || 3007 !RD->hasTrivialDefaultConstructor() || 3008 !RD->hasTrivialDestructor(); 3009 return false; 3010 } 3011 3012 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3013 ParsedAttributesView::const_iterator Itr = 3014 llvm::find_if(list, [](const ParsedAttr &AL) { 3015 return AL.isDeclspecPropertyAttribute(); 3016 }); 3017 if (Itr != list.end()) 3018 return &*Itr; 3019 return nullptr; 3020 } 3021 3022 // Check if there is a field shadowing. 3023 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3024 DeclarationName FieldName, 3025 const CXXRecordDecl *RD, 3026 bool DeclIsField) { 3027 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3028 return; 3029 3030 // To record a shadowed field in a base 3031 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3032 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3033 CXXBasePath &Path) { 3034 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3035 // Record an ambiguous path directly 3036 if (Bases.find(Base) != Bases.end()) 3037 return true; 3038 for (const auto Field : Base->lookup(FieldName)) { 3039 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3040 Field->getAccess() != AS_private) { 3041 assert(Field->getAccess() != AS_none); 3042 assert(Bases.find(Base) == Bases.end()); 3043 Bases[Base] = Field; 3044 return true; 3045 } 3046 } 3047 return false; 3048 }; 3049 3050 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3051 /*DetectVirtual=*/true); 3052 if (!RD->lookupInBases(FieldShadowed, Paths)) 3053 return; 3054 3055 for (const auto &P : Paths) { 3056 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3057 auto It = Bases.find(Base); 3058 // Skip duplicated bases 3059 if (It == Bases.end()) 3060 continue; 3061 auto BaseField = It->second; 3062 assert(BaseField->getAccess() != AS_private); 3063 if (AS_none != 3064 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3065 Diag(Loc, diag::warn_shadow_field) 3066 << FieldName << RD << Base << DeclIsField; 3067 Diag(BaseField->getLocation(), diag::note_shadow_field); 3068 Bases.erase(It); 3069 } 3070 } 3071 } 3072 3073 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3074 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3075 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3076 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3077 /// present (but parsing it has been deferred). 3078 NamedDecl * 3079 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3080 MultiTemplateParamsArg TemplateParameterLists, 3081 Expr *BW, const VirtSpecifiers &VS, 3082 InClassInitStyle InitStyle) { 3083 const DeclSpec &DS = D.getDeclSpec(); 3084 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3085 DeclarationName Name = NameInfo.getName(); 3086 SourceLocation Loc = NameInfo.getLoc(); 3087 3088 // For anonymous bitfields, the location should point to the type. 3089 if (Loc.isInvalid()) 3090 Loc = D.getBeginLoc(); 3091 3092 Expr *BitWidth = static_cast<Expr*>(BW); 3093 3094 assert(isa<CXXRecordDecl>(CurContext)); 3095 assert(!DS.isFriendSpecified()); 3096 3097 bool isFunc = D.isDeclarationOfFunction(); 3098 const ParsedAttr *MSPropertyAttr = 3099 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3100 3101 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3102 // The Microsoft extension __interface only permits public member functions 3103 // and prohibits constructors, destructors, operators, non-public member 3104 // functions, static methods and data members. 3105 unsigned InvalidDecl; 3106 bool ShowDeclName = true; 3107 if (!isFunc && 3108 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3109 InvalidDecl = 0; 3110 else if (!isFunc) 3111 InvalidDecl = 1; 3112 else if (AS != AS_public) 3113 InvalidDecl = 2; 3114 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3115 InvalidDecl = 3; 3116 else switch (Name.getNameKind()) { 3117 case DeclarationName::CXXConstructorName: 3118 InvalidDecl = 4; 3119 ShowDeclName = false; 3120 break; 3121 3122 case DeclarationName::CXXDestructorName: 3123 InvalidDecl = 5; 3124 ShowDeclName = false; 3125 break; 3126 3127 case DeclarationName::CXXOperatorName: 3128 case DeclarationName::CXXConversionFunctionName: 3129 InvalidDecl = 6; 3130 break; 3131 3132 default: 3133 InvalidDecl = 0; 3134 break; 3135 } 3136 3137 if (InvalidDecl) { 3138 if (ShowDeclName) 3139 Diag(Loc, diag::err_invalid_member_in_interface) 3140 << (InvalidDecl-1) << Name; 3141 else 3142 Diag(Loc, diag::err_invalid_member_in_interface) 3143 << (InvalidDecl-1) << ""; 3144 return nullptr; 3145 } 3146 } 3147 3148 // C++ 9.2p6: A member shall not be declared to have automatic storage 3149 // duration (auto, register) or with the extern storage-class-specifier. 3150 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3151 // data members and cannot be applied to names declared const or static, 3152 // and cannot be applied to reference members. 3153 switch (DS.getStorageClassSpec()) { 3154 case DeclSpec::SCS_unspecified: 3155 case DeclSpec::SCS_typedef: 3156 case DeclSpec::SCS_static: 3157 break; 3158 case DeclSpec::SCS_mutable: 3159 if (isFunc) { 3160 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3161 3162 // FIXME: It would be nicer if the keyword was ignored only for this 3163 // declarator. Otherwise we could get follow-up errors. 3164 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3165 } 3166 break; 3167 default: 3168 Diag(DS.getStorageClassSpecLoc(), 3169 diag::err_storageclass_invalid_for_member); 3170 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3171 break; 3172 } 3173 3174 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3175 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3176 !isFunc); 3177 3178 if (DS.hasConstexprSpecifier() && isInstField) { 3179 SemaDiagnosticBuilder B = 3180 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3181 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3182 if (InitStyle == ICIS_NoInit) { 3183 B << 0 << 0; 3184 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3185 B << FixItHint::CreateRemoval(ConstexprLoc); 3186 else { 3187 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3188 D.getMutableDeclSpec().ClearConstexprSpec(); 3189 const char *PrevSpec; 3190 unsigned DiagID; 3191 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3192 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3193 (void)Failed; 3194 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3195 } 3196 } else { 3197 B << 1; 3198 const char *PrevSpec; 3199 unsigned DiagID; 3200 if (D.getMutableDeclSpec().SetStorageClassSpec( 3201 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3202 Context.getPrintingPolicy())) { 3203 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3204 "This is the only DeclSpec that should fail to be applied"); 3205 B << 1; 3206 } else { 3207 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3208 isInstField = false; 3209 } 3210 } 3211 } 3212 3213 NamedDecl *Member; 3214 if (isInstField) { 3215 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3216 3217 // Data members must have identifiers for names. 3218 if (!Name.isIdentifier()) { 3219 Diag(Loc, diag::err_bad_variable_name) 3220 << Name; 3221 return nullptr; 3222 } 3223 3224 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3225 3226 // Member field could not be with "template" keyword. 3227 // So TemplateParameterLists should be empty in this case. 3228 if (TemplateParameterLists.size()) { 3229 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3230 if (TemplateParams->size()) { 3231 // There is no such thing as a member field template. 3232 Diag(D.getIdentifierLoc(), diag::err_template_member) 3233 << II 3234 << SourceRange(TemplateParams->getTemplateLoc(), 3235 TemplateParams->getRAngleLoc()); 3236 } else { 3237 // There is an extraneous 'template<>' for this member. 3238 Diag(TemplateParams->getTemplateLoc(), 3239 diag::err_template_member_noparams) 3240 << II 3241 << SourceRange(TemplateParams->getTemplateLoc(), 3242 TemplateParams->getRAngleLoc()); 3243 } 3244 return nullptr; 3245 } 3246 3247 if (SS.isSet() && !SS.isInvalid()) { 3248 // The user provided a superfluous scope specifier inside a class 3249 // definition: 3250 // 3251 // class X { 3252 // int X::member; 3253 // }; 3254 if (DeclContext *DC = computeDeclContext(SS, false)) 3255 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3256 D.getName().getKind() == 3257 UnqualifiedIdKind::IK_TemplateId); 3258 else 3259 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3260 << Name << SS.getRange(); 3261 3262 SS.clear(); 3263 } 3264 3265 if (MSPropertyAttr) { 3266 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3267 BitWidth, InitStyle, AS, *MSPropertyAttr); 3268 if (!Member) 3269 return nullptr; 3270 isInstField = false; 3271 } else { 3272 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3273 BitWidth, InitStyle, AS); 3274 if (!Member) 3275 return nullptr; 3276 } 3277 3278 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3279 } else { 3280 Member = HandleDeclarator(S, D, TemplateParameterLists); 3281 if (!Member) 3282 return nullptr; 3283 3284 // Non-instance-fields can't have a bitfield. 3285 if (BitWidth) { 3286 if (Member->isInvalidDecl()) { 3287 // don't emit another diagnostic. 3288 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3289 // C++ 9.6p3: A bit-field shall not be a static member. 3290 // "static member 'A' cannot be a bit-field" 3291 Diag(Loc, diag::err_static_not_bitfield) 3292 << Name << BitWidth->getSourceRange(); 3293 } else if (isa<TypedefDecl>(Member)) { 3294 // "typedef member 'x' cannot be a bit-field" 3295 Diag(Loc, diag::err_typedef_not_bitfield) 3296 << Name << BitWidth->getSourceRange(); 3297 } else { 3298 // A function typedef ("typedef int f(); f a;"). 3299 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3300 Diag(Loc, diag::err_not_integral_type_bitfield) 3301 << Name << cast<ValueDecl>(Member)->getType() 3302 << BitWidth->getSourceRange(); 3303 } 3304 3305 BitWidth = nullptr; 3306 Member->setInvalidDecl(); 3307 } 3308 3309 NamedDecl *NonTemplateMember = Member; 3310 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3311 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3312 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3313 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3314 3315 Member->setAccess(AS); 3316 3317 // If we have declared a member function template or static data member 3318 // template, set the access of the templated declaration as well. 3319 if (NonTemplateMember != Member) 3320 NonTemplateMember->setAccess(AS); 3321 3322 // C++ [temp.deduct.guide]p3: 3323 // A deduction guide [...] for a member class template [shall be 3324 // declared] with the same access [as the template]. 3325 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3326 auto *TD = DG->getDeducedTemplate(); 3327 // Access specifiers are only meaningful if both the template and the 3328 // deduction guide are from the same scope. 3329 if (AS != TD->getAccess() && 3330 TD->getDeclContext()->getRedeclContext()->Equals( 3331 DG->getDeclContext()->getRedeclContext())) { 3332 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3333 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3334 << TD->getAccess(); 3335 const AccessSpecDecl *LastAccessSpec = nullptr; 3336 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3337 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3338 LastAccessSpec = AccessSpec; 3339 } 3340 assert(LastAccessSpec && "differing access with no access specifier"); 3341 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3342 << AS; 3343 } 3344 } 3345 } 3346 3347 if (VS.isOverrideSpecified()) 3348 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3349 AttributeCommonInfo::AS_Keyword)); 3350 if (VS.isFinalSpecified()) 3351 Member->addAttr(FinalAttr::Create( 3352 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3353 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3354 3355 if (VS.getLastLocation().isValid()) { 3356 // Update the end location of a method that has a virt-specifiers. 3357 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3358 MD->setRangeEnd(VS.getLastLocation()); 3359 } 3360 3361 CheckOverrideControl(Member); 3362 3363 assert((Name || isInstField) && "No identifier for non-field ?"); 3364 3365 if (isInstField) { 3366 FieldDecl *FD = cast<FieldDecl>(Member); 3367 FieldCollector->Add(FD); 3368 3369 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3370 // Remember all explicit private FieldDecls that have a name, no side 3371 // effects and are not part of a dependent type declaration. 3372 if (!FD->isImplicit() && FD->getDeclName() && 3373 FD->getAccess() == AS_private && 3374 !FD->hasAttr<UnusedAttr>() && 3375 !FD->getParent()->isDependentContext() && 3376 !InitializationHasSideEffects(*FD)) 3377 UnusedPrivateFields.insert(FD); 3378 } 3379 } 3380 3381 return Member; 3382 } 3383 3384 namespace { 3385 class UninitializedFieldVisitor 3386 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3387 Sema &S; 3388 // List of Decls to generate a warning on. Also remove Decls that become 3389 // initialized. 3390 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3391 // List of base classes of the record. Classes are removed after their 3392 // initializers. 3393 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3394 // Vector of decls to be removed from the Decl set prior to visiting the 3395 // nodes. These Decls may have been initialized in the prior initializer. 3396 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3397 // If non-null, add a note to the warning pointing back to the constructor. 3398 const CXXConstructorDecl *Constructor; 3399 // Variables to hold state when processing an initializer list. When 3400 // InitList is true, special case initialization of FieldDecls matching 3401 // InitListFieldDecl. 3402 bool InitList; 3403 FieldDecl *InitListFieldDecl; 3404 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3405 3406 public: 3407 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3408 UninitializedFieldVisitor(Sema &S, 3409 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3410 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3411 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3412 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3413 3414 // Returns true if the use of ME is not an uninitialized use. 3415 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3416 bool CheckReferenceOnly) { 3417 llvm::SmallVector<FieldDecl*, 4> Fields; 3418 bool ReferenceField = false; 3419 while (ME) { 3420 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3421 if (!FD) 3422 return false; 3423 Fields.push_back(FD); 3424 if (FD->getType()->isReferenceType()) 3425 ReferenceField = true; 3426 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3427 } 3428 3429 // Binding a reference to an uninitialized field is not an 3430 // uninitialized use. 3431 if (CheckReferenceOnly && !ReferenceField) 3432 return true; 3433 3434 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3435 // Discard the first field since it is the field decl that is being 3436 // initialized. 3437 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3438 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3439 } 3440 3441 for (auto UsedIter = UsedFieldIndex.begin(), 3442 UsedEnd = UsedFieldIndex.end(), 3443 OrigIter = InitFieldIndex.begin(), 3444 OrigEnd = InitFieldIndex.end(); 3445 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3446 if (*UsedIter < *OrigIter) 3447 return true; 3448 if (*UsedIter > *OrigIter) 3449 break; 3450 } 3451 3452 return false; 3453 } 3454 3455 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3456 bool AddressOf) { 3457 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3458 return; 3459 3460 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3461 // or union. 3462 MemberExpr *FieldME = ME; 3463 3464 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3465 3466 Expr *Base = ME; 3467 while (MemberExpr *SubME = 3468 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3469 3470 if (isa<VarDecl>(SubME->getMemberDecl())) 3471 return; 3472 3473 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3474 if (!FD->isAnonymousStructOrUnion()) 3475 FieldME = SubME; 3476 3477 if (!FieldME->getType().isPODType(S.Context)) 3478 AllPODFields = false; 3479 3480 Base = SubME->getBase(); 3481 } 3482 3483 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3484 return; 3485 3486 if (AddressOf && AllPODFields) 3487 return; 3488 3489 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3490 3491 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3492 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3493 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3494 } 3495 3496 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3497 QualType T = BaseCast->getType(); 3498 if (T->isPointerType() && 3499 BaseClasses.count(T->getPointeeType())) { 3500 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3501 << T->getPointeeType() << FoundVD; 3502 } 3503 } 3504 } 3505 3506 if (!Decls.count(FoundVD)) 3507 return; 3508 3509 const bool IsReference = FoundVD->getType()->isReferenceType(); 3510 3511 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3512 // Special checking for initializer lists. 3513 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3514 return; 3515 } 3516 } else { 3517 // Prevent double warnings on use of unbounded references. 3518 if (CheckReferenceOnly && !IsReference) 3519 return; 3520 } 3521 3522 unsigned diag = IsReference 3523 ? diag::warn_reference_field_is_uninit 3524 : diag::warn_field_is_uninit; 3525 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3526 if (Constructor) 3527 S.Diag(Constructor->getLocation(), 3528 diag::note_uninit_in_this_constructor) 3529 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3530 3531 } 3532 3533 void HandleValue(Expr *E, bool AddressOf) { 3534 E = E->IgnoreParens(); 3535 3536 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3537 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3538 AddressOf /*AddressOf*/); 3539 return; 3540 } 3541 3542 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3543 Visit(CO->getCond()); 3544 HandleValue(CO->getTrueExpr(), AddressOf); 3545 HandleValue(CO->getFalseExpr(), AddressOf); 3546 return; 3547 } 3548 3549 if (BinaryConditionalOperator *BCO = 3550 dyn_cast<BinaryConditionalOperator>(E)) { 3551 Visit(BCO->getCond()); 3552 HandleValue(BCO->getFalseExpr(), AddressOf); 3553 return; 3554 } 3555 3556 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3557 HandleValue(OVE->getSourceExpr(), AddressOf); 3558 return; 3559 } 3560 3561 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3562 switch (BO->getOpcode()) { 3563 default: 3564 break; 3565 case(BO_PtrMemD): 3566 case(BO_PtrMemI): 3567 HandleValue(BO->getLHS(), AddressOf); 3568 Visit(BO->getRHS()); 3569 return; 3570 case(BO_Comma): 3571 Visit(BO->getLHS()); 3572 HandleValue(BO->getRHS(), AddressOf); 3573 return; 3574 } 3575 } 3576 3577 Visit(E); 3578 } 3579 3580 void CheckInitListExpr(InitListExpr *ILE) { 3581 InitFieldIndex.push_back(0); 3582 for (auto Child : ILE->children()) { 3583 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3584 CheckInitListExpr(SubList); 3585 } else { 3586 Visit(Child); 3587 } 3588 ++InitFieldIndex.back(); 3589 } 3590 InitFieldIndex.pop_back(); 3591 } 3592 3593 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3594 FieldDecl *Field, const Type *BaseClass) { 3595 // Remove Decls that may have been initialized in the previous 3596 // initializer. 3597 for (ValueDecl* VD : DeclsToRemove) 3598 Decls.erase(VD); 3599 DeclsToRemove.clear(); 3600 3601 Constructor = FieldConstructor; 3602 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3603 3604 if (ILE && Field) { 3605 InitList = true; 3606 InitListFieldDecl = Field; 3607 InitFieldIndex.clear(); 3608 CheckInitListExpr(ILE); 3609 } else { 3610 InitList = false; 3611 Visit(E); 3612 } 3613 3614 if (Field) 3615 Decls.erase(Field); 3616 if (BaseClass) 3617 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3618 } 3619 3620 void VisitMemberExpr(MemberExpr *ME) { 3621 // All uses of unbounded reference fields will warn. 3622 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3623 } 3624 3625 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3626 if (E->getCastKind() == CK_LValueToRValue) { 3627 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3628 return; 3629 } 3630 3631 Inherited::VisitImplicitCastExpr(E); 3632 } 3633 3634 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3635 if (E->getConstructor()->isCopyConstructor()) { 3636 Expr *ArgExpr = E->getArg(0); 3637 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3638 if (ILE->getNumInits() == 1) 3639 ArgExpr = ILE->getInit(0); 3640 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3641 if (ICE->getCastKind() == CK_NoOp) 3642 ArgExpr = ICE->getSubExpr(); 3643 HandleValue(ArgExpr, false /*AddressOf*/); 3644 return; 3645 } 3646 Inherited::VisitCXXConstructExpr(E); 3647 } 3648 3649 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3650 Expr *Callee = E->getCallee(); 3651 if (isa<MemberExpr>(Callee)) { 3652 HandleValue(Callee, false /*AddressOf*/); 3653 for (auto Arg : E->arguments()) 3654 Visit(Arg); 3655 return; 3656 } 3657 3658 Inherited::VisitCXXMemberCallExpr(E); 3659 } 3660 3661 void VisitCallExpr(CallExpr *E) { 3662 // Treat std::move as a use. 3663 if (E->isCallToStdMove()) { 3664 HandleValue(E->getArg(0), /*AddressOf=*/false); 3665 return; 3666 } 3667 3668 Inherited::VisitCallExpr(E); 3669 } 3670 3671 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3672 Expr *Callee = E->getCallee(); 3673 3674 if (isa<UnresolvedLookupExpr>(Callee)) 3675 return Inherited::VisitCXXOperatorCallExpr(E); 3676 3677 Visit(Callee); 3678 for (auto Arg : E->arguments()) 3679 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3680 } 3681 3682 void VisitBinaryOperator(BinaryOperator *E) { 3683 // If a field assignment is detected, remove the field from the 3684 // uninitiailized field set. 3685 if (E->getOpcode() == BO_Assign) 3686 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3687 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3688 if (!FD->getType()->isReferenceType()) 3689 DeclsToRemove.push_back(FD); 3690 3691 if (E->isCompoundAssignmentOp()) { 3692 HandleValue(E->getLHS(), false /*AddressOf*/); 3693 Visit(E->getRHS()); 3694 return; 3695 } 3696 3697 Inherited::VisitBinaryOperator(E); 3698 } 3699 3700 void VisitUnaryOperator(UnaryOperator *E) { 3701 if (E->isIncrementDecrementOp()) { 3702 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3703 return; 3704 } 3705 if (E->getOpcode() == UO_AddrOf) { 3706 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3707 HandleValue(ME->getBase(), true /*AddressOf*/); 3708 return; 3709 } 3710 } 3711 3712 Inherited::VisitUnaryOperator(E); 3713 } 3714 }; 3715 3716 // Diagnose value-uses of fields to initialize themselves, e.g. 3717 // foo(foo) 3718 // where foo is not also a parameter to the constructor. 3719 // Also diagnose across field uninitialized use such as 3720 // x(y), y(x) 3721 // TODO: implement -Wuninitialized and fold this into that framework. 3722 static void DiagnoseUninitializedFields( 3723 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3724 3725 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3726 Constructor->getLocation())) { 3727 return; 3728 } 3729 3730 if (Constructor->isInvalidDecl()) 3731 return; 3732 3733 const CXXRecordDecl *RD = Constructor->getParent(); 3734 3735 if (RD->getDescribedClassTemplate()) 3736 return; 3737 3738 // Holds fields that are uninitialized. 3739 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3740 3741 // At the beginning, all fields are uninitialized. 3742 for (auto *I : RD->decls()) { 3743 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3744 UninitializedFields.insert(FD); 3745 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3746 UninitializedFields.insert(IFD->getAnonField()); 3747 } 3748 } 3749 3750 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3751 for (auto I : RD->bases()) 3752 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3753 3754 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3755 return; 3756 3757 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3758 UninitializedFields, 3759 UninitializedBaseClasses); 3760 3761 for (const auto *FieldInit : Constructor->inits()) { 3762 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3763 break; 3764 3765 Expr *InitExpr = FieldInit->getInit(); 3766 if (!InitExpr) 3767 continue; 3768 3769 if (CXXDefaultInitExpr *Default = 3770 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3771 InitExpr = Default->getExpr(); 3772 if (!InitExpr) 3773 continue; 3774 // In class initializers will point to the constructor. 3775 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3776 FieldInit->getAnyMember(), 3777 FieldInit->getBaseClass()); 3778 } else { 3779 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3780 FieldInit->getAnyMember(), 3781 FieldInit->getBaseClass()); 3782 } 3783 } 3784 } 3785 } // namespace 3786 3787 /// Enter a new C++ default initializer scope. After calling this, the 3788 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3789 /// parsing or instantiating the initializer failed. 3790 void Sema::ActOnStartCXXInClassMemberInitializer() { 3791 // Create a synthetic function scope to represent the call to the constructor 3792 // that notionally surrounds a use of this initializer. 3793 PushFunctionScope(); 3794 } 3795 3796 /// This is invoked after parsing an in-class initializer for a 3797 /// non-static C++ class member, and after instantiating an in-class initializer 3798 /// in a class template. Such actions are deferred until the class is complete. 3799 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3800 SourceLocation InitLoc, 3801 Expr *InitExpr) { 3802 // Pop the notional constructor scope we created earlier. 3803 PopFunctionScopeInfo(nullptr, D); 3804 3805 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3806 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3807 "must set init style when field is created"); 3808 3809 if (!InitExpr) { 3810 D->setInvalidDecl(); 3811 if (FD) 3812 FD->removeInClassInitializer(); 3813 return; 3814 } 3815 3816 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3817 FD->setInvalidDecl(); 3818 FD->removeInClassInitializer(); 3819 return; 3820 } 3821 3822 ExprResult Init = InitExpr; 3823 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3824 InitializedEntity Entity = 3825 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3826 InitializationKind Kind = 3827 FD->getInClassInitStyle() == ICIS_ListInit 3828 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 3829 InitExpr->getBeginLoc(), 3830 InitExpr->getEndLoc()) 3831 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 3832 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3833 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3834 if (Init.isInvalid()) { 3835 FD->setInvalidDecl(); 3836 return; 3837 } 3838 } 3839 3840 // C++11 [class.base.init]p7: 3841 // The initialization of each base and member constitutes a 3842 // full-expression. 3843 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 3844 if (Init.isInvalid()) { 3845 FD->setInvalidDecl(); 3846 return; 3847 } 3848 3849 InitExpr = Init.get(); 3850 3851 FD->setInClassInitializer(InitExpr); 3852 } 3853 3854 /// Find the direct and/or virtual base specifiers that 3855 /// correspond to the given base type, for use in base initialization 3856 /// within a constructor. 3857 static bool FindBaseInitializer(Sema &SemaRef, 3858 CXXRecordDecl *ClassDecl, 3859 QualType BaseType, 3860 const CXXBaseSpecifier *&DirectBaseSpec, 3861 const CXXBaseSpecifier *&VirtualBaseSpec) { 3862 // First, check for a direct base class. 3863 DirectBaseSpec = nullptr; 3864 for (const auto &Base : ClassDecl->bases()) { 3865 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3866 // We found a direct base of this type. That's what we're 3867 // initializing. 3868 DirectBaseSpec = &Base; 3869 break; 3870 } 3871 } 3872 3873 // Check for a virtual base class. 3874 // FIXME: We might be able to short-circuit this if we know in advance that 3875 // there are no virtual bases. 3876 VirtualBaseSpec = nullptr; 3877 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3878 // We haven't found a base yet; search the class hierarchy for a 3879 // virtual base class. 3880 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3881 /*DetectVirtual=*/false); 3882 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3883 SemaRef.Context.getTypeDeclType(ClassDecl), 3884 BaseType, Paths)) { 3885 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3886 Path != Paths.end(); ++Path) { 3887 if (Path->back().Base->isVirtual()) { 3888 VirtualBaseSpec = Path->back().Base; 3889 break; 3890 } 3891 } 3892 } 3893 } 3894 3895 return DirectBaseSpec || VirtualBaseSpec; 3896 } 3897 3898 /// Handle a C++ member initializer using braced-init-list syntax. 3899 MemInitResult 3900 Sema::ActOnMemInitializer(Decl *ConstructorD, 3901 Scope *S, 3902 CXXScopeSpec &SS, 3903 IdentifierInfo *MemberOrBase, 3904 ParsedType TemplateTypeTy, 3905 const DeclSpec &DS, 3906 SourceLocation IdLoc, 3907 Expr *InitList, 3908 SourceLocation EllipsisLoc) { 3909 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3910 DS, IdLoc, InitList, 3911 EllipsisLoc); 3912 } 3913 3914 /// Handle a C++ member initializer using parentheses syntax. 3915 MemInitResult 3916 Sema::ActOnMemInitializer(Decl *ConstructorD, 3917 Scope *S, 3918 CXXScopeSpec &SS, 3919 IdentifierInfo *MemberOrBase, 3920 ParsedType TemplateTypeTy, 3921 const DeclSpec &DS, 3922 SourceLocation IdLoc, 3923 SourceLocation LParenLoc, 3924 ArrayRef<Expr *> Args, 3925 SourceLocation RParenLoc, 3926 SourceLocation EllipsisLoc) { 3927 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 3928 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3929 DS, IdLoc, List, EllipsisLoc); 3930 } 3931 3932 namespace { 3933 3934 // Callback to only accept typo corrections that can be a valid C++ member 3935 // intializer: either a non-static field member or a base class. 3936 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 3937 public: 3938 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 3939 : ClassDecl(ClassDecl) {} 3940 3941 bool ValidateCandidate(const TypoCorrection &candidate) override { 3942 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 3943 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 3944 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 3945 return isa<TypeDecl>(ND); 3946 } 3947 return false; 3948 } 3949 3950 std::unique_ptr<CorrectionCandidateCallback> clone() override { 3951 return std::make_unique<MemInitializerValidatorCCC>(*this); 3952 } 3953 3954 private: 3955 CXXRecordDecl *ClassDecl; 3956 }; 3957 3958 } 3959 3960 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 3961 CXXScopeSpec &SS, 3962 ParsedType TemplateTypeTy, 3963 IdentifierInfo *MemberOrBase) { 3964 if (SS.getScopeRep() || TemplateTypeTy) 3965 return nullptr; 3966 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 3967 if (Result.empty()) 3968 return nullptr; 3969 ValueDecl *Member; 3970 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 3971 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) 3972 return Member; 3973 return nullptr; 3974 } 3975 3976 /// Handle a C++ member initializer. 3977 MemInitResult 3978 Sema::BuildMemInitializer(Decl *ConstructorD, 3979 Scope *S, 3980 CXXScopeSpec &SS, 3981 IdentifierInfo *MemberOrBase, 3982 ParsedType TemplateTypeTy, 3983 const DeclSpec &DS, 3984 SourceLocation IdLoc, 3985 Expr *Init, 3986 SourceLocation EllipsisLoc) { 3987 ExprResult Res = CorrectDelayedTyposInExpr(Init); 3988 if (!Res.isUsable()) 3989 return true; 3990 Init = Res.get(); 3991 3992 if (!ConstructorD) 3993 return true; 3994 3995 AdjustDeclIfTemplate(ConstructorD); 3996 3997 CXXConstructorDecl *Constructor 3998 = dyn_cast<CXXConstructorDecl>(ConstructorD); 3999 if (!Constructor) { 4000 // The user wrote a constructor initializer on a function that is 4001 // not a C++ constructor. Ignore the error for now, because we may 4002 // have more member initializers coming; we'll diagnose it just 4003 // once in ActOnMemInitializers. 4004 return true; 4005 } 4006 4007 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4008 4009 // C++ [class.base.init]p2: 4010 // Names in a mem-initializer-id are looked up in the scope of the 4011 // constructor's class and, if not found in that scope, are looked 4012 // up in the scope containing the constructor's definition. 4013 // [Note: if the constructor's class contains a member with the 4014 // same name as a direct or virtual base class of the class, a 4015 // mem-initializer-id naming the member or base class and composed 4016 // of a single identifier refers to the class member. A 4017 // mem-initializer-id for the hidden base class may be specified 4018 // using a qualified name. ] 4019 4020 // Look for a member, first. 4021 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4022 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4023 if (EllipsisLoc.isValid()) 4024 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4025 << MemberOrBase 4026 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4027 4028 return BuildMemberInitializer(Member, Init, IdLoc); 4029 } 4030 // It didn't name a member, so see if it names a class. 4031 QualType BaseType; 4032 TypeSourceInfo *TInfo = nullptr; 4033 4034 if (TemplateTypeTy) { 4035 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4036 if (BaseType.isNull()) 4037 return true; 4038 } else if (DS.getTypeSpecType() == TST_decltype) { 4039 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4040 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4041 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4042 return true; 4043 } else { 4044 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4045 LookupParsedName(R, S, &SS); 4046 4047 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4048 if (!TyD) { 4049 if (R.isAmbiguous()) return true; 4050 4051 // We don't want access-control diagnostics here. 4052 R.suppressDiagnostics(); 4053 4054 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4055 bool NotUnknownSpecialization = false; 4056 DeclContext *DC = computeDeclContext(SS, false); 4057 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4058 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4059 4060 if (!NotUnknownSpecialization) { 4061 // When the scope specifier can refer to a member of an unknown 4062 // specialization, we take it as a type name. 4063 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4064 SS.getWithLocInContext(Context), 4065 *MemberOrBase, IdLoc); 4066 if (BaseType.isNull()) 4067 return true; 4068 4069 TInfo = Context.CreateTypeSourceInfo(BaseType); 4070 DependentNameTypeLoc TL = 4071 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4072 if (!TL.isNull()) { 4073 TL.setNameLoc(IdLoc); 4074 TL.setElaboratedKeywordLoc(SourceLocation()); 4075 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4076 } 4077 4078 R.clear(); 4079 R.setLookupName(MemberOrBase); 4080 } 4081 } 4082 4083 // If no results were found, try to correct typos. 4084 TypoCorrection Corr; 4085 MemInitializerValidatorCCC CCC(ClassDecl); 4086 if (R.empty() && BaseType.isNull() && 4087 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4088 CCC, CTK_ErrorRecovery, ClassDecl))) { 4089 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4090 // We have found a non-static data member with a similar 4091 // name to what was typed; complain and initialize that 4092 // member. 4093 diagnoseTypo(Corr, 4094 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4095 << MemberOrBase << true); 4096 return BuildMemberInitializer(Member, Init, IdLoc); 4097 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4098 const CXXBaseSpecifier *DirectBaseSpec; 4099 const CXXBaseSpecifier *VirtualBaseSpec; 4100 if (FindBaseInitializer(*this, ClassDecl, 4101 Context.getTypeDeclType(Type), 4102 DirectBaseSpec, VirtualBaseSpec)) { 4103 // We have found a direct or virtual base class with a 4104 // similar name to what was typed; complain and initialize 4105 // that base class. 4106 diagnoseTypo(Corr, 4107 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4108 << MemberOrBase << false, 4109 PDiag() /*Suppress note, we provide our own.*/); 4110 4111 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4112 : VirtualBaseSpec; 4113 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4114 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4115 4116 TyD = Type; 4117 } 4118 } 4119 } 4120 4121 if (!TyD && BaseType.isNull()) { 4122 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4123 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4124 return true; 4125 } 4126 } 4127 4128 if (BaseType.isNull()) { 4129 BaseType = Context.getTypeDeclType(TyD); 4130 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4131 if (SS.isSet()) { 4132 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4133 BaseType); 4134 TInfo = Context.CreateTypeSourceInfo(BaseType); 4135 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4136 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4137 TL.setElaboratedKeywordLoc(SourceLocation()); 4138 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4139 } 4140 } 4141 } 4142 4143 if (!TInfo) 4144 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4145 4146 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4147 } 4148 4149 MemInitResult 4150 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4151 SourceLocation IdLoc) { 4152 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4153 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4154 assert((DirectMember || IndirectMember) && 4155 "Member must be a FieldDecl or IndirectFieldDecl"); 4156 4157 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4158 return true; 4159 4160 if (Member->isInvalidDecl()) 4161 return true; 4162 4163 MultiExprArg Args; 4164 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4165 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4166 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4167 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4168 } else { 4169 // Template instantiation doesn't reconstruct ParenListExprs for us. 4170 Args = Init; 4171 } 4172 4173 SourceRange InitRange = Init->getSourceRange(); 4174 4175 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4176 // Can't check initialization for a member of dependent type or when 4177 // any of the arguments are type-dependent expressions. 4178 DiscardCleanupsInEvaluationContext(); 4179 } else { 4180 bool InitList = false; 4181 if (isa<InitListExpr>(Init)) { 4182 InitList = true; 4183 Args = Init; 4184 } 4185 4186 // Initialize the member. 4187 InitializedEntity MemberEntity = 4188 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4189 : InitializedEntity::InitializeMember(IndirectMember, 4190 nullptr); 4191 InitializationKind Kind = 4192 InitList ? InitializationKind::CreateDirectList( 4193 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4194 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4195 InitRange.getEnd()); 4196 4197 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4198 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4199 nullptr); 4200 if (MemberInit.isInvalid()) 4201 return true; 4202 4203 // C++11 [class.base.init]p7: 4204 // The initialization of each base and member constitutes a 4205 // full-expression. 4206 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4207 /*DiscardedValue*/ false); 4208 if (MemberInit.isInvalid()) 4209 return true; 4210 4211 Init = MemberInit.get(); 4212 } 4213 4214 if (DirectMember) { 4215 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4216 InitRange.getBegin(), Init, 4217 InitRange.getEnd()); 4218 } else { 4219 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4220 InitRange.getBegin(), Init, 4221 InitRange.getEnd()); 4222 } 4223 } 4224 4225 MemInitResult 4226 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4227 CXXRecordDecl *ClassDecl) { 4228 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4229 if (!LangOpts.CPlusPlus11) 4230 return Diag(NameLoc, diag::err_delegating_ctor) 4231 << TInfo->getTypeLoc().getLocalSourceRange(); 4232 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4233 4234 bool InitList = true; 4235 MultiExprArg Args = Init; 4236 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4237 InitList = false; 4238 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4239 } 4240 4241 SourceRange InitRange = Init->getSourceRange(); 4242 // Initialize the object. 4243 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4244 QualType(ClassDecl->getTypeForDecl(), 0)); 4245 InitializationKind Kind = 4246 InitList ? InitializationKind::CreateDirectList( 4247 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4248 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4249 InitRange.getEnd()); 4250 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4251 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4252 Args, nullptr); 4253 if (DelegationInit.isInvalid()) 4254 return true; 4255 4256 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4257 "Delegating constructor with no target?"); 4258 4259 // C++11 [class.base.init]p7: 4260 // The initialization of each base and member constitutes a 4261 // full-expression. 4262 DelegationInit = ActOnFinishFullExpr( 4263 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4264 if (DelegationInit.isInvalid()) 4265 return true; 4266 4267 // If we are in a dependent context, template instantiation will 4268 // perform this type-checking again. Just save the arguments that we 4269 // received in a ParenListExpr. 4270 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4271 // of the information that we have about the base 4272 // initializer. However, deconstructing the ASTs is a dicey process, 4273 // and this approach is far more likely to get the corner cases right. 4274 if (CurContext->isDependentContext()) 4275 DelegationInit = Init; 4276 4277 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4278 DelegationInit.getAs<Expr>(), 4279 InitRange.getEnd()); 4280 } 4281 4282 MemInitResult 4283 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4284 Expr *Init, CXXRecordDecl *ClassDecl, 4285 SourceLocation EllipsisLoc) { 4286 SourceLocation BaseLoc 4287 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4288 4289 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4290 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4291 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4292 4293 // C++ [class.base.init]p2: 4294 // [...] Unless the mem-initializer-id names a nonstatic data 4295 // member of the constructor's class or a direct or virtual base 4296 // of that class, the mem-initializer is ill-formed. A 4297 // mem-initializer-list can initialize a base class using any 4298 // name that denotes that base class type. 4299 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4300 4301 SourceRange InitRange = Init->getSourceRange(); 4302 if (EllipsisLoc.isValid()) { 4303 // This is a pack expansion. 4304 if (!BaseType->containsUnexpandedParameterPack()) { 4305 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4306 << SourceRange(BaseLoc, InitRange.getEnd()); 4307 4308 EllipsisLoc = SourceLocation(); 4309 } 4310 } else { 4311 // Check for any unexpanded parameter packs. 4312 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4313 return true; 4314 4315 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4316 return true; 4317 } 4318 4319 // Check for direct and virtual base classes. 4320 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4321 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4322 if (!Dependent) { 4323 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4324 BaseType)) 4325 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4326 4327 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4328 VirtualBaseSpec); 4329 4330 // C++ [base.class.init]p2: 4331 // Unless the mem-initializer-id names a nonstatic data member of the 4332 // constructor's class or a direct or virtual base of that class, the 4333 // mem-initializer is ill-formed. 4334 if (!DirectBaseSpec && !VirtualBaseSpec) { 4335 // If the class has any dependent bases, then it's possible that 4336 // one of those types will resolve to the same type as 4337 // BaseType. Therefore, just treat this as a dependent base 4338 // class initialization. FIXME: Should we try to check the 4339 // initialization anyway? It seems odd. 4340 if (ClassDecl->hasAnyDependentBases()) 4341 Dependent = true; 4342 else 4343 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4344 << BaseType << Context.getTypeDeclType(ClassDecl) 4345 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4346 } 4347 } 4348 4349 if (Dependent) { 4350 DiscardCleanupsInEvaluationContext(); 4351 4352 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4353 /*IsVirtual=*/false, 4354 InitRange.getBegin(), Init, 4355 InitRange.getEnd(), EllipsisLoc); 4356 } 4357 4358 // C++ [base.class.init]p2: 4359 // If a mem-initializer-id is ambiguous because it designates both 4360 // a direct non-virtual base class and an inherited virtual base 4361 // class, the mem-initializer is ill-formed. 4362 if (DirectBaseSpec && VirtualBaseSpec) 4363 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4364 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4365 4366 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4367 if (!BaseSpec) 4368 BaseSpec = VirtualBaseSpec; 4369 4370 // Initialize the base. 4371 bool InitList = true; 4372 MultiExprArg Args = Init; 4373 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4374 InitList = false; 4375 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4376 } 4377 4378 InitializedEntity BaseEntity = 4379 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4380 InitializationKind Kind = 4381 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4382 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4383 InitRange.getEnd()); 4384 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4385 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4386 if (BaseInit.isInvalid()) 4387 return true; 4388 4389 // C++11 [class.base.init]p7: 4390 // The initialization of each base and member constitutes a 4391 // full-expression. 4392 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4393 /*DiscardedValue*/ false); 4394 if (BaseInit.isInvalid()) 4395 return true; 4396 4397 // If we are in a dependent context, template instantiation will 4398 // perform this type-checking again. Just save the arguments that we 4399 // received in a ParenListExpr. 4400 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4401 // of the information that we have about the base 4402 // initializer. However, deconstructing the ASTs is a dicey process, 4403 // and this approach is far more likely to get the corner cases right. 4404 if (CurContext->isDependentContext()) 4405 BaseInit = Init; 4406 4407 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4408 BaseSpec->isVirtual(), 4409 InitRange.getBegin(), 4410 BaseInit.getAs<Expr>(), 4411 InitRange.getEnd(), EllipsisLoc); 4412 } 4413 4414 // Create a static_cast\<T&&>(expr). 4415 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4416 if (T.isNull()) T = E->getType(); 4417 QualType TargetType = SemaRef.BuildReferenceType( 4418 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4419 SourceLocation ExprLoc = E->getBeginLoc(); 4420 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4421 TargetType, ExprLoc); 4422 4423 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4424 SourceRange(ExprLoc, ExprLoc), 4425 E->getSourceRange()).get(); 4426 } 4427 4428 /// ImplicitInitializerKind - How an implicit base or member initializer should 4429 /// initialize its base or member. 4430 enum ImplicitInitializerKind { 4431 IIK_Default, 4432 IIK_Copy, 4433 IIK_Move, 4434 IIK_Inherit 4435 }; 4436 4437 static bool 4438 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4439 ImplicitInitializerKind ImplicitInitKind, 4440 CXXBaseSpecifier *BaseSpec, 4441 bool IsInheritedVirtualBase, 4442 CXXCtorInitializer *&CXXBaseInit) { 4443 InitializedEntity InitEntity 4444 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4445 IsInheritedVirtualBase); 4446 4447 ExprResult BaseInit; 4448 4449 switch (ImplicitInitKind) { 4450 case IIK_Inherit: 4451 case IIK_Default: { 4452 InitializationKind InitKind 4453 = InitializationKind::CreateDefault(Constructor->getLocation()); 4454 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4455 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4456 break; 4457 } 4458 4459 case IIK_Move: 4460 case IIK_Copy: { 4461 bool Moving = ImplicitInitKind == IIK_Move; 4462 ParmVarDecl *Param = Constructor->getParamDecl(0); 4463 QualType ParamType = Param->getType().getNonReferenceType(); 4464 4465 Expr *CopyCtorArg = 4466 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4467 SourceLocation(), Param, false, 4468 Constructor->getLocation(), ParamType, 4469 VK_LValue, nullptr); 4470 4471 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4472 4473 // Cast to the base class to avoid ambiguities. 4474 QualType ArgTy = 4475 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4476 ParamType.getQualifiers()); 4477 4478 if (Moving) { 4479 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4480 } 4481 4482 CXXCastPath BasePath; 4483 BasePath.push_back(BaseSpec); 4484 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4485 CK_UncheckedDerivedToBase, 4486 Moving ? VK_XValue : VK_LValue, 4487 &BasePath).get(); 4488 4489 InitializationKind InitKind 4490 = InitializationKind::CreateDirect(Constructor->getLocation(), 4491 SourceLocation(), SourceLocation()); 4492 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4493 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4494 break; 4495 } 4496 } 4497 4498 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4499 if (BaseInit.isInvalid()) 4500 return true; 4501 4502 CXXBaseInit = 4503 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4504 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4505 SourceLocation()), 4506 BaseSpec->isVirtual(), 4507 SourceLocation(), 4508 BaseInit.getAs<Expr>(), 4509 SourceLocation(), 4510 SourceLocation()); 4511 4512 return false; 4513 } 4514 4515 static bool RefersToRValueRef(Expr *MemRef) { 4516 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4517 return Referenced->getType()->isRValueReferenceType(); 4518 } 4519 4520 static bool 4521 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4522 ImplicitInitializerKind ImplicitInitKind, 4523 FieldDecl *Field, IndirectFieldDecl *Indirect, 4524 CXXCtorInitializer *&CXXMemberInit) { 4525 if (Field->isInvalidDecl()) 4526 return true; 4527 4528 SourceLocation Loc = Constructor->getLocation(); 4529 4530 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4531 bool Moving = ImplicitInitKind == IIK_Move; 4532 ParmVarDecl *Param = Constructor->getParamDecl(0); 4533 QualType ParamType = Param->getType().getNonReferenceType(); 4534 4535 // Suppress copying zero-width bitfields. 4536 if (Field->isZeroLengthBitField(SemaRef.Context)) 4537 return false; 4538 4539 Expr *MemberExprBase = 4540 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4541 SourceLocation(), Param, false, 4542 Loc, ParamType, VK_LValue, nullptr); 4543 4544 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4545 4546 if (Moving) { 4547 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4548 } 4549 4550 // Build a reference to this field within the parameter. 4551 CXXScopeSpec SS; 4552 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4553 Sema::LookupMemberName); 4554 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4555 : cast<ValueDecl>(Field), AS_public); 4556 MemberLookup.resolveKind(); 4557 ExprResult CtorArg 4558 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4559 ParamType, Loc, 4560 /*IsArrow=*/false, 4561 SS, 4562 /*TemplateKWLoc=*/SourceLocation(), 4563 /*FirstQualifierInScope=*/nullptr, 4564 MemberLookup, 4565 /*TemplateArgs=*/nullptr, 4566 /*S*/nullptr); 4567 if (CtorArg.isInvalid()) 4568 return true; 4569 4570 // C++11 [class.copy]p15: 4571 // - if a member m has rvalue reference type T&&, it is direct-initialized 4572 // with static_cast<T&&>(x.m); 4573 if (RefersToRValueRef(CtorArg.get())) { 4574 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4575 } 4576 4577 InitializedEntity Entity = 4578 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4579 /*Implicit*/ true) 4580 : InitializedEntity::InitializeMember(Field, nullptr, 4581 /*Implicit*/ true); 4582 4583 // Direct-initialize to use the copy constructor. 4584 InitializationKind InitKind = 4585 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4586 4587 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4588 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4589 ExprResult MemberInit = 4590 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4591 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4592 if (MemberInit.isInvalid()) 4593 return true; 4594 4595 if (Indirect) 4596 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4597 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4598 else 4599 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4600 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4601 return false; 4602 } 4603 4604 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4605 "Unhandled implicit init kind!"); 4606 4607 QualType FieldBaseElementType = 4608 SemaRef.Context.getBaseElementType(Field->getType()); 4609 4610 if (FieldBaseElementType->isRecordType()) { 4611 InitializedEntity InitEntity = 4612 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4613 /*Implicit*/ true) 4614 : InitializedEntity::InitializeMember(Field, nullptr, 4615 /*Implicit*/ true); 4616 InitializationKind InitKind = 4617 InitializationKind::CreateDefault(Loc); 4618 4619 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4620 ExprResult MemberInit = 4621 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4622 4623 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4624 if (MemberInit.isInvalid()) 4625 return true; 4626 4627 if (Indirect) 4628 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4629 Indirect, Loc, 4630 Loc, 4631 MemberInit.get(), 4632 Loc); 4633 else 4634 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4635 Field, Loc, Loc, 4636 MemberInit.get(), 4637 Loc); 4638 return false; 4639 } 4640 4641 if (!Field->getParent()->isUnion()) { 4642 if (FieldBaseElementType->isReferenceType()) { 4643 SemaRef.Diag(Constructor->getLocation(), 4644 diag::err_uninitialized_member_in_ctor) 4645 << (int)Constructor->isImplicit() 4646 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4647 << 0 << Field->getDeclName(); 4648 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4649 return true; 4650 } 4651 4652 if (FieldBaseElementType.isConstQualified()) { 4653 SemaRef.Diag(Constructor->getLocation(), 4654 diag::err_uninitialized_member_in_ctor) 4655 << (int)Constructor->isImplicit() 4656 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4657 << 1 << Field->getDeclName(); 4658 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4659 return true; 4660 } 4661 } 4662 4663 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4664 // ARC and Weak: 4665 // Default-initialize Objective-C pointers to NULL. 4666 CXXMemberInit 4667 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4668 Loc, Loc, 4669 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4670 Loc); 4671 return false; 4672 } 4673 4674 // Nothing to initialize. 4675 CXXMemberInit = nullptr; 4676 return false; 4677 } 4678 4679 namespace { 4680 struct BaseAndFieldInfo { 4681 Sema &S; 4682 CXXConstructorDecl *Ctor; 4683 bool AnyErrorsInInits; 4684 ImplicitInitializerKind IIK; 4685 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4686 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4687 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4688 4689 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4690 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4691 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4692 if (Ctor->getInheritedConstructor()) 4693 IIK = IIK_Inherit; 4694 else if (Generated && Ctor->isCopyConstructor()) 4695 IIK = IIK_Copy; 4696 else if (Generated && Ctor->isMoveConstructor()) 4697 IIK = IIK_Move; 4698 else 4699 IIK = IIK_Default; 4700 } 4701 4702 bool isImplicitCopyOrMove() const { 4703 switch (IIK) { 4704 case IIK_Copy: 4705 case IIK_Move: 4706 return true; 4707 4708 case IIK_Default: 4709 case IIK_Inherit: 4710 return false; 4711 } 4712 4713 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4714 } 4715 4716 bool addFieldInitializer(CXXCtorInitializer *Init) { 4717 AllToInit.push_back(Init); 4718 4719 // Check whether this initializer makes the field "used". 4720 if (Init->getInit()->HasSideEffects(S.Context)) 4721 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4722 4723 return false; 4724 } 4725 4726 bool isInactiveUnionMember(FieldDecl *Field) { 4727 RecordDecl *Record = Field->getParent(); 4728 if (!Record->isUnion()) 4729 return false; 4730 4731 if (FieldDecl *Active = 4732 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4733 return Active != Field->getCanonicalDecl(); 4734 4735 // In an implicit copy or move constructor, ignore any in-class initializer. 4736 if (isImplicitCopyOrMove()) 4737 return true; 4738 4739 // If there's no explicit initialization, the field is active only if it 4740 // has an in-class initializer... 4741 if (Field->hasInClassInitializer()) 4742 return false; 4743 // ... or it's an anonymous struct or union whose class has an in-class 4744 // initializer. 4745 if (!Field->isAnonymousStructOrUnion()) 4746 return true; 4747 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4748 return !FieldRD->hasInClassInitializer(); 4749 } 4750 4751 /// Determine whether the given field is, or is within, a union member 4752 /// that is inactive (because there was an initializer given for a different 4753 /// member of the union, or because the union was not initialized at all). 4754 bool isWithinInactiveUnionMember(FieldDecl *Field, 4755 IndirectFieldDecl *Indirect) { 4756 if (!Indirect) 4757 return isInactiveUnionMember(Field); 4758 4759 for (auto *C : Indirect->chain()) { 4760 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4761 if (Field && isInactiveUnionMember(Field)) 4762 return true; 4763 } 4764 return false; 4765 } 4766 }; 4767 } 4768 4769 /// Determine whether the given type is an incomplete or zero-lenfgth 4770 /// array type. 4771 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4772 if (T->isIncompleteArrayType()) 4773 return true; 4774 4775 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4776 if (!ArrayT->getSize()) 4777 return true; 4778 4779 T = ArrayT->getElementType(); 4780 } 4781 4782 return false; 4783 } 4784 4785 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4786 FieldDecl *Field, 4787 IndirectFieldDecl *Indirect = nullptr) { 4788 if (Field->isInvalidDecl()) 4789 return false; 4790 4791 // Overwhelmingly common case: we have a direct initializer for this field. 4792 if (CXXCtorInitializer *Init = 4793 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4794 return Info.addFieldInitializer(Init); 4795 4796 // C++11 [class.base.init]p8: 4797 // if the entity is a non-static data member that has a 4798 // brace-or-equal-initializer and either 4799 // -- the constructor's class is a union and no other variant member of that 4800 // union is designated by a mem-initializer-id or 4801 // -- the constructor's class is not a union, and, if the entity is a member 4802 // of an anonymous union, no other member of that union is designated by 4803 // a mem-initializer-id, 4804 // the entity is initialized as specified in [dcl.init]. 4805 // 4806 // We also apply the same rules to handle anonymous structs within anonymous 4807 // unions. 4808 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4809 return false; 4810 4811 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4812 ExprResult DIE = 4813 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4814 if (DIE.isInvalid()) 4815 return true; 4816 4817 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4818 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4819 4820 CXXCtorInitializer *Init; 4821 if (Indirect) 4822 Init = new (SemaRef.Context) 4823 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4824 SourceLocation(), DIE.get(), SourceLocation()); 4825 else 4826 Init = new (SemaRef.Context) 4827 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4828 SourceLocation(), DIE.get(), SourceLocation()); 4829 return Info.addFieldInitializer(Init); 4830 } 4831 4832 // Don't initialize incomplete or zero-length arrays. 4833 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4834 return false; 4835 4836 // Don't try to build an implicit initializer if there were semantic 4837 // errors in any of the initializers (and therefore we might be 4838 // missing some that the user actually wrote). 4839 if (Info.AnyErrorsInInits) 4840 return false; 4841 4842 CXXCtorInitializer *Init = nullptr; 4843 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4844 Indirect, Init)) 4845 return true; 4846 4847 if (!Init) 4848 return false; 4849 4850 return Info.addFieldInitializer(Init); 4851 } 4852 4853 bool 4854 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4855 CXXCtorInitializer *Initializer) { 4856 assert(Initializer->isDelegatingInitializer()); 4857 Constructor->setNumCtorInitializers(1); 4858 CXXCtorInitializer **initializer = 4859 new (Context) CXXCtorInitializer*[1]; 4860 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4861 Constructor->setCtorInitializers(initializer); 4862 4863 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4864 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4865 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4866 } 4867 4868 DelegatingCtorDecls.push_back(Constructor); 4869 4870 DiagnoseUninitializedFields(*this, Constructor); 4871 4872 return false; 4873 } 4874 4875 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4876 ArrayRef<CXXCtorInitializer *> Initializers) { 4877 if (Constructor->isDependentContext()) { 4878 // Just store the initializers as written, they will be checked during 4879 // instantiation. 4880 if (!Initializers.empty()) { 4881 Constructor->setNumCtorInitializers(Initializers.size()); 4882 CXXCtorInitializer **baseOrMemberInitializers = 4883 new (Context) CXXCtorInitializer*[Initializers.size()]; 4884 memcpy(baseOrMemberInitializers, Initializers.data(), 4885 Initializers.size() * sizeof(CXXCtorInitializer*)); 4886 Constructor->setCtorInitializers(baseOrMemberInitializers); 4887 } 4888 4889 // Let template instantiation know whether we had errors. 4890 if (AnyErrors) 4891 Constructor->setInvalidDecl(); 4892 4893 return false; 4894 } 4895 4896 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4897 4898 // We need to build the initializer AST according to order of construction 4899 // and not what user specified in the Initializers list. 4900 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4901 if (!ClassDecl) 4902 return true; 4903 4904 bool HadError = false; 4905 4906 for (unsigned i = 0; i < Initializers.size(); i++) { 4907 CXXCtorInitializer *Member = Initializers[i]; 4908 4909 if (Member->isBaseInitializer()) 4910 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4911 else { 4912 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4913 4914 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4915 for (auto *C : F->chain()) { 4916 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4917 if (FD && FD->getParent()->isUnion()) 4918 Info.ActiveUnionMember.insert(std::make_pair( 4919 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4920 } 4921 } else if (FieldDecl *FD = Member->getMember()) { 4922 if (FD->getParent()->isUnion()) 4923 Info.ActiveUnionMember.insert(std::make_pair( 4924 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4925 } 4926 } 4927 } 4928 4929 // Keep track of the direct virtual bases. 4930 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 4931 for (auto &I : ClassDecl->bases()) { 4932 if (I.isVirtual()) 4933 DirectVBases.insert(&I); 4934 } 4935 4936 // Push virtual bases before others. 4937 for (auto &VBase : ClassDecl->vbases()) { 4938 if (CXXCtorInitializer *Value 4939 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 4940 // [class.base.init]p7, per DR257: 4941 // A mem-initializer where the mem-initializer-id names a virtual base 4942 // class is ignored during execution of a constructor of any class that 4943 // is not the most derived class. 4944 if (ClassDecl->isAbstract()) { 4945 // FIXME: Provide a fixit to remove the base specifier. This requires 4946 // tracking the location of the associated comma for a base specifier. 4947 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 4948 << VBase.getType() << ClassDecl; 4949 DiagnoseAbstractType(ClassDecl); 4950 } 4951 4952 Info.AllToInit.push_back(Value); 4953 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 4954 // [class.base.init]p8, per DR257: 4955 // If a given [...] base class is not named by a mem-initializer-id 4956 // [...] and the entity is not a virtual base class of an abstract 4957 // class, then [...] the entity is default-initialized. 4958 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 4959 CXXCtorInitializer *CXXBaseInit; 4960 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4961 &VBase, IsInheritedVirtualBase, 4962 CXXBaseInit)) { 4963 HadError = true; 4964 continue; 4965 } 4966 4967 Info.AllToInit.push_back(CXXBaseInit); 4968 } 4969 } 4970 4971 // Non-virtual bases. 4972 for (auto &Base : ClassDecl->bases()) { 4973 // Virtuals are in the virtual base list and already constructed. 4974 if (Base.isVirtual()) 4975 continue; 4976 4977 if (CXXCtorInitializer *Value 4978 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 4979 Info.AllToInit.push_back(Value); 4980 } else if (!AnyErrors) { 4981 CXXCtorInitializer *CXXBaseInit; 4982 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4983 &Base, /*IsInheritedVirtualBase=*/false, 4984 CXXBaseInit)) { 4985 HadError = true; 4986 continue; 4987 } 4988 4989 Info.AllToInit.push_back(CXXBaseInit); 4990 } 4991 } 4992 4993 // Fields. 4994 for (auto *Mem : ClassDecl->decls()) { 4995 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4996 // C++ [class.bit]p2: 4997 // A declaration for a bit-field that omits the identifier declares an 4998 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4999 // initialized. 5000 if (F->isUnnamedBitfield()) 5001 continue; 5002 5003 // If we're not generating the implicit copy/move constructor, then we'll 5004 // handle anonymous struct/union fields based on their individual 5005 // indirect fields. 5006 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5007 continue; 5008 5009 if (CollectFieldInitializer(*this, Info, F)) 5010 HadError = true; 5011 continue; 5012 } 5013 5014 // Beyond this point, we only consider default initialization. 5015 if (Info.isImplicitCopyOrMove()) 5016 continue; 5017 5018 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5019 if (F->getType()->isIncompleteArrayType()) { 5020 assert(ClassDecl->hasFlexibleArrayMember() && 5021 "Incomplete array type is not valid"); 5022 continue; 5023 } 5024 5025 // Initialize each field of an anonymous struct individually. 5026 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5027 HadError = true; 5028 5029 continue; 5030 } 5031 } 5032 5033 unsigned NumInitializers = Info.AllToInit.size(); 5034 if (NumInitializers > 0) { 5035 Constructor->setNumCtorInitializers(NumInitializers); 5036 CXXCtorInitializer **baseOrMemberInitializers = 5037 new (Context) CXXCtorInitializer*[NumInitializers]; 5038 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5039 NumInitializers * sizeof(CXXCtorInitializer*)); 5040 Constructor->setCtorInitializers(baseOrMemberInitializers); 5041 5042 // Constructors implicitly reference the base and member 5043 // destructors. 5044 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5045 Constructor->getParent()); 5046 } 5047 5048 return HadError; 5049 } 5050 5051 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5052 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5053 const RecordDecl *RD = RT->getDecl(); 5054 if (RD->isAnonymousStructOrUnion()) { 5055 for (auto *Field : RD->fields()) 5056 PopulateKeysForFields(Field, IdealInits); 5057 return; 5058 } 5059 } 5060 IdealInits.push_back(Field->getCanonicalDecl()); 5061 } 5062 5063 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5064 return Context.getCanonicalType(BaseType).getTypePtr(); 5065 } 5066 5067 static const void *GetKeyForMember(ASTContext &Context, 5068 CXXCtorInitializer *Member) { 5069 if (!Member->isAnyMemberInitializer()) 5070 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5071 5072 return Member->getAnyMember()->getCanonicalDecl(); 5073 } 5074 5075 static void DiagnoseBaseOrMemInitializerOrder( 5076 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5077 ArrayRef<CXXCtorInitializer *> Inits) { 5078 if (Constructor->getDeclContext()->isDependentContext()) 5079 return; 5080 5081 // Don't check initializers order unless the warning is enabled at the 5082 // location of at least one initializer. 5083 bool ShouldCheckOrder = false; 5084 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5085 CXXCtorInitializer *Init = Inits[InitIndex]; 5086 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5087 Init->getSourceLocation())) { 5088 ShouldCheckOrder = true; 5089 break; 5090 } 5091 } 5092 if (!ShouldCheckOrder) 5093 return; 5094 5095 // Build the list of bases and members in the order that they'll 5096 // actually be initialized. The explicit initializers should be in 5097 // this same order but may be missing things. 5098 SmallVector<const void*, 32> IdealInitKeys; 5099 5100 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5101 5102 // 1. Virtual bases. 5103 for (const auto &VBase : ClassDecl->vbases()) 5104 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5105 5106 // 2. Non-virtual bases. 5107 for (const auto &Base : ClassDecl->bases()) { 5108 if (Base.isVirtual()) 5109 continue; 5110 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5111 } 5112 5113 // 3. Direct fields. 5114 for (auto *Field : ClassDecl->fields()) { 5115 if (Field->isUnnamedBitfield()) 5116 continue; 5117 5118 PopulateKeysForFields(Field, IdealInitKeys); 5119 } 5120 5121 unsigned NumIdealInits = IdealInitKeys.size(); 5122 unsigned IdealIndex = 0; 5123 5124 CXXCtorInitializer *PrevInit = nullptr; 5125 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5126 CXXCtorInitializer *Init = Inits[InitIndex]; 5127 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 5128 5129 // Scan forward to try to find this initializer in the idealized 5130 // initializers list. 5131 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5132 if (InitKey == IdealInitKeys[IdealIndex]) 5133 break; 5134 5135 // If we didn't find this initializer, it must be because we 5136 // scanned past it on a previous iteration. That can only 5137 // happen if we're out of order; emit a warning. 5138 if (IdealIndex == NumIdealInits && PrevInit) { 5139 Sema::SemaDiagnosticBuilder D = 5140 SemaRef.Diag(PrevInit->getSourceLocation(), 5141 diag::warn_initializer_out_of_order); 5142 5143 if (PrevInit->isAnyMemberInitializer()) 5144 D << 0 << PrevInit->getAnyMember()->getDeclName(); 5145 else 5146 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 5147 5148 if (Init->isAnyMemberInitializer()) 5149 D << 0 << Init->getAnyMember()->getDeclName(); 5150 else 5151 D << 1 << Init->getTypeSourceInfo()->getType(); 5152 5153 // Move back to the initializer's location in the ideal list. 5154 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5155 if (InitKey == IdealInitKeys[IdealIndex]) 5156 break; 5157 5158 assert(IdealIndex < NumIdealInits && 5159 "initializer not found in initializer list"); 5160 } 5161 5162 PrevInit = Init; 5163 } 5164 } 5165 5166 namespace { 5167 bool CheckRedundantInit(Sema &S, 5168 CXXCtorInitializer *Init, 5169 CXXCtorInitializer *&PrevInit) { 5170 if (!PrevInit) { 5171 PrevInit = Init; 5172 return false; 5173 } 5174 5175 if (FieldDecl *Field = Init->getAnyMember()) 5176 S.Diag(Init->getSourceLocation(), 5177 diag::err_multiple_mem_initialization) 5178 << Field->getDeclName() 5179 << Init->getSourceRange(); 5180 else { 5181 const Type *BaseClass = Init->getBaseClass(); 5182 assert(BaseClass && "neither field nor base"); 5183 S.Diag(Init->getSourceLocation(), 5184 diag::err_multiple_base_initialization) 5185 << QualType(BaseClass, 0) 5186 << Init->getSourceRange(); 5187 } 5188 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5189 << 0 << PrevInit->getSourceRange(); 5190 5191 return true; 5192 } 5193 5194 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5195 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5196 5197 bool CheckRedundantUnionInit(Sema &S, 5198 CXXCtorInitializer *Init, 5199 RedundantUnionMap &Unions) { 5200 FieldDecl *Field = Init->getAnyMember(); 5201 RecordDecl *Parent = Field->getParent(); 5202 NamedDecl *Child = Field; 5203 5204 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5205 if (Parent->isUnion()) { 5206 UnionEntry &En = Unions[Parent]; 5207 if (En.first && En.first != Child) { 5208 S.Diag(Init->getSourceLocation(), 5209 diag::err_multiple_mem_union_initialization) 5210 << Field->getDeclName() 5211 << Init->getSourceRange(); 5212 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5213 << 0 << En.second->getSourceRange(); 5214 return true; 5215 } 5216 if (!En.first) { 5217 En.first = Child; 5218 En.second = Init; 5219 } 5220 if (!Parent->isAnonymousStructOrUnion()) 5221 return false; 5222 } 5223 5224 Child = Parent; 5225 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5226 } 5227 5228 return false; 5229 } 5230 } 5231 5232 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5233 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5234 SourceLocation ColonLoc, 5235 ArrayRef<CXXCtorInitializer*> MemInits, 5236 bool AnyErrors) { 5237 if (!ConstructorDecl) 5238 return; 5239 5240 AdjustDeclIfTemplate(ConstructorDecl); 5241 5242 CXXConstructorDecl *Constructor 5243 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5244 5245 if (!Constructor) { 5246 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5247 return; 5248 } 5249 5250 // Mapping for the duplicate initializers check. 5251 // For member initializers, this is keyed with a FieldDecl*. 5252 // For base initializers, this is keyed with a Type*. 5253 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5254 5255 // Mapping for the inconsistent anonymous-union initializers check. 5256 RedundantUnionMap MemberUnions; 5257 5258 bool HadError = false; 5259 for (unsigned i = 0; i < MemInits.size(); i++) { 5260 CXXCtorInitializer *Init = MemInits[i]; 5261 5262 // Set the source order index. 5263 Init->setSourceOrder(i); 5264 5265 if (Init->isAnyMemberInitializer()) { 5266 const void *Key = GetKeyForMember(Context, Init); 5267 if (CheckRedundantInit(*this, Init, Members[Key]) || 5268 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5269 HadError = true; 5270 } else if (Init->isBaseInitializer()) { 5271 const void *Key = GetKeyForMember(Context, Init); 5272 if (CheckRedundantInit(*this, Init, Members[Key])) 5273 HadError = true; 5274 } else { 5275 assert(Init->isDelegatingInitializer()); 5276 // This must be the only initializer 5277 if (MemInits.size() != 1) { 5278 Diag(Init->getSourceLocation(), 5279 diag::err_delegating_initializer_alone) 5280 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5281 // We will treat this as being the only initializer. 5282 } 5283 SetDelegatingInitializer(Constructor, MemInits[i]); 5284 // Return immediately as the initializer is set. 5285 return; 5286 } 5287 } 5288 5289 if (HadError) 5290 return; 5291 5292 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5293 5294 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5295 5296 DiagnoseUninitializedFields(*this, Constructor); 5297 } 5298 5299 void 5300 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5301 CXXRecordDecl *ClassDecl) { 5302 // Ignore dependent contexts. Also ignore unions, since their members never 5303 // have destructors implicitly called. 5304 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5305 return; 5306 5307 // FIXME: all the access-control diagnostics are positioned on the 5308 // field/base declaration. That's probably good; that said, the 5309 // user might reasonably want to know why the destructor is being 5310 // emitted, and we currently don't say. 5311 5312 // Non-static data members. 5313 for (auto *Field : ClassDecl->fields()) { 5314 if (Field->isInvalidDecl()) 5315 continue; 5316 5317 // Don't destroy incomplete or zero-length arrays. 5318 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5319 continue; 5320 5321 QualType FieldType = Context.getBaseElementType(Field->getType()); 5322 5323 const RecordType* RT = FieldType->getAs<RecordType>(); 5324 if (!RT) 5325 continue; 5326 5327 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5328 if (FieldClassDecl->isInvalidDecl()) 5329 continue; 5330 if (FieldClassDecl->hasIrrelevantDestructor()) 5331 continue; 5332 // The destructor for an implicit anonymous union member is never invoked. 5333 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5334 continue; 5335 5336 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5337 assert(Dtor && "No dtor found for FieldClassDecl!"); 5338 CheckDestructorAccess(Field->getLocation(), Dtor, 5339 PDiag(diag::err_access_dtor_field) 5340 << Field->getDeclName() 5341 << FieldType); 5342 5343 MarkFunctionReferenced(Location, Dtor); 5344 DiagnoseUseOfDecl(Dtor, Location); 5345 } 5346 5347 // We only potentially invoke the destructors of potentially constructed 5348 // subobjects. 5349 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5350 5351 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5352 5353 // Bases. 5354 for (const auto &Base : ClassDecl->bases()) { 5355 // Bases are always records in a well-formed non-dependent class. 5356 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5357 5358 // Remember direct virtual bases. 5359 if (Base.isVirtual()) { 5360 if (!VisitVirtualBases) 5361 continue; 5362 DirectVirtualBases.insert(RT); 5363 } 5364 5365 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5366 // If our base class is invalid, we probably can't get its dtor anyway. 5367 if (BaseClassDecl->isInvalidDecl()) 5368 continue; 5369 if (BaseClassDecl->hasIrrelevantDestructor()) 5370 continue; 5371 5372 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5373 assert(Dtor && "No dtor found for BaseClassDecl!"); 5374 5375 // FIXME: caret should be on the start of the class name 5376 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5377 PDiag(diag::err_access_dtor_base) 5378 << Base.getType() << Base.getSourceRange(), 5379 Context.getTypeDeclType(ClassDecl)); 5380 5381 MarkFunctionReferenced(Location, Dtor); 5382 DiagnoseUseOfDecl(Dtor, Location); 5383 } 5384 5385 if (!VisitVirtualBases) 5386 return; 5387 5388 // Virtual bases. 5389 for (const auto &VBase : ClassDecl->vbases()) { 5390 // Bases are always records in a well-formed non-dependent class. 5391 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5392 5393 // Ignore direct virtual bases. 5394 if (DirectVirtualBases.count(RT)) 5395 continue; 5396 5397 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5398 // If our base class is invalid, we probably can't get its dtor anyway. 5399 if (BaseClassDecl->isInvalidDecl()) 5400 continue; 5401 if (BaseClassDecl->hasIrrelevantDestructor()) 5402 continue; 5403 5404 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5405 assert(Dtor && "No dtor found for BaseClassDecl!"); 5406 if (CheckDestructorAccess( 5407 ClassDecl->getLocation(), Dtor, 5408 PDiag(diag::err_access_dtor_vbase) 5409 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5410 Context.getTypeDeclType(ClassDecl)) == 5411 AR_accessible) { 5412 CheckDerivedToBaseConversion( 5413 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5414 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5415 SourceRange(), DeclarationName(), nullptr); 5416 } 5417 5418 MarkFunctionReferenced(Location, Dtor); 5419 DiagnoseUseOfDecl(Dtor, Location); 5420 } 5421 } 5422 5423 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5424 if (!CDtorDecl) 5425 return; 5426 5427 if (CXXConstructorDecl *Constructor 5428 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5429 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5430 DiagnoseUninitializedFields(*this, Constructor); 5431 } 5432 } 5433 5434 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5435 if (!getLangOpts().CPlusPlus) 5436 return false; 5437 5438 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5439 if (!RD) 5440 return false; 5441 5442 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5443 // class template specialization here, but doing so breaks a lot of code. 5444 5445 // We can't answer whether something is abstract until it has a 5446 // definition. If it's currently being defined, we'll walk back 5447 // over all the declarations when we have a full definition. 5448 const CXXRecordDecl *Def = RD->getDefinition(); 5449 if (!Def || Def->isBeingDefined()) 5450 return false; 5451 5452 return RD->isAbstract(); 5453 } 5454 5455 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5456 TypeDiagnoser &Diagnoser) { 5457 if (!isAbstractType(Loc, T)) 5458 return false; 5459 5460 T = Context.getBaseElementType(T); 5461 Diagnoser.diagnose(*this, Loc, T); 5462 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5463 return true; 5464 } 5465 5466 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5467 // Check if we've already emitted the list of pure virtual functions 5468 // for this class. 5469 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5470 return; 5471 5472 // If the diagnostic is suppressed, don't emit the notes. We're only 5473 // going to emit them once, so try to attach them to a diagnostic we're 5474 // actually going to show. 5475 if (Diags.isLastDiagnosticIgnored()) 5476 return; 5477 5478 CXXFinalOverriderMap FinalOverriders; 5479 RD->getFinalOverriders(FinalOverriders); 5480 5481 // Keep a set of seen pure methods so we won't diagnose the same method 5482 // more than once. 5483 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5484 5485 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5486 MEnd = FinalOverriders.end(); 5487 M != MEnd; 5488 ++M) { 5489 for (OverridingMethods::iterator SO = M->second.begin(), 5490 SOEnd = M->second.end(); 5491 SO != SOEnd; ++SO) { 5492 // C++ [class.abstract]p4: 5493 // A class is abstract if it contains or inherits at least one 5494 // pure virtual function for which the final overrider is pure 5495 // virtual. 5496 5497 // 5498 if (SO->second.size() != 1) 5499 continue; 5500 5501 if (!SO->second.front().Method->isPure()) 5502 continue; 5503 5504 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5505 continue; 5506 5507 Diag(SO->second.front().Method->getLocation(), 5508 diag::note_pure_virtual_function) 5509 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5510 } 5511 } 5512 5513 if (!PureVirtualClassDiagSet) 5514 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5515 PureVirtualClassDiagSet->insert(RD); 5516 } 5517 5518 namespace { 5519 struct AbstractUsageInfo { 5520 Sema &S; 5521 CXXRecordDecl *Record; 5522 CanQualType AbstractType; 5523 bool Invalid; 5524 5525 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5526 : S(S), Record(Record), 5527 AbstractType(S.Context.getCanonicalType( 5528 S.Context.getTypeDeclType(Record))), 5529 Invalid(false) {} 5530 5531 void DiagnoseAbstractType() { 5532 if (Invalid) return; 5533 S.DiagnoseAbstractType(Record); 5534 Invalid = true; 5535 } 5536 5537 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5538 }; 5539 5540 struct CheckAbstractUsage { 5541 AbstractUsageInfo &Info; 5542 const NamedDecl *Ctx; 5543 5544 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5545 : Info(Info), Ctx(Ctx) {} 5546 5547 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5548 switch (TL.getTypeLocClass()) { 5549 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5550 #define TYPELOC(CLASS, PARENT) \ 5551 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5552 #include "clang/AST/TypeLocNodes.def" 5553 } 5554 } 5555 5556 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5557 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5558 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5559 if (!TL.getParam(I)) 5560 continue; 5561 5562 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5563 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5564 } 5565 } 5566 5567 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5568 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5569 } 5570 5571 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5572 // Visit the type parameters from a permissive context. 5573 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5574 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5575 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5576 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5577 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5578 // TODO: other template argument types? 5579 } 5580 } 5581 5582 // Visit pointee types from a permissive context. 5583 #define CheckPolymorphic(Type) \ 5584 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5585 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5586 } 5587 CheckPolymorphic(PointerTypeLoc) 5588 CheckPolymorphic(ReferenceTypeLoc) 5589 CheckPolymorphic(MemberPointerTypeLoc) 5590 CheckPolymorphic(BlockPointerTypeLoc) 5591 CheckPolymorphic(AtomicTypeLoc) 5592 5593 /// Handle all the types we haven't given a more specific 5594 /// implementation for above. 5595 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5596 // Every other kind of type that we haven't called out already 5597 // that has an inner type is either (1) sugar or (2) contains that 5598 // inner type in some way as a subobject. 5599 if (TypeLoc Next = TL.getNextTypeLoc()) 5600 return Visit(Next, Sel); 5601 5602 // If there's no inner type and we're in a permissive context, 5603 // don't diagnose. 5604 if (Sel == Sema::AbstractNone) return; 5605 5606 // Check whether the type matches the abstract type. 5607 QualType T = TL.getType(); 5608 if (T->isArrayType()) { 5609 Sel = Sema::AbstractArrayType; 5610 T = Info.S.Context.getBaseElementType(T); 5611 } 5612 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5613 if (CT != Info.AbstractType) return; 5614 5615 // It matched; do some magic. 5616 if (Sel == Sema::AbstractArrayType) { 5617 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5618 << T << TL.getSourceRange(); 5619 } else { 5620 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5621 << Sel << T << TL.getSourceRange(); 5622 } 5623 Info.DiagnoseAbstractType(); 5624 } 5625 }; 5626 5627 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5628 Sema::AbstractDiagSelID Sel) { 5629 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5630 } 5631 5632 } 5633 5634 /// Check for invalid uses of an abstract type in a method declaration. 5635 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5636 CXXMethodDecl *MD) { 5637 // No need to do the check on definitions, which require that 5638 // the return/param types be complete. 5639 if (MD->doesThisDeclarationHaveABody()) 5640 return; 5641 5642 // For safety's sake, just ignore it if we don't have type source 5643 // information. This should never happen for non-implicit methods, 5644 // but... 5645 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5646 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5647 } 5648 5649 /// Check for invalid uses of an abstract type within a class definition. 5650 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5651 CXXRecordDecl *RD) { 5652 for (auto *D : RD->decls()) { 5653 if (D->isImplicit()) continue; 5654 5655 // Methods and method templates. 5656 if (isa<CXXMethodDecl>(D)) { 5657 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5658 } else if (isa<FunctionTemplateDecl>(D)) { 5659 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5660 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5661 5662 // Fields and static variables. 5663 } else if (isa<FieldDecl>(D)) { 5664 FieldDecl *FD = cast<FieldDecl>(D); 5665 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5666 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5667 } else if (isa<VarDecl>(D)) { 5668 VarDecl *VD = cast<VarDecl>(D); 5669 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5670 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5671 5672 // Nested classes and class templates. 5673 } else if (isa<CXXRecordDecl>(D)) { 5674 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5675 } else if (isa<ClassTemplateDecl>(D)) { 5676 CheckAbstractClassUsage(Info, 5677 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5678 } 5679 } 5680 } 5681 5682 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5683 Attr *ClassAttr = getDLLAttr(Class); 5684 if (!ClassAttr) 5685 return; 5686 5687 assert(ClassAttr->getKind() == attr::DLLExport); 5688 5689 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5690 5691 if (TSK == TSK_ExplicitInstantiationDeclaration) 5692 // Don't go any further if this is just an explicit instantiation 5693 // declaration. 5694 return; 5695 5696 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5697 S.MarkVTableUsed(Class->getLocation(), Class, true); 5698 5699 for (Decl *Member : Class->decls()) { 5700 // Defined static variables that are members of an exported base 5701 // class must be marked export too. 5702 auto *VD = dyn_cast<VarDecl>(Member); 5703 if (VD && Member->getAttr<DLLExportAttr>() && 5704 VD->getStorageClass() == SC_Static && 5705 TSK == TSK_ImplicitInstantiation) 5706 S.MarkVariableReferenced(VD->getLocation(), VD); 5707 5708 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5709 if (!MD) 5710 continue; 5711 5712 if (Member->getAttr<DLLExportAttr>()) { 5713 if (MD->isUserProvided()) { 5714 // Instantiate non-default class member functions ... 5715 5716 // .. except for certain kinds of template specializations. 5717 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5718 continue; 5719 5720 S.MarkFunctionReferenced(Class->getLocation(), MD); 5721 5722 // The function will be passed to the consumer when its definition is 5723 // encountered. 5724 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5725 MD->isCopyAssignmentOperator() || 5726 MD->isMoveAssignmentOperator()) { 5727 // Synthesize and instantiate non-trivial implicit methods, explicitly 5728 // defaulted methods, and the copy and move assignment operators. The 5729 // latter are exported even if they are trivial, because the address of 5730 // an operator can be taken and should compare equal across libraries. 5731 DiagnosticErrorTrap Trap(S.Diags); 5732 S.MarkFunctionReferenced(Class->getLocation(), MD); 5733 if (Trap.hasErrorOccurred()) { 5734 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5735 << Class << !S.getLangOpts().CPlusPlus11; 5736 break; 5737 } 5738 5739 // There is no later point when we will see the definition of this 5740 // function, so pass it to the consumer now. 5741 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5742 } 5743 } 5744 } 5745 } 5746 5747 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5748 CXXRecordDecl *Class) { 5749 // Only the MS ABI has default constructor closures, so we don't need to do 5750 // this semantic checking anywhere else. 5751 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5752 return; 5753 5754 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5755 for (Decl *Member : Class->decls()) { 5756 // Look for exported default constructors. 5757 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5758 if (!CD || !CD->isDefaultConstructor()) 5759 continue; 5760 auto *Attr = CD->getAttr<DLLExportAttr>(); 5761 if (!Attr) 5762 continue; 5763 5764 // If the class is non-dependent, mark the default arguments as ODR-used so 5765 // that we can properly codegen the constructor closure. 5766 if (!Class->isDependentContext()) { 5767 for (ParmVarDecl *PD : CD->parameters()) { 5768 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5769 S.DiscardCleanupsInEvaluationContext(); 5770 } 5771 } 5772 5773 if (LastExportedDefaultCtor) { 5774 S.Diag(LastExportedDefaultCtor->getLocation(), 5775 diag::err_attribute_dll_ambiguous_default_ctor) 5776 << Class; 5777 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5778 << CD->getDeclName(); 5779 return; 5780 } 5781 LastExportedDefaultCtor = CD; 5782 } 5783 } 5784 5785 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 5786 // Mark any compiler-generated routines with the implicit code_seg attribute. 5787 for (auto *Method : Class->methods()) { 5788 if (Method->isUserProvided()) 5789 continue; 5790 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 5791 Method->addAttr(A); 5792 } 5793 } 5794 5795 /// Check class-level dllimport/dllexport attribute. 5796 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5797 Attr *ClassAttr = getDLLAttr(Class); 5798 5799 // MSVC inherits DLL attributes to partial class template specializations. 5800 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5801 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5802 if (Attr *TemplateAttr = 5803 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5804 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5805 A->setInherited(true); 5806 ClassAttr = A; 5807 } 5808 } 5809 } 5810 5811 if (!ClassAttr) 5812 return; 5813 5814 if (!Class->isExternallyVisible()) { 5815 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5816 << Class << ClassAttr; 5817 return; 5818 } 5819 5820 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5821 !ClassAttr->isInherited()) { 5822 // Diagnose dll attributes on members of class with dll attribute. 5823 for (Decl *Member : Class->decls()) { 5824 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5825 continue; 5826 InheritableAttr *MemberAttr = getDLLAttr(Member); 5827 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5828 continue; 5829 5830 Diag(MemberAttr->getLocation(), 5831 diag::err_attribute_dll_member_of_dll_class) 5832 << MemberAttr << ClassAttr; 5833 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5834 Member->setInvalidDecl(); 5835 } 5836 } 5837 5838 if (Class->getDescribedClassTemplate()) 5839 // Don't inherit dll attribute until the template is instantiated. 5840 return; 5841 5842 // The class is either imported or exported. 5843 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5844 5845 // Check if this was a dllimport attribute propagated from a derived class to 5846 // a base class template specialization. We don't apply these attributes to 5847 // static data members. 5848 const bool PropagatedImport = 5849 !ClassExported && 5850 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 5851 5852 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5853 5854 // Ignore explicit dllexport on explicit class template instantiation 5855 // declarations, except in MinGW mode. 5856 if (ClassExported && !ClassAttr->isInherited() && 5857 TSK == TSK_ExplicitInstantiationDeclaration && 5858 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 5859 Class->dropAttr<DLLExportAttr>(); 5860 return; 5861 } 5862 5863 // Force declaration of implicit members so they can inherit the attribute. 5864 ForceDeclarationOfImplicitMembers(Class); 5865 5866 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5867 // seem to be true in practice? 5868 5869 for (Decl *Member : Class->decls()) { 5870 VarDecl *VD = dyn_cast<VarDecl>(Member); 5871 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5872 5873 // Only methods and static fields inherit the attributes. 5874 if (!VD && !MD) 5875 continue; 5876 5877 if (MD) { 5878 // Don't process deleted methods. 5879 if (MD->isDeleted()) 5880 continue; 5881 5882 if (MD->isInlined()) { 5883 // MinGW does not import or export inline methods. But do it for 5884 // template instantiations. 5885 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5886 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() && 5887 TSK != TSK_ExplicitInstantiationDeclaration && 5888 TSK != TSK_ExplicitInstantiationDefinition) 5889 continue; 5890 5891 // MSVC versions before 2015 don't export the move assignment operators 5892 // and move constructor, so don't attempt to import/export them if 5893 // we have a definition. 5894 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5895 if ((MD->isMoveAssignmentOperator() || 5896 (Ctor && Ctor->isMoveConstructor())) && 5897 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5898 continue; 5899 5900 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5901 // operator is exported anyway. 5902 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5903 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5904 continue; 5905 } 5906 } 5907 5908 // Don't apply dllimport attributes to static data members of class template 5909 // instantiations when the attribute is propagated from a derived class. 5910 if (VD && PropagatedImport) 5911 continue; 5912 5913 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5914 continue; 5915 5916 if (!getDLLAttr(Member)) { 5917 InheritableAttr *NewAttr = nullptr; 5918 5919 // Do not export/import inline function when -fno-dllexport-inlines is 5920 // passed. But add attribute for later local static var check. 5921 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 5922 TSK != TSK_ExplicitInstantiationDeclaration && 5923 TSK != TSK_ExplicitInstantiationDefinition) { 5924 if (ClassExported) { 5925 NewAttr = ::new (getASTContext()) 5926 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 5927 } else { 5928 NewAttr = ::new (getASTContext()) 5929 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 5930 } 5931 } else { 5932 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5933 } 5934 5935 NewAttr->setInherited(true); 5936 Member->addAttr(NewAttr); 5937 5938 if (MD) { 5939 // Propagate DLLAttr to friend re-declarations of MD that have already 5940 // been constructed. 5941 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 5942 FD = FD->getPreviousDecl()) { 5943 if (FD->getFriendObjectKind() == Decl::FOK_None) 5944 continue; 5945 assert(!getDLLAttr(FD) && 5946 "friend re-decl should not already have a DLLAttr"); 5947 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5948 NewAttr->setInherited(true); 5949 FD->addAttr(NewAttr); 5950 } 5951 } 5952 } 5953 } 5954 5955 if (ClassExported) 5956 DelayedDllExportClasses.push_back(Class); 5957 } 5958 5959 /// Perform propagation of DLL attributes from a derived class to a 5960 /// templated base class for MS compatibility. 5961 void Sema::propagateDLLAttrToBaseClassTemplate( 5962 CXXRecordDecl *Class, Attr *ClassAttr, 5963 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 5964 if (getDLLAttr( 5965 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 5966 // If the base class template has a DLL attribute, don't try to change it. 5967 return; 5968 } 5969 5970 auto TSK = BaseTemplateSpec->getSpecializationKind(); 5971 if (!getDLLAttr(BaseTemplateSpec) && 5972 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 5973 TSK == TSK_ImplicitInstantiation)) { 5974 // The template hasn't been instantiated yet (or it has, but only as an 5975 // explicit instantiation declaration or implicit instantiation, which means 5976 // we haven't codegenned any members yet), so propagate the attribute. 5977 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5978 NewAttr->setInherited(true); 5979 BaseTemplateSpec->addAttr(NewAttr); 5980 5981 // If this was an import, mark that we propagated it from a derived class to 5982 // a base class template specialization. 5983 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 5984 ImportAttr->setPropagatedToBaseTemplate(); 5985 5986 // If the template is already instantiated, checkDLLAttributeRedeclaration() 5987 // needs to be run again to work see the new attribute. Otherwise this will 5988 // get run whenever the template is instantiated. 5989 if (TSK != TSK_Undeclared) 5990 checkClassLevelDLLAttribute(BaseTemplateSpec); 5991 5992 return; 5993 } 5994 5995 if (getDLLAttr(BaseTemplateSpec)) { 5996 // The template has already been specialized or instantiated with an 5997 // attribute, explicitly or through propagation. We should not try to change 5998 // it. 5999 return; 6000 } 6001 6002 // The template was previously instantiated or explicitly specialized without 6003 // a dll attribute, It's too late for us to add an attribute, so warn that 6004 // this is unsupported. 6005 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6006 << BaseTemplateSpec->isExplicitSpecialization(); 6007 Diag(ClassAttr->getLocation(), diag::note_attribute); 6008 if (BaseTemplateSpec->isExplicitSpecialization()) { 6009 Diag(BaseTemplateSpec->getLocation(), 6010 diag::note_template_class_explicit_specialization_was_here) 6011 << BaseTemplateSpec; 6012 } else { 6013 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6014 diag::note_template_class_instantiation_was_here) 6015 << BaseTemplateSpec; 6016 } 6017 } 6018 6019 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 6020 SourceLocation DefaultLoc) { 6021 switch (S.getSpecialMember(MD)) { 6022 case Sema::CXXDefaultConstructor: 6023 S.DefineImplicitDefaultConstructor(DefaultLoc, 6024 cast<CXXConstructorDecl>(MD)); 6025 break; 6026 case Sema::CXXCopyConstructor: 6027 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 6028 break; 6029 case Sema::CXXCopyAssignment: 6030 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 6031 break; 6032 case Sema::CXXDestructor: 6033 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 6034 break; 6035 case Sema::CXXMoveConstructor: 6036 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 6037 break; 6038 case Sema::CXXMoveAssignment: 6039 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 6040 break; 6041 case Sema::CXXInvalid: 6042 llvm_unreachable("Invalid special member."); 6043 } 6044 } 6045 6046 /// Determine whether a type is permitted to be passed or returned in 6047 /// registers, per C++ [class.temporary]p3. 6048 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6049 TargetInfo::CallingConvKind CCK) { 6050 if (D->isDependentType() || D->isInvalidDecl()) 6051 return false; 6052 6053 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6054 // The PS4 platform ABI follows the behavior of Clang 3.2. 6055 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6056 return !D->hasNonTrivialDestructorForCall() && 6057 !D->hasNonTrivialCopyConstructorForCall(); 6058 6059 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6060 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6061 bool DtorIsTrivialForCall = false; 6062 6063 // If a class has at least one non-deleted, trivial copy constructor, it 6064 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6065 // 6066 // Note: This permits classes with non-trivial copy or move ctors to be 6067 // passed in registers, so long as they *also* have a trivial copy ctor, 6068 // which is non-conforming. 6069 if (D->needsImplicitCopyConstructor()) { 6070 if (!D->defaultedCopyConstructorIsDeleted()) { 6071 if (D->hasTrivialCopyConstructor()) 6072 CopyCtorIsTrivial = true; 6073 if (D->hasTrivialCopyConstructorForCall()) 6074 CopyCtorIsTrivialForCall = true; 6075 } 6076 } else { 6077 for (const CXXConstructorDecl *CD : D->ctors()) { 6078 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6079 if (CD->isTrivial()) 6080 CopyCtorIsTrivial = true; 6081 if (CD->isTrivialForCall()) 6082 CopyCtorIsTrivialForCall = true; 6083 } 6084 } 6085 } 6086 6087 if (D->needsImplicitDestructor()) { 6088 if (!D->defaultedDestructorIsDeleted() && 6089 D->hasTrivialDestructorForCall()) 6090 DtorIsTrivialForCall = true; 6091 } else if (const auto *DD = D->getDestructor()) { 6092 if (!DD->isDeleted() && DD->isTrivialForCall()) 6093 DtorIsTrivialForCall = true; 6094 } 6095 6096 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6097 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6098 return true; 6099 6100 // If a class has a destructor, we'd really like to pass it indirectly 6101 // because it allows us to elide copies. Unfortunately, MSVC makes that 6102 // impossible for small types, which it will pass in a single register or 6103 // stack slot. Most objects with dtors are large-ish, so handle that early. 6104 // We can't call out all large objects as being indirect because there are 6105 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6106 // how we pass large POD types. 6107 6108 // Note: This permits small classes with nontrivial destructors to be 6109 // passed in registers, which is non-conforming. 6110 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6111 uint64_t TypeSize = isAArch64 ? 128 : 64; 6112 6113 if (CopyCtorIsTrivial && 6114 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6115 return true; 6116 return false; 6117 } 6118 6119 // Per C++ [class.temporary]p3, the relevant condition is: 6120 // each copy constructor, move constructor, and destructor of X is 6121 // either trivial or deleted, and X has at least one non-deleted copy 6122 // or move constructor 6123 bool HasNonDeletedCopyOrMove = false; 6124 6125 if (D->needsImplicitCopyConstructor() && 6126 !D->defaultedCopyConstructorIsDeleted()) { 6127 if (!D->hasTrivialCopyConstructorForCall()) 6128 return false; 6129 HasNonDeletedCopyOrMove = true; 6130 } 6131 6132 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6133 !D->defaultedMoveConstructorIsDeleted()) { 6134 if (!D->hasTrivialMoveConstructorForCall()) 6135 return false; 6136 HasNonDeletedCopyOrMove = true; 6137 } 6138 6139 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6140 !D->hasTrivialDestructorForCall()) 6141 return false; 6142 6143 for (const CXXMethodDecl *MD : D->methods()) { 6144 if (MD->isDeleted()) 6145 continue; 6146 6147 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6148 if (CD && CD->isCopyOrMoveConstructor()) 6149 HasNonDeletedCopyOrMove = true; 6150 else if (!isa<CXXDestructorDecl>(MD)) 6151 continue; 6152 6153 if (!MD->isTrivialForCall()) 6154 return false; 6155 } 6156 6157 return HasNonDeletedCopyOrMove; 6158 } 6159 6160 /// Perform semantic checks on a class definition that has been 6161 /// completing, introducing implicitly-declared members, checking for 6162 /// abstract types, etc. 6163 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 6164 if (!Record) 6165 return; 6166 6167 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6168 AbstractUsageInfo Info(*this, Record); 6169 CheckAbstractClassUsage(Info, Record); 6170 } 6171 6172 // If this is not an aggregate type and has no user-declared constructor, 6173 // complain about any non-static data members of reference or const scalar 6174 // type, since they will never get initializers. 6175 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6176 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6177 !Record->isLambda()) { 6178 bool Complained = false; 6179 for (const auto *F : Record->fields()) { 6180 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6181 continue; 6182 6183 if (F->getType()->isReferenceType() || 6184 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6185 if (!Complained) { 6186 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6187 << Record->getTagKind() << Record; 6188 Complained = true; 6189 } 6190 6191 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6192 << F->getType()->isReferenceType() 6193 << F->getDeclName(); 6194 } 6195 } 6196 } 6197 6198 if (Record->getIdentifier()) { 6199 // C++ [class.mem]p13: 6200 // If T is the name of a class, then each of the following shall have a 6201 // name different from T: 6202 // - every member of every anonymous union that is a member of class T. 6203 // 6204 // C++ [class.mem]p14: 6205 // In addition, if class T has a user-declared constructor (12.1), every 6206 // non-static data member of class T shall have a name different from T. 6207 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6208 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6209 ++I) { 6210 NamedDecl *D = (*I)->getUnderlyingDecl(); 6211 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6212 Record->hasUserDeclaredConstructor()) || 6213 isa<IndirectFieldDecl>(D)) { 6214 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6215 << D->getDeclName(); 6216 break; 6217 } 6218 } 6219 } 6220 6221 // Warn if the class has virtual methods but non-virtual public destructor. 6222 if (Record->isPolymorphic() && !Record->isDependentType()) { 6223 CXXDestructorDecl *dtor = Record->getDestructor(); 6224 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6225 !Record->hasAttr<FinalAttr>()) 6226 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6227 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6228 } 6229 6230 if (Record->isAbstract()) { 6231 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6232 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6233 << FA->isSpelledAsSealed(); 6234 DiagnoseAbstractType(Record); 6235 } 6236 } 6237 6238 // Warn if the class has a final destructor but is not itself marked final. 6239 if (!Record->hasAttr<FinalAttr>()) { 6240 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6241 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6242 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6243 << FA->isSpelledAsSealed() 6244 << FixItHint::CreateInsertion( 6245 getLocForEndOfToken(Record->getLocation()), 6246 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6247 Diag(Record->getLocation(), 6248 diag::note_final_dtor_non_final_class_silence) 6249 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6250 } 6251 } 6252 } 6253 6254 // See if trivial_abi has to be dropped. 6255 if (Record->hasAttr<TrivialABIAttr>()) 6256 checkIllFormedTrivialABIStruct(*Record); 6257 6258 // Set HasTrivialSpecialMemberForCall if the record has attribute 6259 // "trivial_abi". 6260 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6261 6262 if (HasTrivialABI) 6263 Record->setHasTrivialSpecialMemberForCall(); 6264 6265 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6266 // Check whether the explicitly-defaulted special members are valid. 6267 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 6268 CheckExplicitlyDefaultedSpecialMember(M); 6269 6270 // For an explicitly defaulted or deleted special member, we defer 6271 // determining triviality until the class is complete. That time is now! 6272 CXXSpecialMember CSM = getSpecialMember(M); 6273 if (!M->isImplicit() && !M->isUserProvided()) { 6274 if (CSM != CXXInvalid) { 6275 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6276 // Inform the class that we've finished declaring this member. 6277 Record->finishedDefaultedOrDeletedMember(M); 6278 M->setTrivialForCall( 6279 HasTrivialABI || 6280 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6281 Record->setTrivialForCallFlags(M); 6282 } 6283 } 6284 6285 // Set triviality for the purpose of calls if this is a user-provided 6286 // copy/move constructor or destructor. 6287 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6288 CSM == CXXDestructor) && M->isUserProvided()) { 6289 M->setTrivialForCall(HasTrivialABI); 6290 Record->setTrivialForCallFlags(M); 6291 } 6292 6293 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6294 M->hasAttr<DLLExportAttr>()) { 6295 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6296 M->isTrivial() && 6297 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6298 CSM == CXXDestructor)) 6299 M->dropAttr<DLLExportAttr>(); 6300 6301 if (M->hasAttr<DLLExportAttr>()) { 6302 // Define after any fields with in-class initializers have been parsed. 6303 DelayedDllExportMemberFunctions.push_back(M); 6304 } 6305 } 6306 }; 6307 6308 bool HasMethodWithOverrideControl = false, 6309 HasOverridingMethodWithoutOverrideControl = false; 6310 if (!Record->isDependentType()) { 6311 // Check the destructor before any other member function. We need to 6312 // determine whether it's trivial in order to determine whether the claas 6313 // type is a literal type, which is a prerequisite for determining whether 6314 // other special member functions are valid and whether they're implicitly 6315 // 'constexpr'. 6316 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6317 CompleteMemberFunction(Dtor); 6318 6319 for (auto *M : Record->methods()) { 6320 // See if a method overloads virtual methods in a base 6321 // class without overriding any. 6322 if (!M->isStatic()) 6323 DiagnoseHiddenVirtualMethods(M); 6324 if (M->hasAttr<OverrideAttr>()) 6325 HasMethodWithOverrideControl = true; 6326 else if (M->size_overridden_methods() > 0) 6327 HasOverridingMethodWithoutOverrideControl = true; 6328 6329 if (!isa<CXXDestructorDecl>(M)) 6330 CompleteMemberFunction(M); 6331 } 6332 } 6333 6334 if (HasMethodWithOverrideControl && 6335 HasOverridingMethodWithoutOverrideControl) { 6336 // At least one method has the 'override' control declared. 6337 // Diagnose all other overridden methods which do not have 'override' specified on them. 6338 for (auto *M : Record->methods()) 6339 DiagnoseAbsenceOfOverrideControl(M); 6340 } 6341 6342 // ms_struct is a request to use the same ABI rules as MSVC. Check 6343 // whether this class uses any C++ features that are implemented 6344 // completely differently in MSVC, and if so, emit a diagnostic. 6345 // That diagnostic defaults to an error, but we allow projects to 6346 // map it down to a warning (or ignore it). It's a fairly common 6347 // practice among users of the ms_struct pragma to mass-annotate 6348 // headers, sweeping up a bunch of types that the project doesn't 6349 // really rely on MSVC-compatible layout for. We must therefore 6350 // support "ms_struct except for C++ stuff" as a secondary ABI. 6351 if (Record->isMsStruct(Context) && 6352 (Record->isPolymorphic() || Record->getNumBases())) { 6353 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6354 } 6355 6356 checkClassLevelDLLAttribute(Record); 6357 checkClassLevelCodeSegAttribute(Record); 6358 6359 bool ClangABICompat4 = 6360 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6361 TargetInfo::CallingConvKind CCK = 6362 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6363 bool CanPass = canPassInRegisters(*this, Record, CCK); 6364 6365 // Do not change ArgPassingRestrictions if it has already been set to 6366 // APK_CanNeverPassInRegs. 6367 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6368 Record->setArgPassingRestrictions(CanPass 6369 ? RecordDecl::APK_CanPassInRegs 6370 : RecordDecl::APK_CannotPassInRegs); 6371 6372 // If canPassInRegisters returns true despite the record having a non-trivial 6373 // destructor, the record is destructed in the callee. This happens only when 6374 // the record or one of its subobjects has a field annotated with trivial_abi 6375 // or a field qualified with ObjC __strong/__weak. 6376 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6377 Record->setParamDestroyedInCallee(true); 6378 else if (Record->hasNonTrivialDestructor()) 6379 Record->setParamDestroyedInCallee(CanPass); 6380 6381 if (getLangOpts().ForceEmitVTables) { 6382 // If we want to emit all the vtables, we need to mark it as used. This 6383 // is especially required for cases like vtable assumption loads. 6384 MarkVTableUsed(Record->getInnerLocStart(), Record); 6385 } 6386 } 6387 6388 /// Look up the special member function that would be called by a special 6389 /// member function for a subobject of class type. 6390 /// 6391 /// \param Class The class type of the subobject. 6392 /// \param CSM The kind of special member function. 6393 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6394 /// \param ConstRHS True if this is a copy operation with a const object 6395 /// on its RHS, that is, if the argument to the outer special member 6396 /// function is 'const' and this is not a field marked 'mutable'. 6397 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6398 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6399 unsigned FieldQuals, bool ConstRHS) { 6400 unsigned LHSQuals = 0; 6401 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6402 LHSQuals = FieldQuals; 6403 6404 unsigned RHSQuals = FieldQuals; 6405 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6406 RHSQuals = 0; 6407 else if (ConstRHS) 6408 RHSQuals |= Qualifiers::Const; 6409 6410 return S.LookupSpecialMember(Class, CSM, 6411 RHSQuals & Qualifiers::Const, 6412 RHSQuals & Qualifiers::Volatile, 6413 false, 6414 LHSQuals & Qualifiers::Const, 6415 LHSQuals & Qualifiers::Volatile); 6416 } 6417 6418 class Sema::InheritedConstructorInfo { 6419 Sema &S; 6420 SourceLocation UseLoc; 6421 6422 /// A mapping from the base classes through which the constructor was 6423 /// inherited to the using shadow declaration in that base class (or a null 6424 /// pointer if the constructor was declared in that base class). 6425 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6426 InheritedFromBases; 6427 6428 public: 6429 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6430 ConstructorUsingShadowDecl *Shadow) 6431 : S(S), UseLoc(UseLoc) { 6432 bool DiagnosedMultipleConstructedBases = false; 6433 CXXRecordDecl *ConstructedBase = nullptr; 6434 UsingDecl *ConstructedBaseUsing = nullptr; 6435 6436 // Find the set of such base class subobjects and check that there's a 6437 // unique constructed subobject. 6438 for (auto *D : Shadow->redecls()) { 6439 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6440 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6441 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6442 6443 InheritedFromBases.insert( 6444 std::make_pair(DNominatedBase->getCanonicalDecl(), 6445 DShadow->getNominatedBaseClassShadowDecl())); 6446 if (DShadow->constructsVirtualBase()) 6447 InheritedFromBases.insert( 6448 std::make_pair(DConstructedBase->getCanonicalDecl(), 6449 DShadow->getConstructedBaseClassShadowDecl())); 6450 else 6451 assert(DNominatedBase == DConstructedBase); 6452 6453 // [class.inhctor.init]p2: 6454 // If the constructor was inherited from multiple base class subobjects 6455 // of type B, the program is ill-formed. 6456 if (!ConstructedBase) { 6457 ConstructedBase = DConstructedBase; 6458 ConstructedBaseUsing = D->getUsingDecl(); 6459 } else if (ConstructedBase != DConstructedBase && 6460 !Shadow->isInvalidDecl()) { 6461 if (!DiagnosedMultipleConstructedBases) { 6462 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6463 << Shadow->getTargetDecl(); 6464 S.Diag(ConstructedBaseUsing->getLocation(), 6465 diag::note_ambiguous_inherited_constructor_using) 6466 << ConstructedBase; 6467 DiagnosedMultipleConstructedBases = true; 6468 } 6469 S.Diag(D->getUsingDecl()->getLocation(), 6470 diag::note_ambiguous_inherited_constructor_using) 6471 << DConstructedBase; 6472 } 6473 } 6474 6475 if (DiagnosedMultipleConstructedBases) 6476 Shadow->setInvalidDecl(); 6477 } 6478 6479 /// Find the constructor to use for inherited construction of a base class, 6480 /// and whether that base class constructor inherits the constructor from a 6481 /// virtual base class (in which case it won't actually invoke it). 6482 std::pair<CXXConstructorDecl *, bool> 6483 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6484 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6485 if (It == InheritedFromBases.end()) 6486 return std::make_pair(nullptr, false); 6487 6488 // This is an intermediary class. 6489 if (It->second) 6490 return std::make_pair( 6491 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6492 It->second->constructsVirtualBase()); 6493 6494 // This is the base class from which the constructor was inherited. 6495 return std::make_pair(Ctor, false); 6496 } 6497 }; 6498 6499 /// Is the special member function which would be selected to perform the 6500 /// specified operation on the specified class type a constexpr constructor? 6501 static bool 6502 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6503 Sema::CXXSpecialMember CSM, unsigned Quals, 6504 bool ConstRHS, 6505 CXXConstructorDecl *InheritedCtor = nullptr, 6506 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6507 // If we're inheriting a constructor, see if we need to call it for this base 6508 // class. 6509 if (InheritedCtor) { 6510 assert(CSM == Sema::CXXDefaultConstructor); 6511 auto BaseCtor = 6512 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6513 if (BaseCtor) 6514 return BaseCtor->isConstexpr(); 6515 } 6516 6517 if (CSM == Sema::CXXDefaultConstructor) 6518 return ClassDecl->hasConstexprDefaultConstructor(); 6519 6520 Sema::SpecialMemberOverloadResult SMOR = 6521 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6522 if (!SMOR.getMethod()) 6523 // A constructor we wouldn't select can't be "involved in initializing" 6524 // anything. 6525 return true; 6526 return SMOR.getMethod()->isConstexpr(); 6527 } 6528 6529 /// Determine whether the specified special member function would be constexpr 6530 /// if it were implicitly defined. 6531 static bool defaultedSpecialMemberIsConstexpr( 6532 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6533 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6534 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6535 if (!S.getLangOpts().CPlusPlus11) 6536 return false; 6537 6538 // C++11 [dcl.constexpr]p4: 6539 // In the definition of a constexpr constructor [...] 6540 bool Ctor = true; 6541 switch (CSM) { 6542 case Sema::CXXDefaultConstructor: 6543 if (Inherited) 6544 break; 6545 // Since default constructor lookup is essentially trivial (and cannot 6546 // involve, for instance, template instantiation), we compute whether a 6547 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6548 // 6549 // This is important for performance; we need to know whether the default 6550 // constructor is constexpr to determine whether the type is a literal type. 6551 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6552 6553 case Sema::CXXCopyConstructor: 6554 case Sema::CXXMoveConstructor: 6555 // For copy or move constructors, we need to perform overload resolution. 6556 break; 6557 6558 case Sema::CXXCopyAssignment: 6559 case Sema::CXXMoveAssignment: 6560 if (!S.getLangOpts().CPlusPlus14) 6561 return false; 6562 // In C++1y, we need to perform overload resolution. 6563 Ctor = false; 6564 break; 6565 6566 case Sema::CXXDestructor: 6567 case Sema::CXXInvalid: 6568 return false; 6569 } 6570 6571 // -- if the class is a non-empty union, or for each non-empty anonymous 6572 // union member of a non-union class, exactly one non-static data member 6573 // shall be initialized; [DR1359] 6574 // 6575 // If we squint, this is guaranteed, since exactly one non-static data member 6576 // will be initialized (if the constructor isn't deleted), we just don't know 6577 // which one. 6578 if (Ctor && ClassDecl->isUnion()) 6579 return CSM == Sema::CXXDefaultConstructor 6580 ? ClassDecl->hasInClassInitializer() || 6581 !ClassDecl->hasVariantMembers() 6582 : true; 6583 6584 // -- the class shall not have any virtual base classes; 6585 if (Ctor && ClassDecl->getNumVBases()) 6586 return false; 6587 6588 // C++1y [class.copy]p26: 6589 // -- [the class] is a literal type, and 6590 if (!Ctor && !ClassDecl->isLiteral()) 6591 return false; 6592 6593 // -- every constructor involved in initializing [...] base class 6594 // sub-objects shall be a constexpr constructor; 6595 // -- the assignment operator selected to copy/move each direct base 6596 // class is a constexpr function, and 6597 for (const auto &B : ClassDecl->bases()) { 6598 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6599 if (!BaseType) continue; 6600 6601 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6602 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6603 InheritedCtor, Inherited)) 6604 return false; 6605 } 6606 6607 // -- every constructor involved in initializing non-static data members 6608 // [...] shall be a constexpr constructor; 6609 // -- every non-static data member and base class sub-object shall be 6610 // initialized 6611 // -- for each non-static data member of X that is of class type (or array 6612 // thereof), the assignment operator selected to copy/move that member is 6613 // a constexpr function 6614 for (const auto *F : ClassDecl->fields()) { 6615 if (F->isInvalidDecl()) 6616 continue; 6617 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6618 continue; 6619 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6620 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6621 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6622 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6623 BaseType.getCVRQualifiers(), 6624 ConstArg && !F->isMutable())) 6625 return false; 6626 } else if (CSM == Sema::CXXDefaultConstructor) { 6627 return false; 6628 } 6629 } 6630 6631 // All OK, it's constexpr! 6632 return true; 6633 } 6634 6635 static Sema::ImplicitExceptionSpecification 6636 ComputeDefaultedSpecialMemberExceptionSpec( 6637 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6638 Sema::InheritedConstructorInfo *ICI); 6639 6640 static Sema::ImplicitExceptionSpecification 6641 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6642 auto CSM = S.getSpecialMember(MD); 6643 if (CSM != Sema::CXXInvalid) 6644 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); 6645 6646 auto *CD = cast<CXXConstructorDecl>(MD); 6647 assert(CD->getInheritedConstructor() && 6648 "only special members have implicit exception specs"); 6649 Sema::InheritedConstructorInfo ICI( 6650 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6651 return ComputeDefaultedSpecialMemberExceptionSpec( 6652 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6653 } 6654 6655 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6656 CXXMethodDecl *MD) { 6657 FunctionProtoType::ExtProtoInfo EPI; 6658 6659 // Build an exception specification pointing back at this member. 6660 EPI.ExceptionSpec.Type = EST_Unevaluated; 6661 EPI.ExceptionSpec.SourceDecl = MD; 6662 6663 // Set the calling convention to the default for C++ instance methods. 6664 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6665 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6666 /*IsCXXMethod=*/true)); 6667 return EPI; 6668 } 6669 6670 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6671 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6672 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6673 return; 6674 6675 // Evaluate the exception specification. 6676 auto IES = computeImplicitExceptionSpec(*this, Loc, MD); 6677 auto ESI = IES.getExceptionSpec(); 6678 6679 // Update the type of the special member to use it. 6680 UpdateExceptionSpec(MD, ESI); 6681 6682 // A user-provided destructor can be defined outside the class. When that 6683 // happens, be sure to update the exception specification on both 6684 // declarations. 6685 const FunctionProtoType *CanonicalFPT = 6686 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6687 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6688 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6689 } 6690 6691 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6692 CXXRecordDecl *RD = MD->getParent(); 6693 CXXSpecialMember CSM = getSpecialMember(MD); 6694 6695 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6696 "not an explicitly-defaulted special member"); 6697 6698 // Whether this was the first-declared instance of the constructor. 6699 // This affects whether we implicitly add an exception spec and constexpr. 6700 bool First = MD == MD->getCanonicalDecl(); 6701 6702 bool HadError = false; 6703 6704 // C++11 [dcl.fct.def.default]p1: 6705 // A function that is explicitly defaulted shall 6706 // -- be a special member function (checked elsewhere), 6707 // -- have the same type (except for ref-qualifiers, and except that a 6708 // copy operation can take a non-const reference) as an implicit 6709 // declaration, and 6710 // -- not have default arguments. 6711 // C++2a changes the second bullet to instead delete the function if it's 6712 // defaulted on its first declaration, unless it's "an assignment operator, 6713 // and its return type differs or its parameter type is not a reference". 6714 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First; 6715 bool ShouldDeleteForTypeMismatch = false; 6716 unsigned ExpectedParams = 1; 6717 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6718 ExpectedParams = 0; 6719 if (MD->getNumParams() != ExpectedParams) { 6720 // This checks for default arguments: a copy or move constructor with a 6721 // default argument is classified as a default constructor, and assignment 6722 // operations and destructors can't have default arguments. 6723 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6724 << CSM << MD->getSourceRange(); 6725 HadError = true; 6726 } else if (MD->isVariadic()) { 6727 if (DeleteOnTypeMismatch) 6728 ShouldDeleteForTypeMismatch = true; 6729 else { 6730 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6731 << CSM << MD->getSourceRange(); 6732 HadError = true; 6733 } 6734 } 6735 6736 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6737 6738 bool CanHaveConstParam = false; 6739 if (CSM == CXXCopyConstructor) 6740 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6741 else if (CSM == CXXCopyAssignment) 6742 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6743 6744 QualType ReturnType = Context.VoidTy; 6745 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6746 // Check for return type matching. 6747 ReturnType = Type->getReturnType(); 6748 6749 QualType DeclType = Context.getTypeDeclType(RD); 6750 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 6751 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 6752 6753 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6754 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6755 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6756 HadError = true; 6757 } 6758 6759 // A defaulted special member cannot have cv-qualifiers. 6760 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 6761 if (DeleteOnTypeMismatch) 6762 ShouldDeleteForTypeMismatch = true; 6763 else { 6764 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6765 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6766 HadError = true; 6767 } 6768 } 6769 } 6770 6771 // Check for parameter type matching. 6772 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6773 bool HasConstParam = false; 6774 if (ExpectedParams && ArgType->isReferenceType()) { 6775 // Argument must be reference to possibly-const T. 6776 QualType ReferentType = ArgType->getPointeeType(); 6777 HasConstParam = ReferentType.isConstQualified(); 6778 6779 if (ReferentType.isVolatileQualified()) { 6780 if (DeleteOnTypeMismatch) 6781 ShouldDeleteForTypeMismatch = true; 6782 else { 6783 Diag(MD->getLocation(), 6784 diag::err_defaulted_special_member_volatile_param) << CSM; 6785 HadError = true; 6786 } 6787 } 6788 6789 if (HasConstParam && !CanHaveConstParam) { 6790 if (DeleteOnTypeMismatch) 6791 ShouldDeleteForTypeMismatch = true; 6792 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6793 Diag(MD->getLocation(), 6794 diag::err_defaulted_special_member_copy_const_param) 6795 << (CSM == CXXCopyAssignment); 6796 // FIXME: Explain why this special member can't be const. 6797 HadError = true; 6798 } else { 6799 Diag(MD->getLocation(), 6800 diag::err_defaulted_special_member_move_const_param) 6801 << (CSM == CXXMoveAssignment); 6802 HadError = true; 6803 } 6804 } 6805 } else if (ExpectedParams) { 6806 // A copy assignment operator can take its argument by value, but a 6807 // defaulted one cannot. 6808 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6809 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6810 HadError = true; 6811 } 6812 6813 // C++11 [dcl.fct.def.default]p2: 6814 // An explicitly-defaulted function may be declared constexpr only if it 6815 // would have been implicitly declared as constexpr, 6816 // Do not apply this rule to members of class templates, since core issue 1358 6817 // makes such functions always instantiate to constexpr functions. For 6818 // functions which cannot be constexpr (for non-constructors in C++11 and for 6819 // destructors in C++1y), this is checked elsewhere. 6820 // 6821 // FIXME: This should not apply if the member is deleted. 6822 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6823 HasConstParam); 6824 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6825 : isa<CXXConstructorDecl>(MD)) && 6826 MD->isConstexpr() && !Constexpr && 6827 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6828 Diag(MD->getBeginLoc(), MD->isConsteval() 6829 ? diag::err_incorrect_defaulted_consteval 6830 : diag::err_incorrect_defaulted_constexpr) 6831 << CSM; 6832 // FIXME: Explain why the special member can't be constexpr. 6833 HadError = true; 6834 } 6835 6836 if (First) { 6837 // C++2a [dcl.fct.def.default]p3: 6838 // If a function is explicitly defaulted on its first declaration, it is 6839 // implicitly considered to be constexpr if the implicit declaration 6840 // would be. 6841 MD->setConstexprKind(Constexpr ? CSK_constexpr : CSK_unspecified); 6842 6843 if (!Type->hasExceptionSpec()) { 6844 // C++2a [except.spec]p3: 6845 // If a declaration of a function does not have a noexcept-specifier 6846 // [and] is defaulted on its first declaration, [...] the exception 6847 // specification is as specified below 6848 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6849 EPI.ExceptionSpec.Type = EST_Unevaluated; 6850 EPI.ExceptionSpec.SourceDecl = MD; 6851 MD->setType(Context.getFunctionType(ReturnType, 6852 llvm::makeArrayRef(&ArgType, 6853 ExpectedParams), 6854 EPI)); 6855 } 6856 } 6857 6858 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 6859 if (First) { 6860 SetDeclDeleted(MD, MD->getLocation()); 6861 if (!inTemplateInstantiation() && !HadError) { 6862 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 6863 if (ShouldDeleteForTypeMismatch) { 6864 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 6865 } else { 6866 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6867 } 6868 } 6869 if (ShouldDeleteForTypeMismatch && !HadError) { 6870 Diag(MD->getLocation(), 6871 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 6872 } 6873 } else { 6874 // C++11 [dcl.fct.def.default]p4: 6875 // [For a] user-provided explicitly-defaulted function [...] if such a 6876 // function is implicitly defined as deleted, the program is ill-formed. 6877 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6878 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 6879 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6880 HadError = true; 6881 } 6882 } 6883 6884 if (HadError) 6885 MD->setInvalidDecl(); 6886 } 6887 6888 void Sema::CheckDelayedMemberExceptionSpecs() { 6889 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 6890 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 6891 6892 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 6893 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 6894 6895 // Perform any deferred checking of exception specifications for virtual 6896 // destructors. 6897 for (auto &Check : Overriding) 6898 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6899 6900 // Perform any deferred checking of exception specifications for befriended 6901 // special members. 6902 for (auto &Check : Equivalent) 6903 CheckEquivalentExceptionSpec(Check.second, Check.first); 6904 } 6905 6906 namespace { 6907 /// CRTP base class for visiting operations performed by a special member 6908 /// function (or inherited constructor). 6909 template<typename Derived> 6910 struct SpecialMemberVisitor { 6911 Sema &S; 6912 CXXMethodDecl *MD; 6913 Sema::CXXSpecialMember CSM; 6914 Sema::InheritedConstructorInfo *ICI; 6915 6916 // Properties of the special member, computed for convenience. 6917 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 6918 6919 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6920 Sema::InheritedConstructorInfo *ICI) 6921 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 6922 switch (CSM) { 6923 case Sema::CXXDefaultConstructor: 6924 case Sema::CXXCopyConstructor: 6925 case Sema::CXXMoveConstructor: 6926 IsConstructor = true; 6927 break; 6928 case Sema::CXXCopyAssignment: 6929 case Sema::CXXMoveAssignment: 6930 IsAssignment = true; 6931 break; 6932 case Sema::CXXDestructor: 6933 break; 6934 case Sema::CXXInvalid: 6935 llvm_unreachable("invalid special member kind"); 6936 } 6937 6938 if (MD->getNumParams()) { 6939 if (const ReferenceType *RT = 6940 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6941 ConstArg = RT->getPointeeType().isConstQualified(); 6942 } 6943 } 6944 6945 Derived &getDerived() { return static_cast<Derived&>(*this); } 6946 6947 /// Is this a "move" special member? 6948 bool isMove() const { 6949 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 6950 } 6951 6952 /// Look up the corresponding special member in the given class. 6953 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 6954 unsigned Quals, bool IsMutable) { 6955 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6956 ConstArg && !IsMutable); 6957 } 6958 6959 /// Look up the constructor for the specified base class to see if it's 6960 /// overridden due to this being an inherited constructor. 6961 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 6962 if (!ICI) 6963 return {}; 6964 assert(CSM == Sema::CXXDefaultConstructor); 6965 auto *BaseCtor = 6966 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 6967 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 6968 return MD; 6969 return {}; 6970 } 6971 6972 /// A base or member subobject. 6973 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6974 6975 /// Get the location to use for a subobject in diagnostics. 6976 static SourceLocation getSubobjectLoc(Subobject Subobj) { 6977 // FIXME: For an indirect virtual base, the direct base leading to 6978 // the indirect virtual base would be a more useful choice. 6979 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 6980 return B->getBaseTypeLoc(); 6981 else 6982 return Subobj.get<FieldDecl*>()->getLocation(); 6983 } 6984 6985 enum BasesToVisit { 6986 /// Visit all non-virtual (direct) bases. 6987 VisitNonVirtualBases, 6988 /// Visit all direct bases, virtual or not. 6989 VisitDirectBases, 6990 /// Visit all non-virtual bases, and all virtual bases if the class 6991 /// is not abstract. 6992 VisitPotentiallyConstructedBases, 6993 /// Visit all direct or virtual bases. 6994 VisitAllBases 6995 }; 6996 6997 // Visit the bases and members of the class. 6998 bool visit(BasesToVisit Bases) { 6999 CXXRecordDecl *RD = MD->getParent(); 7000 7001 if (Bases == VisitPotentiallyConstructedBases) 7002 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 7003 7004 for (auto &B : RD->bases()) 7005 if ((Bases == VisitDirectBases || !B.isVirtual()) && 7006 getDerived().visitBase(&B)) 7007 return true; 7008 7009 if (Bases == VisitAllBases) 7010 for (auto &B : RD->vbases()) 7011 if (getDerived().visitBase(&B)) 7012 return true; 7013 7014 for (auto *F : RD->fields()) 7015 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 7016 getDerived().visitField(F)) 7017 return true; 7018 7019 return false; 7020 } 7021 }; 7022 } 7023 7024 namespace { 7025 struct SpecialMemberDeletionInfo 7026 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 7027 bool Diagnose; 7028 7029 SourceLocation Loc; 7030 7031 bool AllFieldsAreConst; 7032 7033 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 7034 Sema::CXXSpecialMember CSM, 7035 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 7036 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 7037 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 7038 7039 bool inUnion() const { return MD->getParent()->isUnion(); } 7040 7041 Sema::CXXSpecialMember getEffectiveCSM() { 7042 return ICI ? Sema::CXXInvalid : CSM; 7043 } 7044 7045 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 7046 7047 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 7048 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 7049 7050 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 7051 bool shouldDeleteForField(FieldDecl *FD); 7052 bool shouldDeleteForAllConstMembers(); 7053 7054 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 7055 unsigned Quals); 7056 bool shouldDeleteForSubobjectCall(Subobject Subobj, 7057 Sema::SpecialMemberOverloadResult SMOR, 7058 bool IsDtorCallInCtor); 7059 7060 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 7061 }; 7062 } 7063 7064 /// Is the given special member inaccessible when used on the given 7065 /// sub-object. 7066 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 7067 CXXMethodDecl *target) { 7068 /// If we're operating on a base class, the object type is the 7069 /// type of this special member. 7070 QualType objectTy; 7071 AccessSpecifier access = target->getAccess(); 7072 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 7073 objectTy = S.Context.getTypeDeclType(MD->getParent()); 7074 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 7075 7076 // If we're operating on a field, the object type is the type of the field. 7077 } else { 7078 objectTy = S.Context.getTypeDeclType(target->getParent()); 7079 } 7080 7081 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 7082 } 7083 7084 /// Check whether we should delete a special member due to the implicit 7085 /// definition containing a call to a special member of a subobject. 7086 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 7087 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 7088 bool IsDtorCallInCtor) { 7089 CXXMethodDecl *Decl = SMOR.getMethod(); 7090 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 7091 7092 int DiagKind = -1; 7093 7094 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 7095 DiagKind = !Decl ? 0 : 1; 7096 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7097 DiagKind = 2; 7098 else if (!isAccessible(Subobj, Decl)) 7099 DiagKind = 3; 7100 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 7101 !Decl->isTrivial()) { 7102 // A member of a union must have a trivial corresponding special member. 7103 // As a weird special case, a destructor call from a union's constructor 7104 // must be accessible and non-deleted, but need not be trivial. Such a 7105 // destructor is never actually called, but is semantically checked as 7106 // if it were. 7107 DiagKind = 4; 7108 } 7109 7110 if (DiagKind == -1) 7111 return false; 7112 7113 if (Diagnose) { 7114 if (Field) { 7115 S.Diag(Field->getLocation(), 7116 diag::note_deleted_special_member_class_subobject) 7117 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 7118 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 7119 } else { 7120 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 7121 S.Diag(Base->getBeginLoc(), 7122 diag::note_deleted_special_member_class_subobject) 7123 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 7124 << Base->getType() << DiagKind << IsDtorCallInCtor 7125 << /*IsObjCPtr*/false; 7126 } 7127 7128 if (DiagKind == 1) 7129 S.NoteDeletedFunction(Decl); 7130 // FIXME: Explain inaccessibility if DiagKind == 3. 7131 } 7132 7133 return true; 7134 } 7135 7136 /// Check whether we should delete a special member function due to having a 7137 /// direct or virtual base class or non-static data member of class type M. 7138 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 7139 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 7140 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 7141 bool IsMutable = Field && Field->isMutable(); 7142 7143 // C++11 [class.ctor]p5: 7144 // -- any direct or virtual base class, or non-static data member with no 7145 // brace-or-equal-initializer, has class type M (or array thereof) and 7146 // either M has no default constructor or overload resolution as applied 7147 // to M's default constructor results in an ambiguity or in a function 7148 // that is deleted or inaccessible 7149 // C++11 [class.copy]p11, C++11 [class.copy]p23: 7150 // -- a direct or virtual base class B that cannot be copied/moved because 7151 // overload resolution, as applied to B's corresponding special member, 7152 // results in an ambiguity or a function that is deleted or inaccessible 7153 // from the defaulted special member 7154 // C++11 [class.dtor]p5: 7155 // -- any direct or virtual base class [...] has a type with a destructor 7156 // that is deleted or inaccessible 7157 if (!(CSM == Sema::CXXDefaultConstructor && 7158 Field && Field->hasInClassInitializer()) && 7159 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 7160 false)) 7161 return true; 7162 7163 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 7164 // -- any direct or virtual base class or non-static data member has a 7165 // type with a destructor that is deleted or inaccessible 7166 if (IsConstructor) { 7167 Sema::SpecialMemberOverloadResult SMOR = 7168 S.LookupSpecialMember(Class, Sema::CXXDestructor, 7169 false, false, false, false, false); 7170 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 7171 return true; 7172 } 7173 7174 return false; 7175 } 7176 7177 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 7178 FieldDecl *FD, QualType FieldType) { 7179 // The defaulted special functions are defined as deleted if this is a variant 7180 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 7181 // type under ARC. 7182 if (!FieldType.hasNonTrivialObjCLifetime()) 7183 return false; 7184 7185 // Don't make the defaulted default constructor defined as deleted if the 7186 // member has an in-class initializer. 7187 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 7188 return false; 7189 7190 if (Diagnose) { 7191 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 7192 S.Diag(FD->getLocation(), 7193 diag::note_deleted_special_member_class_subobject) 7194 << getEffectiveCSM() << ParentClass << /*IsField*/true 7195 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 7196 } 7197 7198 return true; 7199 } 7200 7201 /// Check whether we should delete a special member function due to the class 7202 /// having a particular direct or virtual base class. 7203 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 7204 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 7205 // If program is correct, BaseClass cannot be null, but if it is, the error 7206 // must be reported elsewhere. 7207 if (!BaseClass) 7208 return false; 7209 // If we have an inheriting constructor, check whether we're calling an 7210 // inherited constructor instead of a default constructor. 7211 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 7212 if (auto *BaseCtor = SMOR.getMethod()) { 7213 // Note that we do not check access along this path; other than that, 7214 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 7215 // FIXME: Check that the base has a usable destructor! Sink this into 7216 // shouldDeleteForClassSubobject. 7217 if (BaseCtor->isDeleted() && Diagnose) { 7218 S.Diag(Base->getBeginLoc(), 7219 diag::note_deleted_special_member_class_subobject) 7220 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 7221 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 7222 << /*IsObjCPtr*/false; 7223 S.NoteDeletedFunction(BaseCtor); 7224 } 7225 return BaseCtor->isDeleted(); 7226 } 7227 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 7228 } 7229 7230 /// Check whether we should delete a special member function due to the class 7231 /// having a particular non-static data member. 7232 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 7233 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 7234 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 7235 7236 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 7237 return true; 7238 7239 if (CSM == Sema::CXXDefaultConstructor) { 7240 // For a default constructor, all references must be initialized in-class 7241 // and, if a union, it must have a non-const member. 7242 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 7243 if (Diagnose) 7244 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 7245 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 7246 return true; 7247 } 7248 // C++11 [class.ctor]p5: any non-variant non-static data member of 7249 // const-qualified type (or array thereof) with no 7250 // brace-or-equal-initializer does not have a user-provided default 7251 // constructor. 7252 if (!inUnion() && FieldType.isConstQualified() && 7253 !FD->hasInClassInitializer() && 7254 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 7255 if (Diagnose) 7256 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 7257 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 7258 return true; 7259 } 7260 7261 if (inUnion() && !FieldType.isConstQualified()) 7262 AllFieldsAreConst = false; 7263 } else if (CSM == Sema::CXXCopyConstructor) { 7264 // For a copy constructor, data members must not be of rvalue reference 7265 // type. 7266 if (FieldType->isRValueReferenceType()) { 7267 if (Diagnose) 7268 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 7269 << MD->getParent() << FD << FieldType; 7270 return true; 7271 } 7272 } else if (IsAssignment) { 7273 // For an assignment operator, data members must not be of reference type. 7274 if (FieldType->isReferenceType()) { 7275 if (Diagnose) 7276 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 7277 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 7278 return true; 7279 } 7280 if (!FieldRecord && FieldType.isConstQualified()) { 7281 // C++11 [class.copy]p23: 7282 // -- a non-static data member of const non-class type (or array thereof) 7283 if (Diagnose) 7284 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 7285 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 7286 return true; 7287 } 7288 } 7289 7290 if (FieldRecord) { 7291 // Some additional restrictions exist on the variant members. 7292 if (!inUnion() && FieldRecord->isUnion() && 7293 FieldRecord->isAnonymousStructOrUnion()) { 7294 bool AllVariantFieldsAreConst = true; 7295 7296 // FIXME: Handle anonymous unions declared within anonymous unions. 7297 for (auto *UI : FieldRecord->fields()) { 7298 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 7299 7300 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 7301 return true; 7302 7303 if (!UnionFieldType.isConstQualified()) 7304 AllVariantFieldsAreConst = false; 7305 7306 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 7307 if (UnionFieldRecord && 7308 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 7309 UnionFieldType.getCVRQualifiers())) 7310 return true; 7311 } 7312 7313 // At least one member in each anonymous union must be non-const 7314 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 7315 !FieldRecord->field_empty()) { 7316 if (Diagnose) 7317 S.Diag(FieldRecord->getLocation(), 7318 diag::note_deleted_default_ctor_all_const) 7319 << !!ICI << MD->getParent() << /*anonymous union*/1; 7320 return true; 7321 } 7322 7323 // Don't check the implicit member of the anonymous union type. 7324 // This is technically non-conformant, but sanity demands it. 7325 return false; 7326 } 7327 7328 if (shouldDeleteForClassSubobject(FieldRecord, FD, 7329 FieldType.getCVRQualifiers())) 7330 return true; 7331 } 7332 7333 return false; 7334 } 7335 7336 /// C++11 [class.ctor] p5: 7337 /// A defaulted default constructor for a class X is defined as deleted if 7338 /// X is a union and all of its variant members are of const-qualified type. 7339 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 7340 // This is a silly definition, because it gives an empty union a deleted 7341 // default constructor. Don't do that. 7342 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 7343 bool AnyFields = false; 7344 for (auto *F : MD->getParent()->fields()) 7345 if ((AnyFields = !F->isUnnamedBitfield())) 7346 break; 7347 if (!AnyFields) 7348 return false; 7349 if (Diagnose) 7350 S.Diag(MD->getParent()->getLocation(), 7351 diag::note_deleted_default_ctor_all_const) 7352 << !!ICI << MD->getParent() << /*not anonymous union*/0; 7353 return true; 7354 } 7355 return false; 7356 } 7357 7358 /// Determine whether a defaulted special member function should be defined as 7359 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 7360 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 7361 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 7362 InheritedConstructorInfo *ICI, 7363 bool Diagnose) { 7364 if (MD->isInvalidDecl()) 7365 return false; 7366 CXXRecordDecl *RD = MD->getParent(); 7367 assert(!RD->isDependentType() && "do deletion after instantiation"); 7368 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 7369 return false; 7370 7371 // C++11 [expr.lambda.prim]p19: 7372 // The closure type associated with a lambda-expression has a 7373 // deleted (8.4.3) default constructor and a deleted copy 7374 // assignment operator. 7375 // C++2a adds back these operators if the lambda has no lambda-capture. 7376 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 7377 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 7378 if (Diagnose) 7379 Diag(RD->getLocation(), diag::note_lambda_decl); 7380 return true; 7381 } 7382 7383 // For an anonymous struct or union, the copy and assignment special members 7384 // will never be used, so skip the check. For an anonymous union declared at 7385 // namespace scope, the constructor and destructor are used. 7386 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 7387 RD->isAnonymousStructOrUnion()) 7388 return false; 7389 7390 // C++11 [class.copy]p7, p18: 7391 // If the class definition declares a move constructor or move assignment 7392 // operator, an implicitly declared copy constructor or copy assignment 7393 // operator is defined as deleted. 7394 if (MD->isImplicit() && 7395 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 7396 CXXMethodDecl *UserDeclaredMove = nullptr; 7397 7398 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 7399 // deletion of the corresponding copy operation, not both copy operations. 7400 // MSVC 2015 has adopted the standards conforming behavior. 7401 bool DeletesOnlyMatchingCopy = 7402 getLangOpts().MSVCCompat && 7403 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 7404 7405 if (RD->hasUserDeclaredMoveConstructor() && 7406 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 7407 if (!Diagnose) return true; 7408 7409 // Find any user-declared move constructor. 7410 for (auto *I : RD->ctors()) { 7411 if (I->isMoveConstructor()) { 7412 UserDeclaredMove = I; 7413 break; 7414 } 7415 } 7416 assert(UserDeclaredMove); 7417 } else if (RD->hasUserDeclaredMoveAssignment() && 7418 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 7419 if (!Diagnose) return true; 7420 7421 // Find any user-declared move assignment operator. 7422 for (auto *I : RD->methods()) { 7423 if (I->isMoveAssignmentOperator()) { 7424 UserDeclaredMove = I; 7425 break; 7426 } 7427 } 7428 assert(UserDeclaredMove); 7429 } 7430 7431 if (UserDeclaredMove) { 7432 Diag(UserDeclaredMove->getLocation(), 7433 diag::note_deleted_copy_user_declared_move) 7434 << (CSM == CXXCopyAssignment) << RD 7435 << UserDeclaredMove->isMoveAssignmentOperator(); 7436 return true; 7437 } 7438 } 7439 7440 // Do access control from the special member function 7441 ContextRAII MethodContext(*this, MD); 7442 7443 // C++11 [class.dtor]p5: 7444 // -- for a virtual destructor, lookup of the non-array deallocation function 7445 // results in an ambiguity or in a function that is deleted or inaccessible 7446 if (CSM == CXXDestructor && MD->isVirtual()) { 7447 FunctionDecl *OperatorDelete = nullptr; 7448 DeclarationName Name = 7449 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 7450 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 7451 OperatorDelete, /*Diagnose*/false)) { 7452 if (Diagnose) 7453 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 7454 return true; 7455 } 7456 } 7457 7458 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 7459 7460 // Per DR1611, do not consider virtual bases of constructors of abstract 7461 // classes, since we are not going to construct them. 7462 // Per DR1658, do not consider virtual bases of destructors of abstract 7463 // classes either. 7464 // Per DR2180, for assignment operators we only assign (and thus only 7465 // consider) direct bases. 7466 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 7467 : SMI.VisitPotentiallyConstructedBases)) 7468 return true; 7469 7470 if (SMI.shouldDeleteForAllConstMembers()) 7471 return true; 7472 7473 if (getLangOpts().CUDA) { 7474 // We should delete the special member in CUDA mode if target inference 7475 // failed. 7476 // For inherited constructors (non-null ICI), CSM may be passed so that MD 7477 // is treated as certain special member, which may not reflect what special 7478 // member MD really is. However inferCUDATargetForImplicitSpecialMember 7479 // expects CSM to match MD, therefore recalculate CSM. 7480 assert(ICI || CSM == getSpecialMember(MD)); 7481 auto RealCSM = CSM; 7482 if (ICI) 7483 RealCSM = getSpecialMember(MD); 7484 7485 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 7486 SMI.ConstArg, Diagnose); 7487 } 7488 7489 return false; 7490 } 7491 7492 /// Perform lookup for a special member of the specified kind, and determine 7493 /// whether it is trivial. If the triviality can be determined without the 7494 /// lookup, skip it. This is intended for use when determining whether a 7495 /// special member of a containing object is trivial, and thus does not ever 7496 /// perform overload resolution for default constructors. 7497 /// 7498 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 7499 /// member that was most likely to be intended to be trivial, if any. 7500 /// 7501 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 7502 /// determine whether the special member is trivial. 7503 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 7504 Sema::CXXSpecialMember CSM, unsigned Quals, 7505 bool ConstRHS, 7506 Sema::TrivialABIHandling TAH, 7507 CXXMethodDecl **Selected) { 7508 if (Selected) 7509 *Selected = nullptr; 7510 7511 switch (CSM) { 7512 case Sema::CXXInvalid: 7513 llvm_unreachable("not a special member"); 7514 7515 case Sema::CXXDefaultConstructor: 7516 // C++11 [class.ctor]p5: 7517 // A default constructor is trivial if: 7518 // - all the [direct subobjects] have trivial default constructors 7519 // 7520 // Note, no overload resolution is performed in this case. 7521 if (RD->hasTrivialDefaultConstructor()) 7522 return true; 7523 7524 if (Selected) { 7525 // If there's a default constructor which could have been trivial, dig it 7526 // out. Otherwise, if there's any user-provided default constructor, point 7527 // to that as an example of why there's not a trivial one. 7528 CXXConstructorDecl *DefCtor = nullptr; 7529 if (RD->needsImplicitDefaultConstructor()) 7530 S.DeclareImplicitDefaultConstructor(RD); 7531 for (auto *CI : RD->ctors()) { 7532 if (!CI->isDefaultConstructor()) 7533 continue; 7534 DefCtor = CI; 7535 if (!DefCtor->isUserProvided()) 7536 break; 7537 } 7538 7539 *Selected = DefCtor; 7540 } 7541 7542 return false; 7543 7544 case Sema::CXXDestructor: 7545 // C++11 [class.dtor]p5: 7546 // A destructor is trivial if: 7547 // - all the direct [subobjects] have trivial destructors 7548 if (RD->hasTrivialDestructor() || 7549 (TAH == Sema::TAH_ConsiderTrivialABI && 7550 RD->hasTrivialDestructorForCall())) 7551 return true; 7552 7553 if (Selected) { 7554 if (RD->needsImplicitDestructor()) 7555 S.DeclareImplicitDestructor(RD); 7556 *Selected = RD->getDestructor(); 7557 } 7558 7559 return false; 7560 7561 case Sema::CXXCopyConstructor: 7562 // C++11 [class.copy]p12: 7563 // A copy constructor is trivial if: 7564 // - the constructor selected to copy each direct [subobject] is trivial 7565 if (RD->hasTrivialCopyConstructor() || 7566 (TAH == Sema::TAH_ConsiderTrivialABI && 7567 RD->hasTrivialCopyConstructorForCall())) { 7568 if (Quals == Qualifiers::Const) 7569 // We must either select the trivial copy constructor or reach an 7570 // ambiguity; no need to actually perform overload resolution. 7571 return true; 7572 } else if (!Selected) { 7573 return false; 7574 } 7575 // In C++98, we are not supposed to perform overload resolution here, but we 7576 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 7577 // cases like B as having a non-trivial copy constructor: 7578 // struct A { template<typename T> A(T&); }; 7579 // struct B { mutable A a; }; 7580 goto NeedOverloadResolution; 7581 7582 case Sema::CXXCopyAssignment: 7583 // C++11 [class.copy]p25: 7584 // A copy assignment operator is trivial if: 7585 // - the assignment operator selected to copy each direct [subobject] is 7586 // trivial 7587 if (RD->hasTrivialCopyAssignment()) { 7588 if (Quals == Qualifiers::Const) 7589 return true; 7590 } else if (!Selected) { 7591 return false; 7592 } 7593 // In C++98, we are not supposed to perform overload resolution here, but we 7594 // treat that as a language defect. 7595 goto NeedOverloadResolution; 7596 7597 case Sema::CXXMoveConstructor: 7598 case Sema::CXXMoveAssignment: 7599 NeedOverloadResolution: 7600 Sema::SpecialMemberOverloadResult SMOR = 7601 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 7602 7603 // The standard doesn't describe how to behave if the lookup is ambiguous. 7604 // We treat it as not making the member non-trivial, just like the standard 7605 // mandates for the default constructor. This should rarely matter, because 7606 // the member will also be deleted. 7607 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7608 return true; 7609 7610 if (!SMOR.getMethod()) { 7611 assert(SMOR.getKind() == 7612 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 7613 return false; 7614 } 7615 7616 // We deliberately don't check if we found a deleted special member. We're 7617 // not supposed to! 7618 if (Selected) 7619 *Selected = SMOR.getMethod(); 7620 7621 if (TAH == Sema::TAH_ConsiderTrivialABI && 7622 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 7623 return SMOR.getMethod()->isTrivialForCall(); 7624 return SMOR.getMethod()->isTrivial(); 7625 } 7626 7627 llvm_unreachable("unknown special method kind"); 7628 } 7629 7630 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 7631 for (auto *CI : RD->ctors()) 7632 if (!CI->isImplicit()) 7633 return CI; 7634 7635 // Look for constructor templates. 7636 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 7637 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 7638 if (CXXConstructorDecl *CD = 7639 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 7640 return CD; 7641 } 7642 7643 return nullptr; 7644 } 7645 7646 /// The kind of subobject we are checking for triviality. The values of this 7647 /// enumeration are used in diagnostics. 7648 enum TrivialSubobjectKind { 7649 /// The subobject is a base class. 7650 TSK_BaseClass, 7651 /// The subobject is a non-static data member. 7652 TSK_Field, 7653 /// The object is actually the complete object. 7654 TSK_CompleteObject 7655 }; 7656 7657 /// Check whether the special member selected for a given type would be trivial. 7658 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 7659 QualType SubType, bool ConstRHS, 7660 Sema::CXXSpecialMember CSM, 7661 TrivialSubobjectKind Kind, 7662 Sema::TrivialABIHandling TAH, bool Diagnose) { 7663 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 7664 if (!SubRD) 7665 return true; 7666 7667 CXXMethodDecl *Selected; 7668 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 7669 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 7670 return true; 7671 7672 if (Diagnose) { 7673 if (ConstRHS) 7674 SubType.addConst(); 7675 7676 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 7677 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 7678 << Kind << SubType.getUnqualifiedType(); 7679 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 7680 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 7681 } else if (!Selected) 7682 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 7683 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 7684 else if (Selected->isUserProvided()) { 7685 if (Kind == TSK_CompleteObject) 7686 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 7687 << Kind << SubType.getUnqualifiedType() << CSM; 7688 else { 7689 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 7690 << Kind << SubType.getUnqualifiedType() << CSM; 7691 S.Diag(Selected->getLocation(), diag::note_declared_at); 7692 } 7693 } else { 7694 if (Kind != TSK_CompleteObject) 7695 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 7696 << Kind << SubType.getUnqualifiedType() << CSM; 7697 7698 // Explain why the defaulted or deleted special member isn't trivial. 7699 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 7700 Diagnose); 7701 } 7702 } 7703 7704 return false; 7705 } 7706 7707 /// Check whether the members of a class type allow a special member to be 7708 /// trivial. 7709 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7710 Sema::CXXSpecialMember CSM, 7711 bool ConstArg, 7712 Sema::TrivialABIHandling TAH, 7713 bool Diagnose) { 7714 for (const auto *FI : RD->fields()) { 7715 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7716 continue; 7717 7718 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7719 7720 // Pretend anonymous struct or union members are members of this class. 7721 if (FI->isAnonymousStructOrUnion()) { 7722 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7723 CSM, ConstArg, TAH, Diagnose)) 7724 return false; 7725 continue; 7726 } 7727 7728 // C++11 [class.ctor]p5: 7729 // A default constructor is trivial if [...] 7730 // -- no non-static data member of its class has a 7731 // brace-or-equal-initializer 7732 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7733 if (Diagnose) 7734 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7735 return false; 7736 } 7737 7738 // Objective C ARC 4.3.5: 7739 // [...] nontrivally ownership-qualified types are [...] not trivially 7740 // default constructible, copy constructible, move constructible, copy 7741 // assignable, move assignable, or destructible [...] 7742 if (FieldType.hasNonTrivialObjCLifetime()) { 7743 if (Diagnose) 7744 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7745 << RD << FieldType.getObjCLifetime(); 7746 return false; 7747 } 7748 7749 bool ConstRHS = ConstArg && !FI->isMutable(); 7750 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7751 CSM, TSK_Field, TAH, Diagnose)) 7752 return false; 7753 } 7754 7755 return true; 7756 } 7757 7758 /// Diagnose why the specified class does not have a trivial special member of 7759 /// the given kind. 7760 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7761 QualType Ty = Context.getRecordType(RD); 7762 7763 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7764 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7765 TSK_CompleteObject, TAH_IgnoreTrivialABI, 7766 /*Diagnose*/true); 7767 } 7768 7769 /// Determine whether a defaulted or deleted special member function is trivial, 7770 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7771 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7772 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7773 TrivialABIHandling TAH, bool Diagnose) { 7774 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7775 7776 CXXRecordDecl *RD = MD->getParent(); 7777 7778 bool ConstArg = false; 7779 7780 // C++11 [class.copy]p12, p25: [DR1593] 7781 // A [special member] is trivial if [...] its parameter-type-list is 7782 // equivalent to the parameter-type-list of an implicit declaration [...] 7783 switch (CSM) { 7784 case CXXDefaultConstructor: 7785 case CXXDestructor: 7786 // Trivial default constructors and destructors cannot have parameters. 7787 break; 7788 7789 case CXXCopyConstructor: 7790 case CXXCopyAssignment: { 7791 // Trivial copy operations always have const, non-volatile parameter types. 7792 ConstArg = true; 7793 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7794 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7795 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7796 if (Diagnose) 7797 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7798 << Param0->getSourceRange() << Param0->getType() 7799 << Context.getLValueReferenceType( 7800 Context.getRecordType(RD).withConst()); 7801 return false; 7802 } 7803 break; 7804 } 7805 7806 case CXXMoveConstructor: 7807 case CXXMoveAssignment: { 7808 // Trivial move operations always have non-cv-qualified parameters. 7809 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7810 const RValueReferenceType *RT = 7811 Param0->getType()->getAs<RValueReferenceType>(); 7812 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7813 if (Diagnose) 7814 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7815 << Param0->getSourceRange() << Param0->getType() 7816 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7817 return false; 7818 } 7819 break; 7820 } 7821 7822 case CXXInvalid: 7823 llvm_unreachable("not a special member"); 7824 } 7825 7826 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7827 if (Diagnose) 7828 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7829 diag::note_nontrivial_default_arg) 7830 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7831 return false; 7832 } 7833 if (MD->isVariadic()) { 7834 if (Diagnose) 7835 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7836 return false; 7837 } 7838 7839 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7840 // A copy/move [constructor or assignment operator] is trivial if 7841 // -- the [member] selected to copy/move each direct base class subobject 7842 // is trivial 7843 // 7844 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7845 // A [default constructor or destructor] is trivial if 7846 // -- all the direct base classes have trivial [default constructors or 7847 // destructors] 7848 for (const auto &BI : RD->bases()) 7849 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 7850 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 7851 return false; 7852 7853 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7854 // A copy/move [constructor or assignment operator] for a class X is 7855 // trivial if 7856 // -- for each non-static data member of X that is of class type (or array 7857 // thereof), the constructor selected to copy/move that member is 7858 // trivial 7859 // 7860 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7861 // A [default constructor or destructor] is trivial if 7862 // -- for all of the non-static data members of its class that are of class 7863 // type (or array thereof), each such class has a trivial [default 7864 // constructor or destructor] 7865 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 7866 return false; 7867 7868 // C++11 [class.dtor]p5: 7869 // A destructor is trivial if [...] 7870 // -- the destructor is not virtual 7871 if (CSM == CXXDestructor && MD->isVirtual()) { 7872 if (Diagnose) 7873 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7874 return false; 7875 } 7876 7877 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7878 // A [special member] for class X is trivial if [...] 7879 // -- class X has no virtual functions and no virtual base classes 7880 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7881 if (!Diagnose) 7882 return false; 7883 7884 if (RD->getNumVBases()) { 7885 // Check for virtual bases. We already know that the corresponding 7886 // member in all bases is trivial, so vbases must all be direct. 7887 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7888 assert(BS.isVirtual()); 7889 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 7890 return false; 7891 } 7892 7893 // Must have a virtual method. 7894 for (const auto *MI : RD->methods()) { 7895 if (MI->isVirtual()) { 7896 SourceLocation MLoc = MI->getBeginLoc(); 7897 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7898 return false; 7899 } 7900 } 7901 7902 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7903 } 7904 7905 // Looks like it's trivial! 7906 return true; 7907 } 7908 7909 namespace { 7910 struct FindHiddenVirtualMethod { 7911 Sema *S; 7912 CXXMethodDecl *Method; 7913 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7914 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7915 7916 private: 7917 /// Check whether any most overridden method from MD in Methods 7918 static bool CheckMostOverridenMethods( 7919 const CXXMethodDecl *MD, 7920 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7921 if (MD->size_overridden_methods() == 0) 7922 return Methods.count(MD->getCanonicalDecl()); 7923 for (const CXXMethodDecl *O : MD->overridden_methods()) 7924 if (CheckMostOverridenMethods(O, Methods)) 7925 return true; 7926 return false; 7927 } 7928 7929 public: 7930 /// Member lookup function that determines whether a given C++ 7931 /// method overloads virtual methods in a base class without overriding any, 7932 /// to be used with CXXRecordDecl::lookupInBases(). 7933 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7934 RecordDecl *BaseRecord = 7935 Specifier->getType()->getAs<RecordType>()->getDecl(); 7936 7937 DeclarationName Name = Method->getDeclName(); 7938 assert(Name.getNameKind() == DeclarationName::Identifier); 7939 7940 bool foundSameNameMethod = false; 7941 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7942 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7943 Path.Decls = Path.Decls.slice(1)) { 7944 NamedDecl *D = Path.Decls.front(); 7945 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7946 MD = MD->getCanonicalDecl(); 7947 foundSameNameMethod = true; 7948 // Interested only in hidden virtual methods. 7949 if (!MD->isVirtual()) 7950 continue; 7951 // If the method we are checking overrides a method from its base 7952 // don't warn about the other overloaded methods. Clang deviates from 7953 // GCC by only diagnosing overloads of inherited virtual functions that 7954 // do not override any other virtual functions in the base. GCC's 7955 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7956 // function from a base class. These cases may be better served by a 7957 // warning (not specific to virtual functions) on call sites when the 7958 // call would select a different function from the base class, were it 7959 // visible. 7960 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7961 if (!S->IsOverload(Method, MD, false)) 7962 return true; 7963 // Collect the overload only if its hidden. 7964 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7965 overloadedMethods.push_back(MD); 7966 } 7967 } 7968 7969 if (foundSameNameMethod) 7970 OverloadedMethods.append(overloadedMethods.begin(), 7971 overloadedMethods.end()); 7972 return foundSameNameMethod; 7973 } 7974 }; 7975 } // end anonymous namespace 7976 7977 /// Add the most overriden methods from MD to Methods 7978 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7979 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7980 if (MD->size_overridden_methods() == 0) 7981 Methods.insert(MD->getCanonicalDecl()); 7982 else 7983 for (const CXXMethodDecl *O : MD->overridden_methods()) 7984 AddMostOverridenMethods(O, Methods); 7985 } 7986 7987 /// Check if a method overloads virtual methods in a base class without 7988 /// overriding any. 7989 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7990 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7991 if (!MD->getDeclName().isIdentifier()) 7992 return; 7993 7994 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7995 /*bool RecordPaths=*/false, 7996 /*bool DetectVirtual=*/false); 7997 FindHiddenVirtualMethod FHVM; 7998 FHVM.Method = MD; 7999 FHVM.S = this; 8000 8001 // Keep the base methods that were overridden or introduced in the subclass 8002 // by 'using' in a set. A base method not in this set is hidden. 8003 CXXRecordDecl *DC = MD->getParent(); 8004 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 8005 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 8006 NamedDecl *ND = *I; 8007 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 8008 ND = shad->getTargetDecl(); 8009 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 8010 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 8011 } 8012 8013 if (DC->lookupInBases(FHVM, Paths)) 8014 OverloadedMethods = FHVM.OverloadedMethods; 8015 } 8016 8017 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 8018 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 8019 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 8020 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 8021 PartialDiagnostic PD = PDiag( 8022 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 8023 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 8024 Diag(overloadedMD->getLocation(), PD); 8025 } 8026 } 8027 8028 /// Diagnose methods which overload virtual methods in a base class 8029 /// without overriding any. 8030 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 8031 if (MD->isInvalidDecl()) 8032 return; 8033 8034 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 8035 return; 8036 8037 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 8038 FindHiddenVirtualMethods(MD, OverloadedMethods); 8039 if (!OverloadedMethods.empty()) { 8040 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 8041 << MD << (OverloadedMethods.size() > 1); 8042 8043 NoteHiddenVirtualMethods(MD, OverloadedMethods); 8044 } 8045 } 8046 8047 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 8048 auto PrintDiagAndRemoveAttr = [&]() { 8049 // No diagnostics if this is a template instantiation. 8050 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) 8051 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 8052 diag::ext_cannot_use_trivial_abi) << &RD; 8053 RD.dropAttr<TrivialABIAttr>(); 8054 }; 8055 8056 // Ill-formed if the struct has virtual functions. 8057 if (RD.isPolymorphic()) { 8058 PrintDiagAndRemoveAttr(); 8059 return; 8060 } 8061 8062 for (const auto &B : RD.bases()) { 8063 // Ill-formed if the base class is non-trivial for the purpose of calls or a 8064 // virtual base. 8065 if ((!B.getType()->isDependentType() && 8066 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) || 8067 B.isVirtual()) { 8068 PrintDiagAndRemoveAttr(); 8069 return; 8070 } 8071 } 8072 8073 for (const auto *FD : RD.fields()) { 8074 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 8075 // non-trivial for the purpose of calls. 8076 QualType FT = FD->getType(); 8077 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 8078 PrintDiagAndRemoveAttr(); 8079 return; 8080 } 8081 8082 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 8083 if (!RT->isDependentType() && 8084 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 8085 PrintDiagAndRemoveAttr(); 8086 return; 8087 } 8088 } 8089 } 8090 8091 void Sema::ActOnFinishCXXMemberSpecification( 8092 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 8093 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 8094 if (!TagDecl) 8095 return; 8096 8097 AdjustDeclIfTemplate(TagDecl); 8098 8099 for (const ParsedAttr &AL : AttrList) { 8100 if (AL.getKind() != ParsedAttr::AT_Visibility) 8101 continue; 8102 AL.setInvalid(); 8103 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 8104 } 8105 8106 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 8107 // strict aliasing violation! 8108 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 8109 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 8110 8111 CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl)); 8112 } 8113 8114 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 8115 /// special functions, such as the default constructor, copy 8116 /// constructor, or destructor, to the given C++ class (C++ 8117 /// [special]p1). This routine can only be executed just before the 8118 /// definition of the class is complete. 8119 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 8120 if (ClassDecl->needsImplicitDefaultConstructor()) { 8121 ++getASTContext().NumImplicitDefaultConstructors; 8122 8123 if (ClassDecl->hasInheritedConstructor()) 8124 DeclareImplicitDefaultConstructor(ClassDecl); 8125 } 8126 8127 if (ClassDecl->needsImplicitCopyConstructor()) { 8128 ++getASTContext().NumImplicitCopyConstructors; 8129 8130 // If the properties or semantics of the copy constructor couldn't be 8131 // determined while the class was being declared, force a declaration 8132 // of it now. 8133 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 8134 ClassDecl->hasInheritedConstructor()) 8135 DeclareImplicitCopyConstructor(ClassDecl); 8136 // For the MS ABI we need to know whether the copy ctor is deleted. A 8137 // prerequisite for deleting the implicit copy ctor is that the class has a 8138 // move ctor or move assignment that is either user-declared or whose 8139 // semantics are inherited from a subobject. FIXME: We should provide a more 8140 // direct way for CodeGen to ask whether the constructor was deleted. 8141 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 8142 (ClassDecl->hasUserDeclaredMoveConstructor() || 8143 ClassDecl->needsOverloadResolutionForMoveConstructor() || 8144 ClassDecl->hasUserDeclaredMoveAssignment() || 8145 ClassDecl->needsOverloadResolutionForMoveAssignment())) 8146 DeclareImplicitCopyConstructor(ClassDecl); 8147 } 8148 8149 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 8150 ++getASTContext().NumImplicitMoveConstructors; 8151 8152 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 8153 ClassDecl->hasInheritedConstructor()) 8154 DeclareImplicitMoveConstructor(ClassDecl); 8155 } 8156 8157 if (ClassDecl->needsImplicitCopyAssignment()) { 8158 ++getASTContext().NumImplicitCopyAssignmentOperators; 8159 8160 // If we have a dynamic class, then the copy assignment operator may be 8161 // virtual, so we have to declare it immediately. This ensures that, e.g., 8162 // it shows up in the right place in the vtable and that we diagnose 8163 // problems with the implicit exception specification. 8164 if (ClassDecl->isDynamicClass() || 8165 ClassDecl->needsOverloadResolutionForCopyAssignment() || 8166 ClassDecl->hasInheritedAssignment()) 8167 DeclareImplicitCopyAssignment(ClassDecl); 8168 } 8169 8170 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 8171 ++getASTContext().NumImplicitMoveAssignmentOperators; 8172 8173 // Likewise for the move assignment operator. 8174 if (ClassDecl->isDynamicClass() || 8175 ClassDecl->needsOverloadResolutionForMoveAssignment() || 8176 ClassDecl->hasInheritedAssignment()) 8177 DeclareImplicitMoveAssignment(ClassDecl); 8178 } 8179 8180 if (ClassDecl->needsImplicitDestructor()) { 8181 ++getASTContext().NumImplicitDestructors; 8182 8183 // If we have a dynamic class, then the destructor may be virtual, so we 8184 // have to declare the destructor immediately. This ensures that, e.g., it 8185 // shows up in the right place in the vtable and that we diagnose problems 8186 // with the implicit exception specification. 8187 if (ClassDecl->isDynamicClass() || 8188 ClassDecl->needsOverloadResolutionForDestructor()) 8189 DeclareImplicitDestructor(ClassDecl); 8190 } 8191 } 8192 8193 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 8194 if (!D) 8195 return 0; 8196 8197 // The order of template parameters is not important here. All names 8198 // get added to the same scope. 8199 SmallVector<TemplateParameterList *, 4> ParameterLists; 8200 8201 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 8202 D = TD->getTemplatedDecl(); 8203 8204 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 8205 ParameterLists.push_back(PSD->getTemplateParameters()); 8206 8207 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 8208 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 8209 ParameterLists.push_back(DD->getTemplateParameterList(i)); 8210 8211 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 8212 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 8213 ParameterLists.push_back(FTD->getTemplateParameters()); 8214 } 8215 } 8216 8217 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 8218 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 8219 ParameterLists.push_back(TD->getTemplateParameterList(i)); 8220 8221 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 8222 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 8223 ParameterLists.push_back(CTD->getTemplateParameters()); 8224 } 8225 } 8226 8227 unsigned Count = 0; 8228 for (TemplateParameterList *Params : ParameterLists) { 8229 if (Params->size() > 0) 8230 // Ignore explicit specializations; they don't contribute to the template 8231 // depth. 8232 ++Count; 8233 for (NamedDecl *Param : *Params) { 8234 if (Param->getDeclName()) { 8235 S->AddDecl(Param); 8236 IdResolver.AddDecl(Param); 8237 } 8238 } 8239 } 8240 8241 return Count; 8242 } 8243 8244 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 8245 if (!RecordD) return; 8246 AdjustDeclIfTemplate(RecordD); 8247 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 8248 PushDeclContext(S, Record); 8249 } 8250 8251 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 8252 if (!RecordD) return; 8253 PopDeclContext(); 8254 } 8255 8256 /// This is used to implement the constant expression evaluation part of the 8257 /// attribute enable_if extension. There is nothing in standard C++ which would 8258 /// require reentering parameters. 8259 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 8260 if (!Param) 8261 return; 8262 8263 S->AddDecl(Param); 8264 if (Param->getDeclName()) 8265 IdResolver.AddDecl(Param); 8266 } 8267 8268 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 8269 /// parsing a top-level (non-nested) C++ class, and we are now 8270 /// parsing those parts of the given Method declaration that could 8271 /// not be parsed earlier (C++ [class.mem]p2), such as default 8272 /// arguments. This action should enter the scope of the given 8273 /// Method declaration as if we had just parsed the qualified method 8274 /// name. However, it should not bring the parameters into scope; 8275 /// that will be performed by ActOnDelayedCXXMethodParameter. 8276 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 8277 } 8278 8279 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 8280 /// C++ method declaration. We're (re-)introducing the given 8281 /// function parameter into scope for use in parsing later parts of 8282 /// the method declaration. For example, we could see an 8283 /// ActOnParamDefaultArgument event for this parameter. 8284 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 8285 if (!ParamD) 8286 return; 8287 8288 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 8289 8290 // If this parameter has an unparsed default argument, clear it out 8291 // to make way for the parsed default argument. 8292 if (Param->hasUnparsedDefaultArg()) 8293 Param->setDefaultArg(nullptr); 8294 8295 S->AddDecl(Param); 8296 if (Param->getDeclName()) 8297 IdResolver.AddDecl(Param); 8298 } 8299 8300 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 8301 /// processing the delayed method declaration for Method. The method 8302 /// declaration is now considered finished. There may be a separate 8303 /// ActOnStartOfFunctionDef action later (not necessarily 8304 /// immediately!) for this method, if it was also defined inside the 8305 /// class body. 8306 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 8307 if (!MethodD) 8308 return; 8309 8310 AdjustDeclIfTemplate(MethodD); 8311 8312 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 8313 8314 // Now that we have our default arguments, check the constructor 8315 // again. It could produce additional diagnostics or affect whether 8316 // the class has implicitly-declared destructors, among other 8317 // things. 8318 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 8319 CheckConstructor(Constructor); 8320 8321 // Check the default arguments, which we may have added. 8322 if (!Method->isInvalidDecl()) 8323 CheckCXXDefaultArguments(Method); 8324 } 8325 8326 // Emit the given diagnostic for each non-address-space qualifier. 8327 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 8328 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 8329 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8330 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 8331 bool DiagOccured = false; 8332 FTI.MethodQualifiers->forEachQualifier( 8333 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 8334 SourceLocation SL) { 8335 // This diagnostic should be emitted on any qualifier except an addr 8336 // space qualifier. However, forEachQualifier currently doesn't visit 8337 // addr space qualifiers, so there's no way to write this condition 8338 // right now; we just diagnose on everything. 8339 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 8340 DiagOccured = true; 8341 }); 8342 if (DiagOccured) 8343 D.setInvalidType(); 8344 } 8345 } 8346 8347 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 8348 /// the well-formedness of the constructor declarator @p D with type @p 8349 /// R. If there are any errors in the declarator, this routine will 8350 /// emit diagnostics and set the invalid bit to true. In any case, the type 8351 /// will be updated to reflect a well-formed type for the constructor and 8352 /// returned. 8353 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 8354 StorageClass &SC) { 8355 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8356 8357 // C++ [class.ctor]p3: 8358 // A constructor shall not be virtual (10.3) or static (9.4). A 8359 // constructor can be invoked for a const, volatile or const 8360 // volatile object. A constructor shall not be declared const, 8361 // volatile, or const volatile (9.3.2). 8362 if (isVirtual) { 8363 if (!D.isInvalidType()) 8364 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8365 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 8366 << SourceRange(D.getIdentifierLoc()); 8367 D.setInvalidType(); 8368 } 8369 if (SC == SC_Static) { 8370 if (!D.isInvalidType()) 8371 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8372 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8373 << SourceRange(D.getIdentifierLoc()); 8374 D.setInvalidType(); 8375 SC = SC_None; 8376 } 8377 8378 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8379 diagnoseIgnoredQualifiers( 8380 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 8381 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 8382 D.getDeclSpec().getRestrictSpecLoc(), 8383 D.getDeclSpec().getAtomicSpecLoc()); 8384 D.setInvalidType(); 8385 } 8386 8387 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 8388 8389 // C++0x [class.ctor]p4: 8390 // A constructor shall not be declared with a ref-qualifier. 8391 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8392 if (FTI.hasRefQualifier()) { 8393 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 8394 << FTI.RefQualifierIsLValueRef 8395 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8396 D.setInvalidType(); 8397 } 8398 8399 // Rebuild the function type "R" without any type qualifiers (in 8400 // case any of the errors above fired) and with "void" as the 8401 // return type, since constructors don't have return types. 8402 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8403 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 8404 return R; 8405 8406 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8407 EPI.TypeQuals = Qualifiers(); 8408 EPI.RefQualifier = RQ_None; 8409 8410 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 8411 } 8412 8413 /// CheckConstructor - Checks a fully-formed constructor for 8414 /// well-formedness, issuing any diagnostics required. Returns true if 8415 /// the constructor declarator is invalid. 8416 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 8417 CXXRecordDecl *ClassDecl 8418 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 8419 if (!ClassDecl) 8420 return Constructor->setInvalidDecl(); 8421 8422 // C++ [class.copy]p3: 8423 // A declaration of a constructor for a class X is ill-formed if 8424 // its first parameter is of type (optionally cv-qualified) X and 8425 // either there are no other parameters or else all other 8426 // parameters have default arguments. 8427 if (!Constructor->isInvalidDecl() && 8428 ((Constructor->getNumParams() == 1) || 8429 (Constructor->getNumParams() > 1 && 8430 Constructor->getParamDecl(1)->hasDefaultArg())) && 8431 Constructor->getTemplateSpecializationKind() 8432 != TSK_ImplicitInstantiation) { 8433 QualType ParamType = Constructor->getParamDecl(0)->getType(); 8434 QualType ClassTy = Context.getTagDeclType(ClassDecl); 8435 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 8436 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 8437 const char *ConstRef 8438 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 8439 : " const &"; 8440 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 8441 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 8442 8443 // FIXME: Rather that making the constructor invalid, we should endeavor 8444 // to fix the type. 8445 Constructor->setInvalidDecl(); 8446 } 8447 } 8448 } 8449 8450 /// CheckDestructor - Checks a fully-formed destructor definition for 8451 /// well-formedness, issuing any diagnostics required. Returns true 8452 /// on error. 8453 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 8454 CXXRecordDecl *RD = Destructor->getParent(); 8455 8456 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 8457 SourceLocation Loc; 8458 8459 if (!Destructor->isImplicit()) 8460 Loc = Destructor->getLocation(); 8461 else 8462 Loc = RD->getLocation(); 8463 8464 // If we have a virtual destructor, look up the deallocation function 8465 if (FunctionDecl *OperatorDelete = 8466 FindDeallocationFunctionForDestructor(Loc, RD)) { 8467 Expr *ThisArg = nullptr; 8468 8469 // If the notional 'delete this' expression requires a non-trivial 8470 // conversion from 'this' to the type of a destroying operator delete's 8471 // first parameter, perform that conversion now. 8472 if (OperatorDelete->isDestroyingOperatorDelete()) { 8473 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 8474 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 8475 // C++ [class.dtor]p13: 8476 // ... as if for the expression 'delete this' appearing in a 8477 // non-virtual destructor of the destructor's class. 8478 ContextRAII SwitchContext(*this, Destructor); 8479 ExprResult This = 8480 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 8481 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 8482 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 8483 if (This.isInvalid()) { 8484 // FIXME: Register this as a context note so that it comes out 8485 // in the right order. 8486 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 8487 return true; 8488 } 8489 ThisArg = This.get(); 8490 } 8491 } 8492 8493 DiagnoseUseOfDecl(OperatorDelete, Loc); 8494 MarkFunctionReferenced(Loc, OperatorDelete); 8495 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 8496 } 8497 } 8498 8499 return false; 8500 } 8501 8502 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 8503 /// the well-formednes of the destructor declarator @p D with type @p 8504 /// R. If there are any errors in the declarator, this routine will 8505 /// emit diagnostics and set the declarator to invalid. Even if this happens, 8506 /// will be updated to reflect a well-formed type for the destructor and 8507 /// returned. 8508 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 8509 StorageClass& SC) { 8510 // C++ [class.dtor]p1: 8511 // [...] A typedef-name that names a class is a class-name 8512 // (7.1.3); however, a typedef-name that names a class shall not 8513 // be used as the identifier in the declarator for a destructor 8514 // declaration. 8515 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 8516 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 8517 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8518 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 8519 else if (const TemplateSpecializationType *TST = 8520 DeclaratorType->getAs<TemplateSpecializationType>()) 8521 if (TST->isTypeAlias()) 8522 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8523 << DeclaratorType << 1; 8524 8525 // C++ [class.dtor]p2: 8526 // A destructor is used to destroy objects of its class type. A 8527 // destructor takes no parameters, and no return type can be 8528 // specified for it (not even void). The address of a destructor 8529 // shall not be taken. A destructor shall not be static. A 8530 // destructor can be invoked for a const, volatile or const 8531 // volatile object. A destructor shall not be declared const, 8532 // volatile or const volatile (9.3.2). 8533 if (SC == SC_Static) { 8534 if (!D.isInvalidType()) 8535 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 8536 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8537 << SourceRange(D.getIdentifierLoc()) 8538 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8539 8540 SC = SC_None; 8541 } 8542 if (!D.isInvalidType()) { 8543 // Destructors don't have return types, but the parser will 8544 // happily parse something like: 8545 // 8546 // class X { 8547 // float ~X(); 8548 // }; 8549 // 8550 // The return type will be eliminated later. 8551 if (D.getDeclSpec().hasTypeSpecifier()) 8552 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 8553 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8554 << SourceRange(D.getIdentifierLoc()); 8555 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8556 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 8557 SourceLocation(), 8558 D.getDeclSpec().getConstSpecLoc(), 8559 D.getDeclSpec().getVolatileSpecLoc(), 8560 D.getDeclSpec().getRestrictSpecLoc(), 8561 D.getDeclSpec().getAtomicSpecLoc()); 8562 D.setInvalidType(); 8563 } 8564 } 8565 8566 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 8567 8568 // C++0x [class.dtor]p2: 8569 // A destructor shall not be declared with a ref-qualifier. 8570 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8571 if (FTI.hasRefQualifier()) { 8572 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 8573 << FTI.RefQualifierIsLValueRef 8574 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8575 D.setInvalidType(); 8576 } 8577 8578 // Make sure we don't have any parameters. 8579 if (FTIHasNonVoidParameters(FTI)) { 8580 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 8581 8582 // Delete the parameters. 8583 FTI.freeParams(); 8584 D.setInvalidType(); 8585 } 8586 8587 // Make sure the destructor isn't variadic. 8588 if (FTI.isVariadic) { 8589 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 8590 D.setInvalidType(); 8591 } 8592 8593 // Rebuild the function type "R" without any type qualifiers or 8594 // parameters (in case any of the errors above fired) and with 8595 // "void" as the return type, since destructors don't have return 8596 // types. 8597 if (!D.isInvalidType()) 8598 return R; 8599 8600 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8601 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8602 EPI.Variadic = false; 8603 EPI.TypeQuals = Qualifiers(); 8604 EPI.RefQualifier = RQ_None; 8605 return Context.getFunctionType(Context.VoidTy, None, EPI); 8606 } 8607 8608 static void extendLeft(SourceRange &R, SourceRange Before) { 8609 if (Before.isInvalid()) 8610 return; 8611 R.setBegin(Before.getBegin()); 8612 if (R.getEnd().isInvalid()) 8613 R.setEnd(Before.getEnd()); 8614 } 8615 8616 static void extendRight(SourceRange &R, SourceRange After) { 8617 if (After.isInvalid()) 8618 return; 8619 if (R.getBegin().isInvalid()) 8620 R.setBegin(After.getBegin()); 8621 R.setEnd(After.getEnd()); 8622 } 8623 8624 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 8625 /// well-formednes of the conversion function declarator @p D with 8626 /// type @p R. If there are any errors in the declarator, this routine 8627 /// will emit diagnostics and return true. Otherwise, it will return 8628 /// false. Either way, the type @p R will be updated to reflect a 8629 /// well-formed type for the conversion operator. 8630 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 8631 StorageClass& SC) { 8632 // C++ [class.conv.fct]p1: 8633 // Neither parameter types nor return type can be specified. The 8634 // type of a conversion function (8.3.5) is "function taking no 8635 // parameter returning conversion-type-id." 8636 if (SC == SC_Static) { 8637 if (!D.isInvalidType()) 8638 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 8639 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8640 << D.getName().getSourceRange(); 8641 D.setInvalidType(); 8642 SC = SC_None; 8643 } 8644 8645 TypeSourceInfo *ConvTSI = nullptr; 8646 QualType ConvType = 8647 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 8648 8649 const DeclSpec &DS = D.getDeclSpec(); 8650 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 8651 // Conversion functions don't have return types, but the parser will 8652 // happily parse something like: 8653 // 8654 // class X { 8655 // float operator bool(); 8656 // }; 8657 // 8658 // The return type will be changed later anyway. 8659 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 8660 << SourceRange(DS.getTypeSpecTypeLoc()) 8661 << SourceRange(D.getIdentifierLoc()); 8662 D.setInvalidType(); 8663 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 8664 // It's also plausible that the user writes type qualifiers in the wrong 8665 // place, such as: 8666 // struct S { const operator int(); }; 8667 // FIXME: we could provide a fixit to move the qualifiers onto the 8668 // conversion type. 8669 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 8670 << SourceRange(D.getIdentifierLoc()) << 0; 8671 D.setInvalidType(); 8672 } 8673 8674 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8675 8676 // Make sure we don't have any parameters. 8677 if (Proto->getNumParams() > 0) { 8678 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 8679 8680 // Delete the parameters. 8681 D.getFunctionTypeInfo().freeParams(); 8682 D.setInvalidType(); 8683 } else if (Proto->isVariadic()) { 8684 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 8685 D.setInvalidType(); 8686 } 8687 8688 // Diagnose "&operator bool()" and other such nonsense. This 8689 // is actually a gcc extension which we don't support. 8690 if (Proto->getReturnType() != ConvType) { 8691 bool NeedsTypedef = false; 8692 SourceRange Before, After; 8693 8694 // Walk the chunks and extract information on them for our diagnostic. 8695 bool PastFunctionChunk = false; 8696 for (auto &Chunk : D.type_objects()) { 8697 switch (Chunk.Kind) { 8698 case DeclaratorChunk::Function: 8699 if (!PastFunctionChunk) { 8700 if (Chunk.Fun.HasTrailingReturnType) { 8701 TypeSourceInfo *TRT = nullptr; 8702 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 8703 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 8704 } 8705 PastFunctionChunk = true; 8706 break; 8707 } 8708 LLVM_FALLTHROUGH; 8709 case DeclaratorChunk::Array: 8710 NeedsTypedef = true; 8711 extendRight(After, Chunk.getSourceRange()); 8712 break; 8713 8714 case DeclaratorChunk::Pointer: 8715 case DeclaratorChunk::BlockPointer: 8716 case DeclaratorChunk::Reference: 8717 case DeclaratorChunk::MemberPointer: 8718 case DeclaratorChunk::Pipe: 8719 extendLeft(Before, Chunk.getSourceRange()); 8720 break; 8721 8722 case DeclaratorChunk::Paren: 8723 extendLeft(Before, Chunk.Loc); 8724 extendRight(After, Chunk.EndLoc); 8725 break; 8726 } 8727 } 8728 8729 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 8730 After.isValid() ? After.getBegin() : 8731 D.getIdentifierLoc(); 8732 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 8733 DB << Before << After; 8734 8735 if (!NeedsTypedef) { 8736 DB << /*don't need a typedef*/0; 8737 8738 // If we can provide a correct fix-it hint, do so. 8739 if (After.isInvalid() && ConvTSI) { 8740 SourceLocation InsertLoc = 8741 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 8742 DB << FixItHint::CreateInsertion(InsertLoc, " ") 8743 << FixItHint::CreateInsertionFromRange( 8744 InsertLoc, CharSourceRange::getTokenRange(Before)) 8745 << FixItHint::CreateRemoval(Before); 8746 } 8747 } else if (!Proto->getReturnType()->isDependentType()) { 8748 DB << /*typedef*/1 << Proto->getReturnType(); 8749 } else if (getLangOpts().CPlusPlus11) { 8750 DB << /*alias template*/2 << Proto->getReturnType(); 8751 } else { 8752 DB << /*might not be fixable*/3; 8753 } 8754 8755 // Recover by incorporating the other type chunks into the result type. 8756 // Note, this does *not* change the name of the function. This is compatible 8757 // with the GCC extension: 8758 // struct S { &operator int(); } s; 8759 // int &r = s.operator int(); // ok in GCC 8760 // S::operator int&() {} // error in GCC, function name is 'operator int'. 8761 ConvType = Proto->getReturnType(); 8762 } 8763 8764 // C++ [class.conv.fct]p4: 8765 // The conversion-type-id shall not represent a function type nor 8766 // an array type. 8767 if (ConvType->isArrayType()) { 8768 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 8769 ConvType = Context.getPointerType(ConvType); 8770 D.setInvalidType(); 8771 } else if (ConvType->isFunctionType()) { 8772 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 8773 ConvType = Context.getPointerType(ConvType); 8774 D.setInvalidType(); 8775 } 8776 8777 // Rebuild the function type "R" without any parameters (in case any 8778 // of the errors above fired) and with the conversion type as the 8779 // return type. 8780 if (D.isInvalidType()) 8781 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 8782 8783 // C++0x explicit conversion operators. 8784 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a) 8785 Diag(DS.getExplicitSpecLoc(), 8786 getLangOpts().CPlusPlus11 8787 ? diag::warn_cxx98_compat_explicit_conversion_functions 8788 : diag::ext_explicit_conversion_functions) 8789 << SourceRange(DS.getExplicitSpecRange()); 8790 } 8791 8792 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8793 /// the declaration of the given C++ conversion function. This routine 8794 /// is responsible for recording the conversion function in the C++ 8795 /// class, if possible. 8796 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8797 assert(Conversion && "Expected to receive a conversion function declaration"); 8798 8799 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8800 8801 // Make sure we aren't redeclaring the conversion function. 8802 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8803 8804 // C++ [class.conv.fct]p1: 8805 // [...] A conversion function is never used to convert a 8806 // (possibly cv-qualified) object to the (possibly cv-qualified) 8807 // same object type (or a reference to it), to a (possibly 8808 // cv-qualified) base class of that type (or a reference to it), 8809 // or to (possibly cv-qualified) void. 8810 // FIXME: Suppress this warning if the conversion function ends up being a 8811 // virtual function that overrides a virtual function in a base class. 8812 QualType ClassType 8813 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8814 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8815 ConvType = ConvTypeRef->getPointeeType(); 8816 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8817 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8818 /* Suppress diagnostics for instantiations. */; 8819 else if (ConvType->isRecordType()) { 8820 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8821 if (ConvType == ClassType) 8822 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8823 << ClassType; 8824 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8825 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8826 << ClassType << ConvType; 8827 } else if (ConvType->isVoidType()) { 8828 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8829 << ClassType << ConvType; 8830 } 8831 8832 if (FunctionTemplateDecl *ConversionTemplate 8833 = Conversion->getDescribedFunctionTemplate()) 8834 return ConversionTemplate; 8835 8836 return Conversion; 8837 } 8838 8839 namespace { 8840 /// Utility class to accumulate and print a diagnostic listing the invalid 8841 /// specifier(s) on a declaration. 8842 struct BadSpecifierDiagnoser { 8843 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 8844 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 8845 ~BadSpecifierDiagnoser() { 8846 Diagnostic << Specifiers; 8847 } 8848 8849 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 8850 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 8851 } 8852 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 8853 return check(SpecLoc, 8854 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 8855 } 8856 void check(SourceLocation SpecLoc, const char *Spec) { 8857 if (SpecLoc.isInvalid()) return; 8858 Diagnostic << SourceRange(SpecLoc, SpecLoc); 8859 if (!Specifiers.empty()) Specifiers += " "; 8860 Specifiers += Spec; 8861 } 8862 8863 Sema &S; 8864 Sema::SemaDiagnosticBuilder Diagnostic; 8865 std::string Specifiers; 8866 }; 8867 } 8868 8869 /// Check the validity of a declarator that we parsed for a deduction-guide. 8870 /// These aren't actually declarators in the grammar, so we need to check that 8871 /// the user didn't specify any pieces that are not part of the deduction-guide 8872 /// grammar. 8873 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 8874 StorageClass &SC) { 8875 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 8876 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 8877 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 8878 8879 // C++ [temp.deduct.guide]p3: 8880 // A deduction-gide shall be declared in the same scope as the 8881 // corresponding class template. 8882 if (!CurContext->getRedeclContext()->Equals( 8883 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 8884 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 8885 << GuidedTemplateDecl; 8886 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 8887 } 8888 8889 auto &DS = D.getMutableDeclSpec(); 8890 // We leave 'friend' and 'virtual' to be rejected in the normal way. 8891 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 8892 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 8893 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 8894 BadSpecifierDiagnoser Diagnoser( 8895 *this, D.getIdentifierLoc(), 8896 diag::err_deduction_guide_invalid_specifier); 8897 8898 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 8899 DS.ClearStorageClassSpecs(); 8900 SC = SC_None; 8901 8902 // 'explicit' is permitted. 8903 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 8904 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 8905 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 8906 DS.ClearConstexprSpec(); 8907 8908 Diagnoser.check(DS.getConstSpecLoc(), "const"); 8909 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 8910 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 8911 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 8912 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 8913 DS.ClearTypeQualifiers(); 8914 8915 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 8916 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 8917 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 8918 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 8919 DS.ClearTypeSpecType(); 8920 } 8921 8922 if (D.isInvalidType()) 8923 return; 8924 8925 // Check the declarator is simple enough. 8926 bool FoundFunction = false; 8927 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 8928 if (Chunk.Kind == DeclaratorChunk::Paren) 8929 continue; 8930 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 8931 Diag(D.getDeclSpec().getBeginLoc(), 8932 diag::err_deduction_guide_with_complex_decl) 8933 << D.getSourceRange(); 8934 break; 8935 } 8936 if (!Chunk.Fun.hasTrailingReturnType()) { 8937 Diag(D.getName().getBeginLoc(), 8938 diag::err_deduction_guide_no_trailing_return_type); 8939 break; 8940 } 8941 8942 // Check that the return type is written as a specialization of 8943 // the template specified as the deduction-guide's name. 8944 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 8945 TypeSourceInfo *TSI = nullptr; 8946 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 8947 assert(TSI && "deduction guide has valid type but invalid return type?"); 8948 bool AcceptableReturnType = false; 8949 bool MightInstantiateToSpecialization = false; 8950 if (auto RetTST = 8951 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 8952 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 8953 bool TemplateMatches = 8954 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 8955 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 8956 AcceptableReturnType = true; 8957 else { 8958 // This could still instantiate to the right type, unless we know it 8959 // names the wrong class template. 8960 auto *TD = SpecifiedName.getAsTemplateDecl(); 8961 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 8962 !TemplateMatches); 8963 } 8964 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 8965 MightInstantiateToSpecialization = true; 8966 } 8967 8968 if (!AcceptableReturnType) { 8969 Diag(TSI->getTypeLoc().getBeginLoc(), 8970 diag::err_deduction_guide_bad_trailing_return_type) 8971 << GuidedTemplate << TSI->getType() 8972 << MightInstantiateToSpecialization 8973 << TSI->getTypeLoc().getSourceRange(); 8974 } 8975 8976 // Keep going to check that we don't have any inner declarator pieces (we 8977 // could still have a function returning a pointer to a function). 8978 FoundFunction = true; 8979 } 8980 8981 if (D.isFunctionDefinition()) 8982 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 8983 } 8984 8985 //===----------------------------------------------------------------------===// 8986 // Namespace Handling 8987 //===----------------------------------------------------------------------===// 8988 8989 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 8990 /// reopened. 8991 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8992 SourceLocation Loc, 8993 IdentifierInfo *II, bool *IsInline, 8994 NamespaceDecl *PrevNS) { 8995 assert(*IsInline != PrevNS->isInline()); 8996 8997 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8998 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8999 // inline namespaces, with the intention of bringing names into namespace std. 9000 // 9001 // We support this just well enough to get that case working; this is not 9002 // sufficient to support reopening namespaces as inline in general. 9003 if (*IsInline && II && II->getName().startswith("__atomic") && 9004 S.getSourceManager().isInSystemHeader(Loc)) { 9005 // Mark all prior declarations of the namespace as inline. 9006 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 9007 NS = NS->getPreviousDecl()) 9008 NS->setInline(*IsInline); 9009 // Patch up the lookup table for the containing namespace. This isn't really 9010 // correct, but it's good enough for this particular case. 9011 for (auto *I : PrevNS->decls()) 9012 if (auto *ND = dyn_cast<NamedDecl>(I)) 9013 PrevNS->getParent()->makeDeclVisibleInContext(ND); 9014 return; 9015 } 9016 9017 if (PrevNS->isInline()) 9018 // The user probably just forgot the 'inline', so suggest that it 9019 // be added back. 9020 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 9021 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 9022 else 9023 S.Diag(Loc, diag::err_inline_namespace_mismatch); 9024 9025 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 9026 *IsInline = PrevNS->isInline(); 9027 } 9028 9029 /// ActOnStartNamespaceDef - This is called at the start of a namespace 9030 /// definition. 9031 Decl *Sema::ActOnStartNamespaceDef( 9032 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 9033 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 9034 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 9035 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 9036 // For anonymous namespace, take the location of the left brace. 9037 SourceLocation Loc = II ? IdentLoc : LBrace; 9038 bool IsInline = InlineLoc.isValid(); 9039 bool IsInvalid = false; 9040 bool IsStd = false; 9041 bool AddToKnown = false; 9042 Scope *DeclRegionScope = NamespcScope->getParent(); 9043 9044 NamespaceDecl *PrevNS = nullptr; 9045 if (II) { 9046 // C++ [namespace.def]p2: 9047 // The identifier in an original-namespace-definition shall not 9048 // have been previously defined in the declarative region in 9049 // which the original-namespace-definition appears. The 9050 // identifier in an original-namespace-definition is the name of 9051 // the namespace. Subsequently in that declarative region, it is 9052 // treated as an original-namespace-name. 9053 // 9054 // Since namespace names are unique in their scope, and we don't 9055 // look through using directives, just look for any ordinary names 9056 // as if by qualified name lookup. 9057 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 9058 ForExternalRedeclaration); 9059 LookupQualifiedName(R, CurContext->getRedeclContext()); 9060 NamedDecl *PrevDecl = 9061 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 9062 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 9063 9064 if (PrevNS) { 9065 // This is an extended namespace definition. 9066 if (IsInline != PrevNS->isInline()) 9067 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 9068 &IsInline, PrevNS); 9069 } else if (PrevDecl) { 9070 // This is an invalid name redefinition. 9071 Diag(Loc, diag::err_redefinition_different_kind) 9072 << II; 9073 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 9074 IsInvalid = true; 9075 // Continue on to push Namespc as current DeclContext and return it. 9076 } else if (II->isStr("std") && 9077 CurContext->getRedeclContext()->isTranslationUnit()) { 9078 // This is the first "real" definition of the namespace "std", so update 9079 // our cache of the "std" namespace to point at this definition. 9080 PrevNS = getStdNamespace(); 9081 IsStd = true; 9082 AddToKnown = !IsInline; 9083 } else { 9084 // We've seen this namespace for the first time. 9085 AddToKnown = !IsInline; 9086 } 9087 } else { 9088 // Anonymous namespaces. 9089 9090 // Determine whether the parent already has an anonymous namespace. 9091 DeclContext *Parent = CurContext->getRedeclContext(); 9092 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 9093 PrevNS = TU->getAnonymousNamespace(); 9094 } else { 9095 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 9096 PrevNS = ND->getAnonymousNamespace(); 9097 } 9098 9099 if (PrevNS && IsInline != PrevNS->isInline()) 9100 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 9101 &IsInline, PrevNS); 9102 } 9103 9104 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 9105 StartLoc, Loc, II, PrevNS); 9106 if (IsInvalid) 9107 Namespc->setInvalidDecl(); 9108 9109 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 9110 AddPragmaAttributes(DeclRegionScope, Namespc); 9111 9112 // FIXME: Should we be merging attributes? 9113 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 9114 PushNamespaceVisibilityAttr(Attr, Loc); 9115 9116 if (IsStd) 9117 StdNamespace = Namespc; 9118 if (AddToKnown) 9119 KnownNamespaces[Namespc] = false; 9120 9121 if (II) { 9122 PushOnScopeChains(Namespc, DeclRegionScope); 9123 } else { 9124 // Link the anonymous namespace into its parent. 9125 DeclContext *Parent = CurContext->getRedeclContext(); 9126 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 9127 TU->setAnonymousNamespace(Namespc); 9128 } else { 9129 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 9130 } 9131 9132 CurContext->addDecl(Namespc); 9133 9134 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 9135 // behaves as if it were replaced by 9136 // namespace unique { /* empty body */ } 9137 // using namespace unique; 9138 // namespace unique { namespace-body } 9139 // where all occurrences of 'unique' in a translation unit are 9140 // replaced by the same identifier and this identifier differs 9141 // from all other identifiers in the entire program. 9142 9143 // We just create the namespace with an empty name and then add an 9144 // implicit using declaration, just like the standard suggests. 9145 // 9146 // CodeGen enforces the "universally unique" aspect by giving all 9147 // declarations semantically contained within an anonymous 9148 // namespace internal linkage. 9149 9150 if (!PrevNS) { 9151 UD = UsingDirectiveDecl::Create(Context, Parent, 9152 /* 'using' */ LBrace, 9153 /* 'namespace' */ SourceLocation(), 9154 /* qualifier */ NestedNameSpecifierLoc(), 9155 /* identifier */ SourceLocation(), 9156 Namespc, 9157 /* Ancestor */ Parent); 9158 UD->setImplicit(); 9159 Parent->addDecl(UD); 9160 } 9161 } 9162 9163 ActOnDocumentableDecl(Namespc); 9164 9165 // Although we could have an invalid decl (i.e. the namespace name is a 9166 // redefinition), push it as current DeclContext and try to continue parsing. 9167 // FIXME: We should be able to push Namespc here, so that the each DeclContext 9168 // for the namespace has the declarations that showed up in that particular 9169 // namespace definition. 9170 PushDeclContext(NamespcScope, Namespc); 9171 return Namespc; 9172 } 9173 9174 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 9175 /// is a namespace alias, returns the namespace it points to. 9176 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 9177 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 9178 return AD->getNamespace(); 9179 return dyn_cast_or_null<NamespaceDecl>(D); 9180 } 9181 9182 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 9183 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 9184 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 9185 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 9186 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 9187 Namespc->setRBraceLoc(RBrace); 9188 PopDeclContext(); 9189 if (Namespc->hasAttr<VisibilityAttr>()) 9190 PopPragmaVisibility(true, RBrace); 9191 // If this namespace contains an export-declaration, export it now. 9192 if (DeferredExportedNamespaces.erase(Namespc)) 9193 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 9194 } 9195 9196 CXXRecordDecl *Sema::getStdBadAlloc() const { 9197 return cast_or_null<CXXRecordDecl>( 9198 StdBadAlloc.get(Context.getExternalSource())); 9199 } 9200 9201 EnumDecl *Sema::getStdAlignValT() const { 9202 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 9203 } 9204 9205 NamespaceDecl *Sema::getStdNamespace() const { 9206 return cast_or_null<NamespaceDecl>( 9207 StdNamespace.get(Context.getExternalSource())); 9208 } 9209 9210 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 9211 if (!StdExperimentalNamespaceCache) { 9212 if (auto Std = getStdNamespace()) { 9213 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 9214 SourceLocation(), LookupNamespaceName); 9215 if (!LookupQualifiedName(Result, Std) || 9216 !(StdExperimentalNamespaceCache = 9217 Result.getAsSingle<NamespaceDecl>())) 9218 Result.suppressDiagnostics(); 9219 } 9220 } 9221 return StdExperimentalNamespaceCache; 9222 } 9223 9224 namespace { 9225 9226 enum UnsupportedSTLSelect { 9227 USS_InvalidMember, 9228 USS_MissingMember, 9229 USS_NonTrivial, 9230 USS_Other 9231 }; 9232 9233 struct InvalidSTLDiagnoser { 9234 Sema &S; 9235 SourceLocation Loc; 9236 QualType TyForDiags; 9237 9238 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 9239 const VarDecl *VD = nullptr) { 9240 { 9241 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 9242 << TyForDiags << ((int)Sel); 9243 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 9244 assert(!Name.empty()); 9245 D << Name; 9246 } 9247 } 9248 if (Sel == USS_InvalidMember) { 9249 S.Diag(VD->getLocation(), diag::note_var_declared_here) 9250 << VD << VD->getSourceRange(); 9251 } 9252 return QualType(); 9253 } 9254 }; 9255 } // namespace 9256 9257 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 9258 SourceLocation Loc) { 9259 assert(getLangOpts().CPlusPlus && 9260 "Looking for comparison category type outside of C++."); 9261 9262 // Check if we've already successfully checked the comparison category type 9263 // before. If so, skip checking it again. 9264 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 9265 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) 9266 return Info->getType(); 9267 9268 // If lookup failed 9269 if (!Info) { 9270 std::string NameForDiags = "std::"; 9271 NameForDiags += ComparisonCategories::getCategoryString(Kind); 9272 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 9273 << NameForDiags; 9274 return QualType(); 9275 } 9276 9277 assert(Info->Kind == Kind); 9278 assert(Info->Record); 9279 9280 // Update the Record decl in case we encountered a forward declaration on our 9281 // first pass. FIXME: This is a bit of a hack. 9282 if (Info->Record->hasDefinition()) 9283 Info->Record = Info->Record->getDefinition(); 9284 9285 // Use an elaborated type for diagnostics which has a name containing the 9286 // prepended 'std' namespace but not any inline namespace names. 9287 QualType TyForDiags = [&]() { 9288 auto *NNS = 9289 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 9290 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 9291 }(); 9292 9293 if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type)) 9294 return QualType(); 9295 9296 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags}; 9297 9298 if (!Info->Record->isTriviallyCopyable()) 9299 return UnsupportedSTLError(USS_NonTrivial); 9300 9301 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 9302 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 9303 // Tolerate empty base classes. 9304 if (Base->isEmpty()) 9305 continue; 9306 // Reject STL implementations which have at least one non-empty base. 9307 return UnsupportedSTLError(); 9308 } 9309 9310 // Check that the STL has implemented the types using a single integer field. 9311 // This expectation allows better codegen for builtin operators. We require: 9312 // (1) The class has exactly one field. 9313 // (2) The field is an integral or enumeration type. 9314 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 9315 if (std::distance(FIt, FEnd) != 1 || 9316 !FIt->getType()->isIntegralOrEnumerationType()) { 9317 return UnsupportedSTLError(); 9318 } 9319 9320 // Build each of the require values and store them in Info. 9321 for (ComparisonCategoryResult CCR : 9322 ComparisonCategories::getPossibleResultsForType(Kind)) { 9323 StringRef MemName = ComparisonCategories::getResultString(CCR); 9324 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 9325 9326 if (!ValInfo) 9327 return UnsupportedSTLError(USS_MissingMember, MemName); 9328 9329 VarDecl *VD = ValInfo->VD; 9330 assert(VD && "should not be null!"); 9331 9332 // Attempt to diagnose reasons why the STL definition of this type 9333 // might be foobar, including it failing to be a constant expression. 9334 // TODO Handle more ways the lookup or result can be invalid. 9335 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() || 9336 !VD->checkInitIsICE()) 9337 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 9338 9339 // Attempt to evaluate the var decl as a constant expression and extract 9340 // the value of its first field as a ICE. If this fails, the STL 9341 // implementation is not supported. 9342 if (!ValInfo->hasValidIntValue()) 9343 return UnsupportedSTLError(); 9344 9345 MarkVariableReferenced(Loc, VD); 9346 } 9347 9348 // We've successfully built the required types and expressions. Update 9349 // the cache and return the newly cached value. 9350 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 9351 return Info->getType(); 9352 } 9353 9354 /// Retrieve the special "std" namespace, which may require us to 9355 /// implicitly define the namespace. 9356 NamespaceDecl *Sema::getOrCreateStdNamespace() { 9357 if (!StdNamespace) { 9358 // The "std" namespace has not yet been defined, so build one implicitly. 9359 StdNamespace = NamespaceDecl::Create(Context, 9360 Context.getTranslationUnitDecl(), 9361 /*Inline=*/false, 9362 SourceLocation(), SourceLocation(), 9363 &PP.getIdentifierTable().get("std"), 9364 /*PrevDecl=*/nullptr); 9365 getStdNamespace()->setImplicit(true); 9366 } 9367 9368 return getStdNamespace(); 9369 } 9370 9371 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 9372 assert(getLangOpts().CPlusPlus && 9373 "Looking for std::initializer_list outside of C++."); 9374 9375 // We're looking for implicit instantiations of 9376 // template <typename E> class std::initializer_list. 9377 9378 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 9379 return false; 9380 9381 ClassTemplateDecl *Template = nullptr; 9382 const TemplateArgument *Arguments = nullptr; 9383 9384 if (const RecordType *RT = Ty->getAs<RecordType>()) { 9385 9386 ClassTemplateSpecializationDecl *Specialization = 9387 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 9388 if (!Specialization) 9389 return false; 9390 9391 Template = Specialization->getSpecializedTemplate(); 9392 Arguments = Specialization->getTemplateArgs().data(); 9393 } else if (const TemplateSpecializationType *TST = 9394 Ty->getAs<TemplateSpecializationType>()) { 9395 Template = dyn_cast_or_null<ClassTemplateDecl>( 9396 TST->getTemplateName().getAsTemplateDecl()); 9397 Arguments = TST->getArgs(); 9398 } 9399 if (!Template) 9400 return false; 9401 9402 if (!StdInitializerList) { 9403 // Haven't recognized std::initializer_list yet, maybe this is it. 9404 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 9405 if (TemplateClass->getIdentifier() != 9406 &PP.getIdentifierTable().get("initializer_list") || 9407 !getStdNamespace()->InEnclosingNamespaceSetOf( 9408 TemplateClass->getDeclContext())) 9409 return false; 9410 // This is a template called std::initializer_list, but is it the right 9411 // template? 9412 TemplateParameterList *Params = Template->getTemplateParameters(); 9413 if (Params->getMinRequiredArguments() != 1) 9414 return false; 9415 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 9416 return false; 9417 9418 // It's the right template. 9419 StdInitializerList = Template; 9420 } 9421 9422 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 9423 return false; 9424 9425 // This is an instance of std::initializer_list. Find the argument type. 9426 if (Element) 9427 *Element = Arguments[0].getAsType(); 9428 return true; 9429 } 9430 9431 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 9432 NamespaceDecl *Std = S.getStdNamespace(); 9433 if (!Std) { 9434 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9435 return nullptr; 9436 } 9437 9438 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 9439 Loc, Sema::LookupOrdinaryName); 9440 if (!S.LookupQualifiedName(Result, Std)) { 9441 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9442 return nullptr; 9443 } 9444 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 9445 if (!Template) { 9446 Result.suppressDiagnostics(); 9447 // We found something weird. Complain about the first thing we found. 9448 NamedDecl *Found = *Result.begin(); 9449 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 9450 return nullptr; 9451 } 9452 9453 // We found some template called std::initializer_list. Now verify that it's 9454 // correct. 9455 TemplateParameterList *Params = Template->getTemplateParameters(); 9456 if (Params->getMinRequiredArguments() != 1 || 9457 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 9458 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 9459 return nullptr; 9460 } 9461 9462 return Template; 9463 } 9464 9465 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 9466 if (!StdInitializerList) { 9467 StdInitializerList = LookupStdInitializerList(*this, Loc); 9468 if (!StdInitializerList) 9469 return QualType(); 9470 } 9471 9472 TemplateArgumentListInfo Args(Loc, Loc); 9473 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 9474 Context.getTrivialTypeSourceInfo(Element, 9475 Loc))); 9476 return Context.getCanonicalType( 9477 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 9478 } 9479 9480 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 9481 // C++ [dcl.init.list]p2: 9482 // A constructor is an initializer-list constructor if its first parameter 9483 // is of type std::initializer_list<E> or reference to possibly cv-qualified 9484 // std::initializer_list<E> for some type E, and either there are no other 9485 // parameters or else all other parameters have default arguments. 9486 if (Ctor->getNumParams() < 1 || 9487 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 9488 return false; 9489 9490 QualType ArgType = Ctor->getParamDecl(0)->getType(); 9491 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 9492 ArgType = RT->getPointeeType().getUnqualifiedType(); 9493 9494 return isStdInitializerList(ArgType, nullptr); 9495 } 9496 9497 /// Determine whether a using statement is in a context where it will be 9498 /// apply in all contexts. 9499 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 9500 switch (CurContext->getDeclKind()) { 9501 case Decl::TranslationUnit: 9502 return true; 9503 case Decl::LinkageSpec: 9504 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 9505 default: 9506 return false; 9507 } 9508 } 9509 9510 namespace { 9511 9512 // Callback to only accept typo corrections that are namespaces. 9513 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 9514 public: 9515 bool ValidateCandidate(const TypoCorrection &candidate) override { 9516 if (NamedDecl *ND = candidate.getCorrectionDecl()) 9517 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 9518 return false; 9519 } 9520 9521 std::unique_ptr<CorrectionCandidateCallback> clone() override { 9522 return std::make_unique<NamespaceValidatorCCC>(*this); 9523 } 9524 }; 9525 9526 } 9527 9528 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 9529 CXXScopeSpec &SS, 9530 SourceLocation IdentLoc, 9531 IdentifierInfo *Ident) { 9532 R.clear(); 9533 NamespaceValidatorCCC CCC{}; 9534 if (TypoCorrection Corrected = 9535 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 9536 Sema::CTK_ErrorRecovery)) { 9537 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 9538 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 9539 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 9540 Ident->getName().equals(CorrectedStr); 9541 S.diagnoseTypo(Corrected, 9542 S.PDiag(diag::err_using_directive_member_suggest) 9543 << Ident << DC << DroppedSpecifier << SS.getRange(), 9544 S.PDiag(diag::note_namespace_defined_here)); 9545 } else { 9546 S.diagnoseTypo(Corrected, 9547 S.PDiag(diag::err_using_directive_suggest) << Ident, 9548 S.PDiag(diag::note_namespace_defined_here)); 9549 } 9550 R.addDecl(Corrected.getFoundDecl()); 9551 return true; 9552 } 9553 return false; 9554 } 9555 9556 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 9557 SourceLocation NamespcLoc, CXXScopeSpec &SS, 9558 SourceLocation IdentLoc, 9559 IdentifierInfo *NamespcName, 9560 const ParsedAttributesView &AttrList) { 9561 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9562 assert(NamespcName && "Invalid NamespcName."); 9563 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 9564 9565 // This can only happen along a recovery path. 9566 while (S->isTemplateParamScope()) 9567 S = S->getParent(); 9568 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9569 9570 UsingDirectiveDecl *UDir = nullptr; 9571 NestedNameSpecifier *Qualifier = nullptr; 9572 if (SS.isSet()) 9573 Qualifier = SS.getScopeRep(); 9574 9575 // Lookup namespace name. 9576 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 9577 LookupParsedName(R, S, &SS); 9578 if (R.isAmbiguous()) 9579 return nullptr; 9580 9581 if (R.empty()) { 9582 R.clear(); 9583 // Allow "using namespace std;" or "using namespace ::std;" even if 9584 // "std" hasn't been defined yet, for GCC compatibility. 9585 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 9586 NamespcName->isStr("std")) { 9587 Diag(IdentLoc, diag::ext_using_undefined_std); 9588 R.addDecl(getOrCreateStdNamespace()); 9589 R.resolveKind(); 9590 } 9591 // Otherwise, attempt typo correction. 9592 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 9593 } 9594 9595 if (!R.empty()) { 9596 NamedDecl *Named = R.getRepresentativeDecl(); 9597 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 9598 assert(NS && "expected namespace decl"); 9599 9600 // The use of a nested name specifier may trigger deprecation warnings. 9601 DiagnoseUseOfDecl(Named, IdentLoc); 9602 9603 // C++ [namespace.udir]p1: 9604 // A using-directive specifies that the names in the nominated 9605 // namespace can be used in the scope in which the 9606 // using-directive appears after the using-directive. During 9607 // unqualified name lookup (3.4.1), the names appear as if they 9608 // were declared in the nearest enclosing namespace which 9609 // contains both the using-directive and the nominated 9610 // namespace. [Note: in this context, "contains" means "contains 9611 // directly or indirectly". ] 9612 9613 // Find enclosing context containing both using-directive and 9614 // nominated namespace. 9615 DeclContext *CommonAncestor = NS; 9616 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 9617 CommonAncestor = CommonAncestor->getParent(); 9618 9619 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 9620 SS.getWithLocInContext(Context), 9621 IdentLoc, Named, CommonAncestor); 9622 9623 if (IsUsingDirectiveInToplevelContext(CurContext) && 9624 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 9625 Diag(IdentLoc, diag::warn_using_directive_in_header); 9626 } 9627 9628 PushUsingDirective(S, UDir); 9629 } else { 9630 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 9631 } 9632 9633 if (UDir) 9634 ProcessDeclAttributeList(S, UDir, AttrList); 9635 9636 return UDir; 9637 } 9638 9639 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 9640 // If the scope has an associated entity and the using directive is at 9641 // namespace or translation unit scope, add the UsingDirectiveDecl into 9642 // its lookup structure so qualified name lookup can find it. 9643 DeclContext *Ctx = S->getEntity(); 9644 if (Ctx && !Ctx->isFunctionOrMethod()) 9645 Ctx->addDecl(UDir); 9646 else 9647 // Otherwise, it is at block scope. The using-directives will affect lookup 9648 // only to the end of the scope. 9649 S->PushUsingDirective(UDir); 9650 } 9651 9652 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 9653 SourceLocation UsingLoc, 9654 SourceLocation TypenameLoc, CXXScopeSpec &SS, 9655 UnqualifiedId &Name, 9656 SourceLocation EllipsisLoc, 9657 const ParsedAttributesView &AttrList) { 9658 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9659 9660 if (SS.isEmpty()) { 9661 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 9662 return nullptr; 9663 } 9664 9665 switch (Name.getKind()) { 9666 case UnqualifiedIdKind::IK_ImplicitSelfParam: 9667 case UnqualifiedIdKind::IK_Identifier: 9668 case UnqualifiedIdKind::IK_OperatorFunctionId: 9669 case UnqualifiedIdKind::IK_LiteralOperatorId: 9670 case UnqualifiedIdKind::IK_ConversionFunctionId: 9671 break; 9672 9673 case UnqualifiedIdKind::IK_ConstructorName: 9674 case UnqualifiedIdKind::IK_ConstructorTemplateId: 9675 // C++11 inheriting constructors. 9676 Diag(Name.getBeginLoc(), 9677 getLangOpts().CPlusPlus11 9678 ? diag::warn_cxx98_compat_using_decl_constructor 9679 : diag::err_using_decl_constructor) 9680 << SS.getRange(); 9681 9682 if (getLangOpts().CPlusPlus11) break; 9683 9684 return nullptr; 9685 9686 case UnqualifiedIdKind::IK_DestructorName: 9687 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 9688 return nullptr; 9689 9690 case UnqualifiedIdKind::IK_TemplateId: 9691 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 9692 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 9693 return nullptr; 9694 9695 case UnqualifiedIdKind::IK_DeductionGuideName: 9696 llvm_unreachable("cannot parse qualified deduction guide name"); 9697 } 9698 9699 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 9700 DeclarationName TargetName = TargetNameInfo.getName(); 9701 if (!TargetName) 9702 return nullptr; 9703 9704 // Warn about access declarations. 9705 if (UsingLoc.isInvalid()) { 9706 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 9707 ? diag::err_access_decl 9708 : diag::warn_access_decl_deprecated) 9709 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 9710 } 9711 9712 if (EllipsisLoc.isInvalid()) { 9713 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 9714 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 9715 return nullptr; 9716 } else { 9717 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 9718 !TargetNameInfo.containsUnexpandedParameterPack()) { 9719 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 9720 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 9721 EllipsisLoc = SourceLocation(); 9722 } 9723 } 9724 9725 NamedDecl *UD = 9726 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 9727 SS, TargetNameInfo, EllipsisLoc, AttrList, 9728 /*IsInstantiation*/false); 9729 if (UD) 9730 PushOnScopeChains(UD, S, /*AddToContext*/ false); 9731 9732 return UD; 9733 } 9734 9735 /// Determine whether a using declaration considers the given 9736 /// declarations as "equivalent", e.g., if they are redeclarations of 9737 /// the same entity or are both typedefs of the same type. 9738 static bool 9739 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 9740 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 9741 return true; 9742 9743 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 9744 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 9745 return Context.hasSameType(TD1->getUnderlyingType(), 9746 TD2->getUnderlyingType()); 9747 9748 return false; 9749 } 9750 9751 9752 /// Determines whether to create a using shadow decl for a particular 9753 /// decl, given the set of decls existing prior to this using lookup. 9754 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 9755 const LookupResult &Previous, 9756 UsingShadowDecl *&PrevShadow) { 9757 // Diagnose finding a decl which is not from a base class of the 9758 // current class. We do this now because there are cases where this 9759 // function will silently decide not to build a shadow decl, which 9760 // will pre-empt further diagnostics. 9761 // 9762 // We don't need to do this in C++11 because we do the check once on 9763 // the qualifier. 9764 // 9765 // FIXME: diagnose the following if we care enough: 9766 // struct A { int foo; }; 9767 // struct B : A { using A::foo; }; 9768 // template <class T> struct C : A {}; 9769 // template <class T> struct D : C<T> { using B::foo; } // <--- 9770 // This is invalid (during instantiation) in C++03 because B::foo 9771 // resolves to the using decl in B, which is not a base class of D<T>. 9772 // We can't diagnose it immediately because C<T> is an unknown 9773 // specialization. The UsingShadowDecl in D<T> then points directly 9774 // to A::foo, which will look well-formed when we instantiate. 9775 // The right solution is to not collapse the shadow-decl chain. 9776 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 9777 DeclContext *OrigDC = Orig->getDeclContext(); 9778 9779 // Handle enums and anonymous structs. 9780 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 9781 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 9782 while (OrigRec->isAnonymousStructOrUnion()) 9783 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 9784 9785 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 9786 if (OrigDC == CurContext) { 9787 Diag(Using->getLocation(), 9788 diag::err_using_decl_nested_name_specifier_is_current_class) 9789 << Using->getQualifierLoc().getSourceRange(); 9790 Diag(Orig->getLocation(), diag::note_using_decl_target); 9791 Using->setInvalidDecl(); 9792 return true; 9793 } 9794 9795 Diag(Using->getQualifierLoc().getBeginLoc(), 9796 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9797 << Using->getQualifier() 9798 << cast<CXXRecordDecl>(CurContext) 9799 << Using->getQualifierLoc().getSourceRange(); 9800 Diag(Orig->getLocation(), diag::note_using_decl_target); 9801 Using->setInvalidDecl(); 9802 return true; 9803 } 9804 } 9805 9806 if (Previous.empty()) return false; 9807 9808 NamedDecl *Target = Orig; 9809 if (isa<UsingShadowDecl>(Target)) 9810 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9811 9812 // If the target happens to be one of the previous declarations, we 9813 // don't have a conflict. 9814 // 9815 // FIXME: but we might be increasing its access, in which case we 9816 // should redeclare it. 9817 NamedDecl *NonTag = nullptr, *Tag = nullptr; 9818 bool FoundEquivalentDecl = false; 9819 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9820 I != E; ++I) { 9821 NamedDecl *D = (*I)->getUnderlyingDecl(); 9822 // We can have UsingDecls in our Previous results because we use the same 9823 // LookupResult for checking whether the UsingDecl itself is a valid 9824 // redeclaration. 9825 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 9826 continue; 9827 9828 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 9829 // C++ [class.mem]p19: 9830 // If T is the name of a class, then [every named member other than 9831 // a non-static data member] shall have a name different from T 9832 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 9833 !isa<IndirectFieldDecl>(Target) && 9834 !isa<UnresolvedUsingValueDecl>(Target) && 9835 DiagnoseClassNameShadow( 9836 CurContext, 9837 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 9838 return true; 9839 } 9840 9841 if (IsEquivalentForUsingDecl(Context, D, Target)) { 9842 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 9843 PrevShadow = Shadow; 9844 FoundEquivalentDecl = true; 9845 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 9846 // We don't conflict with an existing using shadow decl of an equivalent 9847 // declaration, but we're not a redeclaration of it. 9848 FoundEquivalentDecl = true; 9849 } 9850 9851 if (isVisible(D)) 9852 (isa<TagDecl>(D) ? Tag : NonTag) = D; 9853 } 9854 9855 if (FoundEquivalentDecl) 9856 return false; 9857 9858 if (FunctionDecl *FD = Target->getAsFunction()) { 9859 NamedDecl *OldDecl = nullptr; 9860 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 9861 /*IsForUsingDecl*/ true)) { 9862 case Ovl_Overload: 9863 return false; 9864 9865 case Ovl_NonFunction: 9866 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9867 break; 9868 9869 // We found a decl with the exact signature. 9870 case Ovl_Match: 9871 // If we're in a record, we want to hide the target, so we 9872 // return true (without a diagnostic) to tell the caller not to 9873 // build a shadow decl. 9874 if (CurContext->isRecord()) 9875 return true; 9876 9877 // If we're not in a record, this is an error. 9878 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9879 break; 9880 } 9881 9882 Diag(Target->getLocation(), diag::note_using_decl_target); 9883 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 9884 Using->setInvalidDecl(); 9885 return true; 9886 } 9887 9888 // Target is not a function. 9889 9890 if (isa<TagDecl>(Target)) { 9891 // No conflict between a tag and a non-tag. 9892 if (!Tag) return false; 9893 9894 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9895 Diag(Target->getLocation(), diag::note_using_decl_target); 9896 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 9897 Using->setInvalidDecl(); 9898 return true; 9899 } 9900 9901 // No conflict between a tag and a non-tag. 9902 if (!NonTag) return false; 9903 9904 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9905 Diag(Target->getLocation(), diag::note_using_decl_target); 9906 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 9907 Using->setInvalidDecl(); 9908 return true; 9909 } 9910 9911 /// Determine whether a direct base class is a virtual base class. 9912 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 9913 if (!Derived->getNumVBases()) 9914 return false; 9915 for (auto &B : Derived->bases()) 9916 if (B.getType()->getAsCXXRecordDecl() == Base) 9917 return B.isVirtual(); 9918 llvm_unreachable("not a direct base class"); 9919 } 9920 9921 /// Builds a shadow declaration corresponding to a 'using' declaration. 9922 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 9923 UsingDecl *UD, 9924 NamedDecl *Orig, 9925 UsingShadowDecl *PrevDecl) { 9926 // If we resolved to another shadow declaration, just coalesce them. 9927 NamedDecl *Target = Orig; 9928 if (isa<UsingShadowDecl>(Target)) { 9929 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9930 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 9931 } 9932 9933 NamedDecl *NonTemplateTarget = Target; 9934 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 9935 NonTemplateTarget = TargetTD->getTemplatedDecl(); 9936 9937 UsingShadowDecl *Shadow; 9938 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 9939 bool IsVirtualBase = 9940 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 9941 UD->getQualifier()->getAsRecordDecl()); 9942 Shadow = ConstructorUsingShadowDecl::Create( 9943 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 9944 } else { 9945 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 9946 Target); 9947 } 9948 UD->addShadowDecl(Shadow); 9949 9950 Shadow->setAccess(UD->getAccess()); 9951 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 9952 Shadow->setInvalidDecl(); 9953 9954 Shadow->setPreviousDecl(PrevDecl); 9955 9956 if (S) 9957 PushOnScopeChains(Shadow, S); 9958 else 9959 CurContext->addDecl(Shadow); 9960 9961 9962 return Shadow; 9963 } 9964 9965 /// Hides a using shadow declaration. This is required by the current 9966 /// using-decl implementation when a resolvable using declaration in a 9967 /// class is followed by a declaration which would hide or override 9968 /// one or more of the using decl's targets; for example: 9969 /// 9970 /// struct Base { void foo(int); }; 9971 /// struct Derived : Base { 9972 /// using Base::foo; 9973 /// void foo(int); 9974 /// }; 9975 /// 9976 /// The governing language is C++03 [namespace.udecl]p12: 9977 /// 9978 /// When a using-declaration brings names from a base class into a 9979 /// derived class scope, member functions in the derived class 9980 /// override and/or hide member functions with the same name and 9981 /// parameter types in a base class (rather than conflicting). 9982 /// 9983 /// There are two ways to implement this: 9984 /// (1) optimistically create shadow decls when they're not hidden 9985 /// by existing declarations, or 9986 /// (2) don't create any shadow decls (or at least don't make them 9987 /// visible) until we've fully parsed/instantiated the class. 9988 /// The problem with (1) is that we might have to retroactively remove 9989 /// a shadow decl, which requires several O(n) operations because the 9990 /// decl structures are (very reasonably) not designed for removal. 9991 /// (2) avoids this but is very fiddly and phase-dependent. 9992 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 9993 if (Shadow->getDeclName().getNameKind() == 9994 DeclarationName::CXXConversionFunctionName) 9995 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 9996 9997 // Remove it from the DeclContext... 9998 Shadow->getDeclContext()->removeDecl(Shadow); 9999 10000 // ...and the scope, if applicable... 10001 if (S) { 10002 S->RemoveDecl(Shadow); 10003 IdResolver.RemoveDecl(Shadow); 10004 } 10005 10006 // ...and the using decl. 10007 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 10008 10009 // TODO: complain somehow if Shadow was used. It shouldn't 10010 // be possible for this to happen, because...? 10011 } 10012 10013 /// Find the base specifier for a base class with the given type. 10014 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 10015 QualType DesiredBase, 10016 bool &AnyDependentBases) { 10017 // Check whether the named type is a direct base class. 10018 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 10019 .getUnqualifiedType(); 10020 for (auto &Base : Derived->bases()) { 10021 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 10022 if (CanonicalDesiredBase == BaseType) 10023 return &Base; 10024 if (BaseType->isDependentType()) 10025 AnyDependentBases = true; 10026 } 10027 return nullptr; 10028 } 10029 10030 namespace { 10031 class UsingValidatorCCC final : public CorrectionCandidateCallback { 10032 public: 10033 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 10034 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 10035 : HasTypenameKeyword(HasTypenameKeyword), 10036 IsInstantiation(IsInstantiation), OldNNS(NNS), 10037 RequireMemberOf(RequireMemberOf) {} 10038 10039 bool ValidateCandidate(const TypoCorrection &Candidate) override { 10040 NamedDecl *ND = Candidate.getCorrectionDecl(); 10041 10042 // Keywords are not valid here. 10043 if (!ND || isa<NamespaceDecl>(ND)) 10044 return false; 10045 10046 // Completely unqualified names are invalid for a 'using' declaration. 10047 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 10048 return false; 10049 10050 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 10051 // reject. 10052 10053 if (RequireMemberOf) { 10054 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 10055 if (FoundRecord && FoundRecord->isInjectedClassName()) { 10056 // No-one ever wants a using-declaration to name an injected-class-name 10057 // of a base class, unless they're declaring an inheriting constructor. 10058 ASTContext &Ctx = ND->getASTContext(); 10059 if (!Ctx.getLangOpts().CPlusPlus11) 10060 return false; 10061 QualType FoundType = Ctx.getRecordType(FoundRecord); 10062 10063 // Check that the injected-class-name is named as a member of its own 10064 // type; we don't want to suggest 'using Derived::Base;', since that 10065 // means something else. 10066 NestedNameSpecifier *Specifier = 10067 Candidate.WillReplaceSpecifier() 10068 ? Candidate.getCorrectionSpecifier() 10069 : OldNNS; 10070 if (!Specifier->getAsType() || 10071 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 10072 return false; 10073 10074 // Check that this inheriting constructor declaration actually names a 10075 // direct base class of the current class. 10076 bool AnyDependentBases = false; 10077 if (!findDirectBaseWithType(RequireMemberOf, 10078 Ctx.getRecordType(FoundRecord), 10079 AnyDependentBases) && 10080 !AnyDependentBases) 10081 return false; 10082 } else { 10083 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 10084 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 10085 return false; 10086 10087 // FIXME: Check that the base class member is accessible? 10088 } 10089 } else { 10090 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 10091 if (FoundRecord && FoundRecord->isInjectedClassName()) 10092 return false; 10093 } 10094 10095 if (isa<TypeDecl>(ND)) 10096 return HasTypenameKeyword || !IsInstantiation; 10097 10098 return !HasTypenameKeyword; 10099 } 10100 10101 std::unique_ptr<CorrectionCandidateCallback> clone() override { 10102 return std::make_unique<UsingValidatorCCC>(*this); 10103 } 10104 10105 private: 10106 bool HasTypenameKeyword; 10107 bool IsInstantiation; 10108 NestedNameSpecifier *OldNNS; 10109 CXXRecordDecl *RequireMemberOf; 10110 }; 10111 } // end anonymous namespace 10112 10113 /// Builds a using declaration. 10114 /// 10115 /// \param IsInstantiation - Whether this call arises from an 10116 /// instantiation of an unresolved using declaration. We treat 10117 /// the lookup differently for these declarations. 10118 NamedDecl *Sema::BuildUsingDeclaration( 10119 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 10120 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 10121 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 10122 const ParsedAttributesView &AttrList, bool IsInstantiation) { 10123 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 10124 SourceLocation IdentLoc = NameInfo.getLoc(); 10125 assert(IdentLoc.isValid() && "Invalid TargetName location."); 10126 10127 // FIXME: We ignore attributes for now. 10128 10129 // For an inheriting constructor declaration, the name of the using 10130 // declaration is the name of a constructor in this class, not in the 10131 // base class. 10132 DeclarationNameInfo UsingName = NameInfo; 10133 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 10134 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 10135 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 10136 Context.getCanonicalType(Context.getRecordType(RD)))); 10137 10138 // Do the redeclaration lookup in the current scope. 10139 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 10140 ForVisibleRedeclaration); 10141 Previous.setHideTags(false); 10142 if (S) { 10143 LookupName(Previous, S); 10144 10145 // It is really dumb that we have to do this. 10146 LookupResult::Filter F = Previous.makeFilter(); 10147 while (F.hasNext()) { 10148 NamedDecl *D = F.next(); 10149 if (!isDeclInScope(D, CurContext, S)) 10150 F.erase(); 10151 // If we found a local extern declaration that's not ordinarily visible, 10152 // and this declaration is being added to a non-block scope, ignore it. 10153 // We're only checking for scope conflicts here, not also for violations 10154 // of the linkage rules. 10155 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 10156 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 10157 F.erase(); 10158 } 10159 F.done(); 10160 } else { 10161 assert(IsInstantiation && "no scope in non-instantiation"); 10162 if (CurContext->isRecord()) 10163 LookupQualifiedName(Previous, CurContext); 10164 else { 10165 // No redeclaration check is needed here; in non-member contexts we 10166 // diagnosed all possible conflicts with other using-declarations when 10167 // building the template: 10168 // 10169 // For a dependent non-type using declaration, the only valid case is 10170 // if we instantiate to a single enumerator. We check for conflicts 10171 // between shadow declarations we introduce, and we check in the template 10172 // definition for conflicts between a non-type using declaration and any 10173 // other declaration, which together covers all cases. 10174 // 10175 // A dependent typename using declaration will never successfully 10176 // instantiate, since it will always name a class member, so we reject 10177 // that in the template definition. 10178 } 10179 } 10180 10181 // Check for invalid redeclarations. 10182 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 10183 SS, IdentLoc, Previous)) 10184 return nullptr; 10185 10186 // Check for bad qualifiers. 10187 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 10188 IdentLoc)) 10189 return nullptr; 10190 10191 DeclContext *LookupContext = computeDeclContext(SS); 10192 NamedDecl *D; 10193 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 10194 if (!LookupContext || EllipsisLoc.isValid()) { 10195 if (HasTypenameKeyword) { 10196 // FIXME: not all declaration name kinds are legal here 10197 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 10198 UsingLoc, TypenameLoc, 10199 QualifierLoc, 10200 IdentLoc, NameInfo.getName(), 10201 EllipsisLoc); 10202 } else { 10203 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 10204 QualifierLoc, NameInfo, EllipsisLoc); 10205 } 10206 D->setAccess(AS); 10207 CurContext->addDecl(D); 10208 return D; 10209 } 10210 10211 auto Build = [&](bool Invalid) { 10212 UsingDecl *UD = 10213 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 10214 UsingName, HasTypenameKeyword); 10215 UD->setAccess(AS); 10216 CurContext->addDecl(UD); 10217 UD->setInvalidDecl(Invalid); 10218 return UD; 10219 }; 10220 auto BuildInvalid = [&]{ return Build(true); }; 10221 auto BuildValid = [&]{ return Build(false); }; 10222 10223 if (RequireCompleteDeclContext(SS, LookupContext)) 10224 return BuildInvalid(); 10225 10226 // Look up the target name. 10227 LookupResult R(*this, NameInfo, LookupOrdinaryName); 10228 10229 // Unlike most lookups, we don't always want to hide tag 10230 // declarations: tag names are visible through the using declaration 10231 // even if hidden by ordinary names, *except* in a dependent context 10232 // where it's important for the sanity of two-phase lookup. 10233 if (!IsInstantiation) 10234 R.setHideTags(false); 10235 10236 // For the purposes of this lookup, we have a base object type 10237 // equal to that of the current context. 10238 if (CurContext->isRecord()) { 10239 R.setBaseObjectType( 10240 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 10241 } 10242 10243 LookupQualifiedName(R, LookupContext); 10244 10245 // Try to correct typos if possible. If constructor name lookup finds no 10246 // results, that means the named class has no explicit constructors, and we 10247 // suppressed declaring implicit ones (probably because it's dependent or 10248 // invalid). 10249 if (R.empty() && 10250 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 10251 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 10252 // it will believe that glibc provides a ::gets in cases where it does not, 10253 // and will try to pull it into namespace std with a using-declaration. 10254 // Just ignore the using-declaration in that case. 10255 auto *II = NameInfo.getName().getAsIdentifierInfo(); 10256 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 10257 CurContext->isStdNamespace() && 10258 isa<TranslationUnitDecl>(LookupContext) && 10259 getSourceManager().isInSystemHeader(UsingLoc)) 10260 return nullptr; 10261 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 10262 dyn_cast<CXXRecordDecl>(CurContext)); 10263 if (TypoCorrection Corrected = 10264 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 10265 CTK_ErrorRecovery)) { 10266 // We reject candidates where DroppedSpecifier == true, hence the 10267 // literal '0' below. 10268 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 10269 << NameInfo.getName() << LookupContext << 0 10270 << SS.getRange()); 10271 10272 // If we picked a correction with no attached Decl we can't do anything 10273 // useful with it, bail out. 10274 NamedDecl *ND = Corrected.getCorrectionDecl(); 10275 if (!ND) 10276 return BuildInvalid(); 10277 10278 // If we corrected to an inheriting constructor, handle it as one. 10279 auto *RD = dyn_cast<CXXRecordDecl>(ND); 10280 if (RD && RD->isInjectedClassName()) { 10281 // The parent of the injected class name is the class itself. 10282 RD = cast<CXXRecordDecl>(RD->getParent()); 10283 10284 // Fix up the information we'll use to build the using declaration. 10285 if (Corrected.WillReplaceSpecifier()) { 10286 NestedNameSpecifierLocBuilder Builder; 10287 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 10288 QualifierLoc.getSourceRange()); 10289 QualifierLoc = Builder.getWithLocInContext(Context); 10290 } 10291 10292 // In this case, the name we introduce is the name of a derived class 10293 // constructor. 10294 auto *CurClass = cast<CXXRecordDecl>(CurContext); 10295 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 10296 Context.getCanonicalType(Context.getRecordType(CurClass)))); 10297 UsingName.setNamedTypeInfo(nullptr); 10298 for (auto *Ctor : LookupConstructors(RD)) 10299 R.addDecl(Ctor); 10300 R.resolveKind(); 10301 } else { 10302 // FIXME: Pick up all the declarations if we found an overloaded 10303 // function. 10304 UsingName.setName(ND->getDeclName()); 10305 R.addDecl(ND); 10306 } 10307 } else { 10308 Diag(IdentLoc, diag::err_no_member) 10309 << NameInfo.getName() << LookupContext << SS.getRange(); 10310 return BuildInvalid(); 10311 } 10312 } 10313 10314 if (R.isAmbiguous()) 10315 return BuildInvalid(); 10316 10317 if (HasTypenameKeyword) { 10318 // If we asked for a typename and got a non-type decl, error out. 10319 if (!R.getAsSingle<TypeDecl>()) { 10320 Diag(IdentLoc, diag::err_using_typename_non_type); 10321 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10322 Diag((*I)->getUnderlyingDecl()->getLocation(), 10323 diag::note_using_decl_target); 10324 return BuildInvalid(); 10325 } 10326 } else { 10327 // If we asked for a non-typename and we got a type, error out, 10328 // but only if this is an instantiation of an unresolved using 10329 // decl. Otherwise just silently find the type name. 10330 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 10331 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 10332 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 10333 return BuildInvalid(); 10334 } 10335 } 10336 10337 // C++14 [namespace.udecl]p6: 10338 // A using-declaration shall not name a namespace. 10339 if (R.getAsSingle<NamespaceDecl>()) { 10340 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 10341 << SS.getRange(); 10342 return BuildInvalid(); 10343 } 10344 10345 // C++14 [namespace.udecl]p7: 10346 // A using-declaration shall not name a scoped enumerator. 10347 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 10348 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 10349 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 10350 << SS.getRange(); 10351 return BuildInvalid(); 10352 } 10353 } 10354 10355 UsingDecl *UD = BuildValid(); 10356 10357 // Some additional rules apply to inheriting constructors. 10358 if (UsingName.getName().getNameKind() == 10359 DeclarationName::CXXConstructorName) { 10360 // Suppress access diagnostics; the access check is instead performed at the 10361 // point of use for an inheriting constructor. 10362 R.suppressDiagnostics(); 10363 if (CheckInheritingConstructorUsingDecl(UD)) 10364 return UD; 10365 } 10366 10367 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 10368 UsingShadowDecl *PrevDecl = nullptr; 10369 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 10370 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 10371 } 10372 10373 return UD; 10374 } 10375 10376 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 10377 ArrayRef<NamedDecl *> Expansions) { 10378 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 10379 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 10380 isa<UsingPackDecl>(InstantiatedFrom)); 10381 10382 auto *UPD = 10383 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 10384 UPD->setAccess(InstantiatedFrom->getAccess()); 10385 CurContext->addDecl(UPD); 10386 return UPD; 10387 } 10388 10389 /// Additional checks for a using declaration referring to a constructor name. 10390 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 10391 assert(!UD->hasTypename() && "expecting a constructor name"); 10392 10393 const Type *SourceType = UD->getQualifier()->getAsType(); 10394 assert(SourceType && 10395 "Using decl naming constructor doesn't have type in scope spec."); 10396 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 10397 10398 // Check whether the named type is a direct base class. 10399 bool AnyDependentBases = false; 10400 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 10401 AnyDependentBases); 10402 if (!Base && !AnyDependentBases) { 10403 Diag(UD->getUsingLoc(), 10404 diag::err_using_decl_constructor_not_in_direct_base) 10405 << UD->getNameInfo().getSourceRange() 10406 << QualType(SourceType, 0) << TargetClass; 10407 UD->setInvalidDecl(); 10408 return true; 10409 } 10410 10411 if (Base) 10412 Base->setInheritConstructors(); 10413 10414 return false; 10415 } 10416 10417 /// Checks that the given using declaration is not an invalid 10418 /// redeclaration. Note that this is checking only for the using decl 10419 /// itself, not for any ill-formedness among the UsingShadowDecls. 10420 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 10421 bool HasTypenameKeyword, 10422 const CXXScopeSpec &SS, 10423 SourceLocation NameLoc, 10424 const LookupResult &Prev) { 10425 NestedNameSpecifier *Qual = SS.getScopeRep(); 10426 10427 // C++03 [namespace.udecl]p8: 10428 // C++0x [namespace.udecl]p10: 10429 // A using-declaration is a declaration and can therefore be used 10430 // repeatedly where (and only where) multiple declarations are 10431 // allowed. 10432 // 10433 // That's in non-member contexts. 10434 if (!CurContext->getRedeclContext()->isRecord()) { 10435 // A dependent qualifier outside a class can only ever resolve to an 10436 // enumeration type. Therefore it conflicts with any other non-type 10437 // declaration in the same scope. 10438 // FIXME: How should we check for dependent type-type conflicts at block 10439 // scope? 10440 if (Qual->isDependent() && !HasTypenameKeyword) { 10441 for (auto *D : Prev) { 10442 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 10443 bool OldCouldBeEnumerator = 10444 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 10445 Diag(NameLoc, 10446 OldCouldBeEnumerator ? diag::err_redefinition 10447 : diag::err_redefinition_different_kind) 10448 << Prev.getLookupName(); 10449 Diag(D->getLocation(), diag::note_previous_definition); 10450 return true; 10451 } 10452 } 10453 } 10454 return false; 10455 } 10456 10457 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 10458 NamedDecl *D = *I; 10459 10460 bool DTypename; 10461 NestedNameSpecifier *DQual; 10462 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 10463 DTypename = UD->hasTypename(); 10464 DQual = UD->getQualifier(); 10465 } else if (UnresolvedUsingValueDecl *UD 10466 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 10467 DTypename = false; 10468 DQual = UD->getQualifier(); 10469 } else if (UnresolvedUsingTypenameDecl *UD 10470 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 10471 DTypename = true; 10472 DQual = UD->getQualifier(); 10473 } else continue; 10474 10475 // using decls differ if one says 'typename' and the other doesn't. 10476 // FIXME: non-dependent using decls? 10477 if (HasTypenameKeyword != DTypename) continue; 10478 10479 // using decls differ if they name different scopes (but note that 10480 // template instantiation can cause this check to trigger when it 10481 // didn't before instantiation). 10482 if (Context.getCanonicalNestedNameSpecifier(Qual) != 10483 Context.getCanonicalNestedNameSpecifier(DQual)) 10484 continue; 10485 10486 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 10487 Diag(D->getLocation(), diag::note_using_decl) << 1; 10488 return true; 10489 } 10490 10491 return false; 10492 } 10493 10494 10495 /// Checks that the given nested-name qualifier used in a using decl 10496 /// in the current context is appropriately related to the current 10497 /// scope. If an error is found, diagnoses it and returns true. 10498 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 10499 bool HasTypename, 10500 const CXXScopeSpec &SS, 10501 const DeclarationNameInfo &NameInfo, 10502 SourceLocation NameLoc) { 10503 DeclContext *NamedContext = computeDeclContext(SS); 10504 10505 if (!CurContext->isRecord()) { 10506 // C++03 [namespace.udecl]p3: 10507 // C++0x [namespace.udecl]p8: 10508 // A using-declaration for a class member shall be a member-declaration. 10509 10510 // If we weren't able to compute a valid scope, it might validly be a 10511 // dependent class scope or a dependent enumeration unscoped scope. If 10512 // we have a 'typename' keyword, the scope must resolve to a class type. 10513 if ((HasTypename && !NamedContext) || 10514 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 10515 auto *RD = NamedContext 10516 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 10517 : nullptr; 10518 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 10519 RD = nullptr; 10520 10521 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 10522 << SS.getRange(); 10523 10524 // If we have a complete, non-dependent source type, try to suggest a 10525 // way to get the same effect. 10526 if (!RD) 10527 return true; 10528 10529 // Find what this using-declaration was referring to. 10530 LookupResult R(*this, NameInfo, LookupOrdinaryName); 10531 R.setHideTags(false); 10532 R.suppressDiagnostics(); 10533 LookupQualifiedName(R, RD); 10534 10535 if (R.getAsSingle<TypeDecl>()) { 10536 if (getLangOpts().CPlusPlus11) { 10537 // Convert 'using X::Y;' to 'using Y = X::Y;'. 10538 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 10539 << 0 // alias declaration 10540 << FixItHint::CreateInsertion(SS.getBeginLoc(), 10541 NameInfo.getName().getAsString() + 10542 " = "); 10543 } else { 10544 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 10545 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 10546 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 10547 << 1 // typedef declaration 10548 << FixItHint::CreateReplacement(UsingLoc, "typedef") 10549 << FixItHint::CreateInsertion( 10550 InsertLoc, " " + NameInfo.getName().getAsString()); 10551 } 10552 } else if (R.getAsSingle<VarDecl>()) { 10553 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10554 // repeating the type of the static data member here. 10555 FixItHint FixIt; 10556 if (getLangOpts().CPlusPlus11) { 10557 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10558 FixIt = FixItHint::CreateReplacement( 10559 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 10560 } 10561 10562 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10563 << 2 // reference declaration 10564 << FixIt; 10565 } else if (R.getAsSingle<EnumConstantDecl>()) { 10566 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10567 // repeating the type of the enumeration here, and we can't do so if 10568 // the type is anonymous. 10569 FixItHint FixIt; 10570 if (getLangOpts().CPlusPlus11) { 10571 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10572 FixIt = FixItHint::CreateReplacement( 10573 UsingLoc, 10574 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 10575 } 10576 10577 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10578 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 10579 << FixIt; 10580 } 10581 return true; 10582 } 10583 10584 // Otherwise, this might be valid. 10585 return false; 10586 } 10587 10588 // The current scope is a record. 10589 10590 // If the named context is dependent, we can't decide much. 10591 if (!NamedContext) { 10592 // FIXME: in C++0x, we can diagnose if we can prove that the 10593 // nested-name-specifier does not refer to a base class, which is 10594 // still possible in some cases. 10595 10596 // Otherwise we have to conservatively report that things might be 10597 // okay. 10598 return false; 10599 } 10600 10601 if (!NamedContext->isRecord()) { 10602 // Ideally this would point at the last name in the specifier, 10603 // but we don't have that level of source info. 10604 Diag(SS.getRange().getBegin(), 10605 diag::err_using_decl_nested_name_specifier_is_not_class) 10606 << SS.getScopeRep() << SS.getRange(); 10607 return true; 10608 } 10609 10610 if (!NamedContext->isDependentContext() && 10611 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 10612 return true; 10613 10614 if (getLangOpts().CPlusPlus11) { 10615 // C++11 [namespace.udecl]p3: 10616 // In a using-declaration used as a member-declaration, the 10617 // nested-name-specifier shall name a base class of the class 10618 // being defined. 10619 10620 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 10621 cast<CXXRecordDecl>(NamedContext))) { 10622 if (CurContext == NamedContext) { 10623 Diag(NameLoc, 10624 diag::err_using_decl_nested_name_specifier_is_current_class) 10625 << SS.getRange(); 10626 return true; 10627 } 10628 10629 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 10630 Diag(SS.getRange().getBegin(), 10631 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10632 << SS.getScopeRep() 10633 << cast<CXXRecordDecl>(CurContext) 10634 << SS.getRange(); 10635 } 10636 return true; 10637 } 10638 10639 return false; 10640 } 10641 10642 // C++03 [namespace.udecl]p4: 10643 // A using-declaration used as a member-declaration shall refer 10644 // to a member of a base class of the class being defined [etc.]. 10645 10646 // Salient point: SS doesn't have to name a base class as long as 10647 // lookup only finds members from base classes. Therefore we can 10648 // diagnose here only if we can prove that that can't happen, 10649 // i.e. if the class hierarchies provably don't intersect. 10650 10651 // TODO: it would be nice if "definitely valid" results were cached 10652 // in the UsingDecl and UsingShadowDecl so that these checks didn't 10653 // need to be repeated. 10654 10655 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 10656 auto Collect = [&Bases](const CXXRecordDecl *Base) { 10657 Bases.insert(Base); 10658 return true; 10659 }; 10660 10661 // Collect all bases. Return false if we find a dependent base. 10662 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 10663 return false; 10664 10665 // Returns true if the base is dependent or is one of the accumulated base 10666 // classes. 10667 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 10668 return !Bases.count(Base); 10669 }; 10670 10671 // Return false if the class has a dependent base or if it or one 10672 // of its bases is present in the base set of the current context. 10673 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 10674 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 10675 return false; 10676 10677 Diag(SS.getRange().getBegin(), 10678 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10679 << SS.getScopeRep() 10680 << cast<CXXRecordDecl>(CurContext) 10681 << SS.getRange(); 10682 10683 return true; 10684 } 10685 10686 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 10687 MultiTemplateParamsArg TemplateParamLists, 10688 SourceLocation UsingLoc, UnqualifiedId &Name, 10689 const ParsedAttributesView &AttrList, 10690 TypeResult Type, Decl *DeclFromDeclSpec) { 10691 // Skip up to the relevant declaration scope. 10692 while (S->isTemplateParamScope()) 10693 S = S->getParent(); 10694 assert((S->getFlags() & Scope::DeclScope) && 10695 "got alias-declaration outside of declaration scope"); 10696 10697 if (Type.isInvalid()) 10698 return nullptr; 10699 10700 bool Invalid = false; 10701 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 10702 TypeSourceInfo *TInfo = nullptr; 10703 GetTypeFromParser(Type.get(), &TInfo); 10704 10705 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 10706 return nullptr; 10707 10708 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 10709 UPPC_DeclarationType)) { 10710 Invalid = true; 10711 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10712 TInfo->getTypeLoc().getBeginLoc()); 10713 } 10714 10715 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10716 TemplateParamLists.size() 10717 ? forRedeclarationInCurContext() 10718 : ForVisibleRedeclaration); 10719 LookupName(Previous, S); 10720 10721 // Warn about shadowing the name of a template parameter. 10722 if (Previous.isSingleResult() && 10723 Previous.getFoundDecl()->isTemplateParameter()) { 10724 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 10725 Previous.clear(); 10726 } 10727 10728 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 10729 "name in alias declaration must be an identifier"); 10730 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 10731 Name.StartLocation, 10732 Name.Identifier, TInfo); 10733 10734 NewTD->setAccess(AS); 10735 10736 if (Invalid) 10737 NewTD->setInvalidDecl(); 10738 10739 ProcessDeclAttributeList(S, NewTD, AttrList); 10740 AddPragmaAttributes(S, NewTD); 10741 10742 CheckTypedefForVariablyModifiedType(S, NewTD); 10743 Invalid |= NewTD->isInvalidDecl(); 10744 10745 bool Redeclaration = false; 10746 10747 NamedDecl *NewND; 10748 if (TemplateParamLists.size()) { 10749 TypeAliasTemplateDecl *OldDecl = nullptr; 10750 TemplateParameterList *OldTemplateParams = nullptr; 10751 10752 if (TemplateParamLists.size() != 1) { 10753 Diag(UsingLoc, diag::err_alias_template_extra_headers) 10754 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 10755 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 10756 } 10757 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 10758 10759 // Check that we can declare a template here. 10760 if (CheckTemplateDeclScope(S, TemplateParams)) 10761 return nullptr; 10762 10763 // Only consider previous declarations in the same scope. 10764 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 10765 /*ExplicitInstantiationOrSpecialization*/false); 10766 if (!Previous.empty()) { 10767 Redeclaration = true; 10768 10769 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 10770 if (!OldDecl && !Invalid) { 10771 Diag(UsingLoc, diag::err_redefinition_different_kind) 10772 << Name.Identifier; 10773 10774 NamedDecl *OldD = Previous.getRepresentativeDecl(); 10775 if (OldD->getLocation().isValid()) 10776 Diag(OldD->getLocation(), diag::note_previous_definition); 10777 10778 Invalid = true; 10779 } 10780 10781 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 10782 if (TemplateParameterListsAreEqual(TemplateParams, 10783 OldDecl->getTemplateParameters(), 10784 /*Complain=*/true, 10785 TPL_TemplateMatch)) 10786 OldTemplateParams = 10787 OldDecl->getMostRecentDecl()->getTemplateParameters(); 10788 else 10789 Invalid = true; 10790 10791 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 10792 if (!Invalid && 10793 !Context.hasSameType(OldTD->getUnderlyingType(), 10794 NewTD->getUnderlyingType())) { 10795 // FIXME: The C++0x standard does not clearly say this is ill-formed, 10796 // but we can't reasonably accept it. 10797 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 10798 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 10799 if (OldTD->getLocation().isValid()) 10800 Diag(OldTD->getLocation(), diag::note_previous_definition); 10801 Invalid = true; 10802 } 10803 } 10804 } 10805 10806 // Merge any previous default template arguments into our parameters, 10807 // and check the parameter list. 10808 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 10809 TPC_TypeAliasTemplate)) 10810 return nullptr; 10811 10812 TypeAliasTemplateDecl *NewDecl = 10813 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 10814 Name.Identifier, TemplateParams, 10815 NewTD); 10816 NewTD->setDescribedAliasTemplate(NewDecl); 10817 10818 NewDecl->setAccess(AS); 10819 10820 if (Invalid) 10821 NewDecl->setInvalidDecl(); 10822 else if (OldDecl) { 10823 NewDecl->setPreviousDecl(OldDecl); 10824 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 10825 } 10826 10827 NewND = NewDecl; 10828 } else { 10829 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 10830 setTagNameForLinkagePurposes(TD, NewTD); 10831 handleTagNumbering(TD, S); 10832 } 10833 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 10834 NewND = NewTD; 10835 } 10836 10837 PushOnScopeChains(NewND, S); 10838 ActOnDocumentableDecl(NewND); 10839 return NewND; 10840 } 10841 10842 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 10843 SourceLocation AliasLoc, 10844 IdentifierInfo *Alias, CXXScopeSpec &SS, 10845 SourceLocation IdentLoc, 10846 IdentifierInfo *Ident) { 10847 10848 // Lookup the namespace name. 10849 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 10850 LookupParsedName(R, S, &SS); 10851 10852 if (R.isAmbiguous()) 10853 return nullptr; 10854 10855 if (R.empty()) { 10856 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 10857 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 10858 return nullptr; 10859 } 10860 } 10861 assert(!R.isAmbiguous() && !R.empty()); 10862 NamedDecl *ND = R.getRepresentativeDecl(); 10863 10864 // Check if we have a previous declaration with the same name. 10865 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 10866 ForVisibleRedeclaration); 10867 LookupName(PrevR, S); 10868 10869 // Check we're not shadowing a template parameter. 10870 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 10871 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 10872 PrevR.clear(); 10873 } 10874 10875 // Filter out any other lookup result from an enclosing scope. 10876 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 10877 /*AllowInlineNamespace*/false); 10878 10879 // Find the previous declaration and check that we can redeclare it. 10880 NamespaceAliasDecl *Prev = nullptr; 10881 if (PrevR.isSingleResult()) { 10882 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 10883 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 10884 // We already have an alias with the same name that points to the same 10885 // namespace; check that it matches. 10886 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 10887 Prev = AD; 10888 } else if (isVisible(PrevDecl)) { 10889 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 10890 << Alias; 10891 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 10892 << AD->getNamespace(); 10893 return nullptr; 10894 } 10895 } else if (isVisible(PrevDecl)) { 10896 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 10897 ? diag::err_redefinition 10898 : diag::err_redefinition_different_kind; 10899 Diag(AliasLoc, DiagID) << Alias; 10900 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10901 return nullptr; 10902 } 10903 } 10904 10905 // The use of a nested name specifier may trigger deprecation warnings. 10906 DiagnoseUseOfDecl(ND, IdentLoc); 10907 10908 NamespaceAliasDecl *AliasDecl = 10909 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 10910 Alias, SS.getWithLocInContext(Context), 10911 IdentLoc, ND); 10912 if (Prev) 10913 AliasDecl->setPreviousDecl(Prev); 10914 10915 PushOnScopeChains(AliasDecl, S); 10916 return AliasDecl; 10917 } 10918 10919 namespace { 10920 struct SpecialMemberExceptionSpecInfo 10921 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 10922 SourceLocation Loc; 10923 Sema::ImplicitExceptionSpecification ExceptSpec; 10924 10925 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 10926 Sema::CXXSpecialMember CSM, 10927 Sema::InheritedConstructorInfo *ICI, 10928 SourceLocation Loc) 10929 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 10930 10931 bool visitBase(CXXBaseSpecifier *Base); 10932 bool visitField(FieldDecl *FD); 10933 10934 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 10935 unsigned Quals); 10936 10937 void visitSubobjectCall(Subobject Subobj, 10938 Sema::SpecialMemberOverloadResult SMOR); 10939 }; 10940 } 10941 10942 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 10943 auto *RT = Base->getType()->getAs<RecordType>(); 10944 if (!RT) 10945 return false; 10946 10947 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 10948 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 10949 if (auto *BaseCtor = SMOR.getMethod()) { 10950 visitSubobjectCall(Base, BaseCtor); 10951 return false; 10952 } 10953 10954 visitClassSubobject(BaseClass, Base, 0); 10955 return false; 10956 } 10957 10958 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 10959 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 10960 Expr *E = FD->getInClassInitializer(); 10961 if (!E) 10962 // FIXME: It's a little wasteful to build and throw away a 10963 // CXXDefaultInitExpr here. 10964 // FIXME: We should have a single context note pointing at Loc, and 10965 // this location should be MD->getLocation() instead, since that's 10966 // the location where we actually use the default init expression. 10967 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 10968 if (E) 10969 ExceptSpec.CalledExpr(E); 10970 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 10971 ->getAs<RecordType>()) { 10972 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 10973 FD->getType().getCVRQualifiers()); 10974 } 10975 return false; 10976 } 10977 10978 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 10979 Subobject Subobj, 10980 unsigned Quals) { 10981 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 10982 bool IsMutable = Field && Field->isMutable(); 10983 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 10984 } 10985 10986 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 10987 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 10988 // Note, if lookup fails, it doesn't matter what exception specification we 10989 // choose because the special member will be deleted. 10990 if (CXXMethodDecl *MD = SMOR.getMethod()) 10991 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 10992 } 10993 10994 namespace { 10995 /// RAII object to register a special member as being currently declared. 10996 struct ComputingExceptionSpec { 10997 Sema &S; 10998 10999 ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc) 11000 : S(S) { 11001 Sema::CodeSynthesisContext Ctx; 11002 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 11003 Ctx.PointOfInstantiation = Loc; 11004 Ctx.Entity = MD; 11005 S.pushCodeSynthesisContext(Ctx); 11006 } 11007 ~ComputingExceptionSpec() { 11008 S.popCodeSynthesisContext(); 11009 } 11010 }; 11011 } 11012 11013 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 11014 llvm::APSInt Result; 11015 ExprResult Converted = CheckConvertedConstantExpression( 11016 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 11017 ExplicitSpec.setExpr(Converted.get()); 11018 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 11019 ExplicitSpec.setKind(Result.getBoolValue() 11020 ? ExplicitSpecKind::ResolvedTrue 11021 : ExplicitSpecKind::ResolvedFalse); 11022 return true; 11023 } 11024 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 11025 return false; 11026 } 11027 11028 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 11029 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 11030 if (!ExplicitExpr->isTypeDependent()) 11031 tryResolveExplicitSpecifier(ES); 11032 return ES; 11033 } 11034 11035 static Sema::ImplicitExceptionSpecification 11036 ComputeDefaultedSpecialMemberExceptionSpec( 11037 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 11038 Sema::InheritedConstructorInfo *ICI) { 11039 ComputingExceptionSpec CES(S, MD, Loc); 11040 11041 CXXRecordDecl *ClassDecl = MD->getParent(); 11042 11043 // C++ [except.spec]p14: 11044 // An implicitly declared special member function (Clause 12) shall have an 11045 // exception-specification. [...] 11046 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 11047 if (ClassDecl->isInvalidDecl()) 11048 return Info.ExceptSpec; 11049 11050 // FIXME: If this diagnostic fires, we're probably missing a check for 11051 // attempting to resolve an exception specification before it's known 11052 // at a higher level. 11053 if (S.RequireCompleteType(MD->getLocation(), 11054 S.Context.getRecordType(ClassDecl), 11055 diag::err_exception_spec_incomplete_type)) 11056 return Info.ExceptSpec; 11057 11058 // C++1z [except.spec]p7: 11059 // [Look for exceptions thrown by] a constructor selected [...] to 11060 // initialize a potentially constructed subobject, 11061 // C++1z [except.spec]p8: 11062 // The exception specification for an implicitly-declared destructor, or a 11063 // destructor without a noexcept-specifier, is potentially-throwing if and 11064 // only if any of the destructors for any of its potentially constructed 11065 // subojects is potentially throwing. 11066 // FIXME: We respect the first rule but ignore the "potentially constructed" 11067 // in the second rule to resolve a core issue (no number yet) that would have 11068 // us reject: 11069 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 11070 // struct B : A {}; 11071 // struct C : B { void f(); }; 11072 // ... due to giving B::~B() a non-throwing exception specification. 11073 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 11074 : Info.VisitAllBases); 11075 11076 return Info.ExceptSpec; 11077 } 11078 11079 namespace { 11080 /// RAII object to register a special member as being currently declared. 11081 struct DeclaringSpecialMember { 11082 Sema &S; 11083 Sema::SpecialMemberDecl D; 11084 Sema::ContextRAII SavedContext; 11085 bool WasAlreadyBeingDeclared; 11086 11087 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 11088 : S(S), D(RD, CSM), SavedContext(S, RD) { 11089 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 11090 if (WasAlreadyBeingDeclared) 11091 // This almost never happens, but if it does, ensure that our cache 11092 // doesn't contain a stale result. 11093 S.SpecialMemberCache.clear(); 11094 else { 11095 // Register a note to be produced if we encounter an error while 11096 // declaring the special member. 11097 Sema::CodeSynthesisContext Ctx; 11098 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 11099 // FIXME: We don't have a location to use here. Using the class's 11100 // location maintains the fiction that we declare all special members 11101 // with the class, but (1) it's not clear that lying about that helps our 11102 // users understand what's going on, and (2) there may be outer contexts 11103 // on the stack (some of which are relevant) and printing them exposes 11104 // our lies. 11105 Ctx.PointOfInstantiation = RD->getLocation(); 11106 Ctx.Entity = RD; 11107 Ctx.SpecialMember = CSM; 11108 S.pushCodeSynthesisContext(Ctx); 11109 } 11110 } 11111 ~DeclaringSpecialMember() { 11112 if (!WasAlreadyBeingDeclared) { 11113 S.SpecialMembersBeingDeclared.erase(D); 11114 S.popCodeSynthesisContext(); 11115 } 11116 } 11117 11118 /// Are we already trying to declare this special member? 11119 bool isAlreadyBeingDeclared() const { 11120 return WasAlreadyBeingDeclared; 11121 } 11122 }; 11123 } 11124 11125 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 11126 // Look up any existing declarations, but don't trigger declaration of all 11127 // implicit special members with this name. 11128 DeclarationName Name = FD->getDeclName(); 11129 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 11130 ForExternalRedeclaration); 11131 for (auto *D : FD->getParent()->lookup(Name)) 11132 if (auto *Acceptable = R.getAcceptableDecl(D)) 11133 R.addDecl(Acceptable); 11134 R.resolveKind(); 11135 R.suppressDiagnostics(); 11136 11137 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 11138 } 11139 11140 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 11141 QualType ResultTy, 11142 ArrayRef<QualType> Args) { 11143 // Build an exception specification pointing back at this constructor. 11144 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 11145 11146 if (getLangOpts().OpenCLCPlusPlus) { 11147 // OpenCL: Implicitly defaulted special member are of the generic address 11148 // space. 11149 EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic); 11150 } 11151 11152 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 11153 SpecialMem->setType(QT); 11154 } 11155 11156 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 11157 CXXRecordDecl *ClassDecl) { 11158 // C++ [class.ctor]p5: 11159 // A default constructor for a class X is a constructor of class X 11160 // that can be called without an argument. If there is no 11161 // user-declared constructor for class X, a default constructor is 11162 // implicitly declared. An implicitly-declared default constructor 11163 // is an inline public member of its class. 11164 assert(ClassDecl->needsImplicitDefaultConstructor() && 11165 "Should not build implicit default constructor!"); 11166 11167 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 11168 if (DSM.isAlreadyBeingDeclared()) 11169 return nullptr; 11170 11171 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11172 CXXDefaultConstructor, 11173 false); 11174 11175 // Create the actual constructor declaration. 11176 CanQualType ClassType 11177 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 11178 SourceLocation ClassLoc = ClassDecl->getLocation(); 11179 DeclarationName Name 11180 = Context.DeclarationNames.getCXXConstructorName(ClassType); 11181 DeclarationNameInfo NameInfo(Name, ClassLoc); 11182 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 11183 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 11184 /*TInfo=*/nullptr, ExplicitSpecifier(), 11185 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 11186 Constexpr ? CSK_constexpr : CSK_unspecified); 11187 DefaultCon->setAccess(AS_public); 11188 DefaultCon->setDefaulted(); 11189 11190 if (getLangOpts().CUDA) { 11191 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 11192 DefaultCon, 11193 /* ConstRHS */ false, 11194 /* Diagnose */ false); 11195 } 11196 11197 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 11198 11199 // We don't need to use SpecialMemberIsTrivial here; triviality for default 11200 // constructors is easy to compute. 11201 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 11202 11203 // Note that we have declared this constructor. 11204 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 11205 11206 Scope *S = getScopeForContext(ClassDecl); 11207 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 11208 11209 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 11210 SetDeclDeleted(DefaultCon, ClassLoc); 11211 11212 if (S) 11213 PushOnScopeChains(DefaultCon, S, false); 11214 ClassDecl->addDecl(DefaultCon); 11215 11216 return DefaultCon; 11217 } 11218 11219 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 11220 CXXConstructorDecl *Constructor) { 11221 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 11222 !Constructor->doesThisDeclarationHaveABody() && 11223 !Constructor->isDeleted()) && 11224 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 11225 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 11226 return; 11227 11228 CXXRecordDecl *ClassDecl = Constructor->getParent(); 11229 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 11230 11231 SynthesizedFunctionScope Scope(*this, Constructor); 11232 11233 // The exception specification is needed because we are defining the 11234 // function. 11235 ResolveExceptionSpec(CurrentLocation, 11236 Constructor->getType()->castAs<FunctionProtoType>()); 11237 MarkVTableUsed(CurrentLocation, ClassDecl); 11238 11239 // Add a context note for diagnostics produced after this point. 11240 Scope.addContextNote(CurrentLocation); 11241 11242 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 11243 Constructor->setInvalidDecl(); 11244 return; 11245 } 11246 11247 SourceLocation Loc = Constructor->getEndLoc().isValid() 11248 ? Constructor->getEndLoc() 11249 : Constructor->getLocation(); 11250 Constructor->setBody(new (Context) CompoundStmt(Loc)); 11251 Constructor->markUsed(Context); 11252 11253 if (ASTMutationListener *L = getASTMutationListener()) { 11254 L->CompletedImplicitDefinition(Constructor); 11255 } 11256 11257 DiagnoseUninitializedFields(*this, Constructor); 11258 } 11259 11260 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 11261 // Perform any delayed checks on exception specifications. 11262 CheckDelayedMemberExceptionSpecs(); 11263 } 11264 11265 /// Find or create the fake constructor we synthesize to model constructing an 11266 /// object of a derived class via a constructor of a base class. 11267 CXXConstructorDecl * 11268 Sema::findInheritingConstructor(SourceLocation Loc, 11269 CXXConstructorDecl *BaseCtor, 11270 ConstructorUsingShadowDecl *Shadow) { 11271 CXXRecordDecl *Derived = Shadow->getParent(); 11272 SourceLocation UsingLoc = Shadow->getLocation(); 11273 11274 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 11275 // For now we use the name of the base class constructor as a member of the 11276 // derived class to indicate a (fake) inherited constructor name. 11277 DeclarationName Name = BaseCtor->getDeclName(); 11278 11279 // Check to see if we already have a fake constructor for this inherited 11280 // constructor call. 11281 for (NamedDecl *Ctor : Derived->lookup(Name)) 11282 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 11283 ->getInheritedConstructor() 11284 .getConstructor(), 11285 BaseCtor)) 11286 return cast<CXXConstructorDecl>(Ctor); 11287 11288 DeclarationNameInfo NameInfo(Name, UsingLoc); 11289 TypeSourceInfo *TInfo = 11290 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 11291 FunctionProtoTypeLoc ProtoLoc = 11292 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 11293 11294 // Check the inherited constructor is valid and find the list of base classes 11295 // from which it was inherited. 11296 InheritedConstructorInfo ICI(*this, Loc, Shadow); 11297 11298 bool Constexpr = 11299 BaseCtor->isConstexpr() && 11300 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 11301 false, BaseCtor, &ICI); 11302 11303 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 11304 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 11305 BaseCtor->getExplicitSpecifier(), /*isInline=*/true, 11306 /*isImplicitlyDeclared=*/true, 11307 Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified, 11308 InheritedConstructor(Shadow, BaseCtor)); 11309 if (Shadow->isInvalidDecl()) 11310 DerivedCtor->setInvalidDecl(); 11311 11312 // Build an unevaluated exception specification for this fake constructor. 11313 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 11314 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11315 EPI.ExceptionSpec.Type = EST_Unevaluated; 11316 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 11317 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 11318 FPT->getParamTypes(), EPI)); 11319 11320 // Build the parameter declarations. 11321 SmallVector<ParmVarDecl *, 16> ParamDecls; 11322 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 11323 TypeSourceInfo *TInfo = 11324 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 11325 ParmVarDecl *PD = ParmVarDecl::Create( 11326 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 11327 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 11328 PD->setScopeInfo(0, I); 11329 PD->setImplicit(); 11330 // Ensure attributes are propagated onto parameters (this matters for 11331 // format, pass_object_size, ...). 11332 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 11333 ParamDecls.push_back(PD); 11334 ProtoLoc.setParam(I, PD); 11335 } 11336 11337 // Set up the new constructor. 11338 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 11339 DerivedCtor->setAccess(BaseCtor->getAccess()); 11340 DerivedCtor->setParams(ParamDecls); 11341 Derived->addDecl(DerivedCtor); 11342 11343 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 11344 SetDeclDeleted(DerivedCtor, UsingLoc); 11345 11346 return DerivedCtor; 11347 } 11348 11349 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 11350 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 11351 Ctor->getInheritedConstructor().getShadowDecl()); 11352 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 11353 /*Diagnose*/true); 11354 } 11355 11356 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 11357 CXXConstructorDecl *Constructor) { 11358 CXXRecordDecl *ClassDecl = Constructor->getParent(); 11359 assert(Constructor->getInheritedConstructor() && 11360 !Constructor->doesThisDeclarationHaveABody() && 11361 !Constructor->isDeleted()); 11362 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 11363 return; 11364 11365 // Initializations are performed "as if by a defaulted default constructor", 11366 // so enter the appropriate scope. 11367 SynthesizedFunctionScope Scope(*this, Constructor); 11368 11369 // The exception specification is needed because we are defining the 11370 // function. 11371 ResolveExceptionSpec(CurrentLocation, 11372 Constructor->getType()->castAs<FunctionProtoType>()); 11373 MarkVTableUsed(CurrentLocation, ClassDecl); 11374 11375 // Add a context note for diagnostics produced after this point. 11376 Scope.addContextNote(CurrentLocation); 11377 11378 ConstructorUsingShadowDecl *Shadow = 11379 Constructor->getInheritedConstructor().getShadowDecl(); 11380 CXXConstructorDecl *InheritedCtor = 11381 Constructor->getInheritedConstructor().getConstructor(); 11382 11383 // [class.inhctor.init]p1: 11384 // initialization proceeds as if a defaulted default constructor is used to 11385 // initialize the D object and each base class subobject from which the 11386 // constructor was inherited 11387 11388 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 11389 CXXRecordDecl *RD = Shadow->getParent(); 11390 SourceLocation InitLoc = Shadow->getLocation(); 11391 11392 // Build explicit initializers for all base classes from which the 11393 // constructor was inherited. 11394 SmallVector<CXXCtorInitializer*, 8> Inits; 11395 for (bool VBase : {false, true}) { 11396 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 11397 if (B.isVirtual() != VBase) 11398 continue; 11399 11400 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 11401 if (!BaseRD) 11402 continue; 11403 11404 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 11405 if (!BaseCtor.first) 11406 continue; 11407 11408 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 11409 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 11410 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 11411 11412 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 11413 Inits.push_back(new (Context) CXXCtorInitializer( 11414 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 11415 SourceLocation())); 11416 } 11417 } 11418 11419 // We now proceed as if for a defaulted default constructor, with the relevant 11420 // initializers replaced. 11421 11422 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 11423 Constructor->setInvalidDecl(); 11424 return; 11425 } 11426 11427 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 11428 Constructor->markUsed(Context); 11429 11430 if (ASTMutationListener *L = getASTMutationListener()) { 11431 L->CompletedImplicitDefinition(Constructor); 11432 } 11433 11434 DiagnoseUninitializedFields(*this, Constructor); 11435 } 11436 11437 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 11438 // C++ [class.dtor]p2: 11439 // If a class has no user-declared destructor, a destructor is 11440 // declared implicitly. An implicitly-declared destructor is an 11441 // inline public member of its class. 11442 assert(ClassDecl->needsImplicitDestructor()); 11443 11444 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 11445 if (DSM.isAlreadyBeingDeclared()) 11446 return nullptr; 11447 11448 // Create the actual destructor declaration. 11449 CanQualType ClassType 11450 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 11451 SourceLocation ClassLoc = ClassDecl->getLocation(); 11452 DeclarationName Name 11453 = Context.DeclarationNames.getCXXDestructorName(ClassType); 11454 DeclarationNameInfo NameInfo(Name, ClassLoc); 11455 CXXDestructorDecl *Destructor 11456 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 11457 QualType(), nullptr, /*isInline=*/true, 11458 /*isImplicitlyDeclared=*/true); 11459 Destructor->setAccess(AS_public); 11460 Destructor->setDefaulted(); 11461 11462 if (getLangOpts().CUDA) { 11463 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 11464 Destructor, 11465 /* ConstRHS */ false, 11466 /* Diagnose */ false); 11467 } 11468 11469 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 11470 11471 // We don't need to use SpecialMemberIsTrivial here; triviality for 11472 // destructors is easy to compute. 11473 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 11474 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 11475 ClassDecl->hasTrivialDestructorForCall()); 11476 11477 // Note that we have declared this destructor. 11478 ++getASTContext().NumImplicitDestructorsDeclared; 11479 11480 Scope *S = getScopeForContext(ClassDecl); 11481 CheckImplicitSpecialMemberDeclaration(S, Destructor); 11482 11483 // We can't check whether an implicit destructor is deleted before we complete 11484 // the definition of the class, because its validity depends on the alignment 11485 // of the class. We'll check this from ActOnFields once the class is complete. 11486 if (ClassDecl->isCompleteDefinition() && 11487 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 11488 SetDeclDeleted(Destructor, ClassLoc); 11489 11490 // Introduce this destructor into its scope. 11491 if (S) 11492 PushOnScopeChains(Destructor, S, false); 11493 ClassDecl->addDecl(Destructor); 11494 11495 return Destructor; 11496 } 11497 11498 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 11499 CXXDestructorDecl *Destructor) { 11500 assert((Destructor->isDefaulted() && 11501 !Destructor->doesThisDeclarationHaveABody() && 11502 !Destructor->isDeleted()) && 11503 "DefineImplicitDestructor - call it for implicit default dtor"); 11504 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 11505 return; 11506 11507 CXXRecordDecl *ClassDecl = Destructor->getParent(); 11508 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 11509 11510 SynthesizedFunctionScope Scope(*this, Destructor); 11511 11512 // The exception specification is needed because we are defining the 11513 // function. 11514 ResolveExceptionSpec(CurrentLocation, 11515 Destructor->getType()->castAs<FunctionProtoType>()); 11516 MarkVTableUsed(CurrentLocation, ClassDecl); 11517 11518 // Add a context note for diagnostics produced after this point. 11519 Scope.addContextNote(CurrentLocation); 11520 11521 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 11522 Destructor->getParent()); 11523 11524 if (CheckDestructor(Destructor)) { 11525 Destructor->setInvalidDecl(); 11526 return; 11527 } 11528 11529 SourceLocation Loc = Destructor->getEndLoc().isValid() 11530 ? Destructor->getEndLoc() 11531 : Destructor->getLocation(); 11532 Destructor->setBody(new (Context) CompoundStmt(Loc)); 11533 Destructor->markUsed(Context); 11534 11535 if (ASTMutationListener *L = getASTMutationListener()) { 11536 L->CompletedImplicitDefinition(Destructor); 11537 } 11538 } 11539 11540 /// Perform any semantic analysis which needs to be delayed until all 11541 /// pending class member declarations have been parsed. 11542 void Sema::ActOnFinishCXXMemberDecls() { 11543 // If the context is an invalid C++ class, just suppress these checks. 11544 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 11545 if (Record->isInvalidDecl()) { 11546 DelayedOverridingExceptionSpecChecks.clear(); 11547 DelayedEquivalentExceptionSpecChecks.clear(); 11548 return; 11549 } 11550 checkForMultipleExportedDefaultConstructors(*this, Record); 11551 } 11552 } 11553 11554 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 11555 referenceDLLExportedClassMethods(); 11556 11557 if (!DelayedDllExportMemberFunctions.empty()) { 11558 SmallVector<CXXMethodDecl*, 4> WorkList; 11559 std::swap(DelayedDllExportMemberFunctions, WorkList); 11560 for (CXXMethodDecl *M : WorkList) { 11561 DefineImplicitSpecialMember(*this, M, M->getLocation()); 11562 11563 // Pass the method to the consumer to get emitted. This is not necessary 11564 // for explicit instantiation definitions, as they will get emitted 11565 // anyway. 11566 if (M->getParent()->getTemplateSpecializationKind() != 11567 TSK_ExplicitInstantiationDefinition) 11568 ActOnFinishInlineFunctionDef(M); 11569 } 11570 } 11571 } 11572 11573 void Sema::referenceDLLExportedClassMethods() { 11574 if (!DelayedDllExportClasses.empty()) { 11575 // Calling ReferenceDllExportedMembers might cause the current function to 11576 // be called again, so use a local copy of DelayedDllExportClasses. 11577 SmallVector<CXXRecordDecl *, 4> WorkList; 11578 std::swap(DelayedDllExportClasses, WorkList); 11579 for (CXXRecordDecl *Class : WorkList) 11580 ReferenceDllExportedMembers(*this, Class); 11581 } 11582 } 11583 11584 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 11585 assert(getLangOpts().CPlusPlus11 && 11586 "adjusting dtor exception specs was introduced in c++11"); 11587 11588 if (Destructor->isDependentContext()) 11589 return; 11590 11591 // C++11 [class.dtor]p3: 11592 // A declaration of a destructor that does not have an exception- 11593 // specification is implicitly considered to have the same exception- 11594 // specification as an implicit declaration. 11595 const FunctionProtoType *DtorType = Destructor->getType()-> 11596 getAs<FunctionProtoType>(); 11597 if (DtorType->hasExceptionSpec()) 11598 return; 11599 11600 // Replace the destructor's type, building off the existing one. Fortunately, 11601 // the only thing of interest in the destructor type is its extended info. 11602 // The return and arguments are fixed. 11603 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 11604 EPI.ExceptionSpec.Type = EST_Unevaluated; 11605 EPI.ExceptionSpec.SourceDecl = Destructor; 11606 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 11607 11608 // FIXME: If the destructor has a body that could throw, and the newly created 11609 // spec doesn't allow exceptions, we should emit a warning, because this 11610 // change in behavior can break conforming C++03 programs at runtime. 11611 // However, we don't have a body or an exception specification yet, so it 11612 // needs to be done somewhere else. 11613 } 11614 11615 namespace { 11616 /// An abstract base class for all helper classes used in building the 11617 // copy/move operators. These classes serve as factory functions and help us 11618 // avoid using the same Expr* in the AST twice. 11619 class ExprBuilder { 11620 ExprBuilder(const ExprBuilder&) = delete; 11621 ExprBuilder &operator=(const ExprBuilder&) = delete; 11622 11623 protected: 11624 static Expr *assertNotNull(Expr *E) { 11625 assert(E && "Expression construction must not fail."); 11626 return E; 11627 } 11628 11629 public: 11630 ExprBuilder() {} 11631 virtual ~ExprBuilder() {} 11632 11633 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 11634 }; 11635 11636 class RefBuilder: public ExprBuilder { 11637 VarDecl *Var; 11638 QualType VarType; 11639 11640 public: 11641 Expr *build(Sema &S, SourceLocation Loc) const override { 11642 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 11643 } 11644 11645 RefBuilder(VarDecl *Var, QualType VarType) 11646 : Var(Var), VarType(VarType) {} 11647 }; 11648 11649 class ThisBuilder: public ExprBuilder { 11650 public: 11651 Expr *build(Sema &S, SourceLocation Loc) const override { 11652 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 11653 } 11654 }; 11655 11656 class CastBuilder: public ExprBuilder { 11657 const ExprBuilder &Builder; 11658 QualType Type; 11659 ExprValueKind Kind; 11660 const CXXCastPath &Path; 11661 11662 public: 11663 Expr *build(Sema &S, SourceLocation Loc) const override { 11664 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 11665 CK_UncheckedDerivedToBase, Kind, 11666 &Path).get()); 11667 } 11668 11669 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 11670 const CXXCastPath &Path) 11671 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 11672 }; 11673 11674 class DerefBuilder: public ExprBuilder { 11675 const ExprBuilder &Builder; 11676 11677 public: 11678 Expr *build(Sema &S, SourceLocation Loc) const override { 11679 return assertNotNull( 11680 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 11681 } 11682 11683 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11684 }; 11685 11686 class MemberBuilder: public ExprBuilder { 11687 const ExprBuilder &Builder; 11688 QualType Type; 11689 CXXScopeSpec SS; 11690 bool IsArrow; 11691 LookupResult &MemberLookup; 11692 11693 public: 11694 Expr *build(Sema &S, SourceLocation Loc) const override { 11695 return assertNotNull(S.BuildMemberReferenceExpr( 11696 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 11697 nullptr, MemberLookup, nullptr, nullptr).get()); 11698 } 11699 11700 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 11701 LookupResult &MemberLookup) 11702 : Builder(Builder), Type(Type), IsArrow(IsArrow), 11703 MemberLookup(MemberLookup) {} 11704 }; 11705 11706 class MoveCastBuilder: public ExprBuilder { 11707 const ExprBuilder &Builder; 11708 11709 public: 11710 Expr *build(Sema &S, SourceLocation Loc) const override { 11711 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 11712 } 11713 11714 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11715 }; 11716 11717 class LvalueConvBuilder: public ExprBuilder { 11718 const ExprBuilder &Builder; 11719 11720 public: 11721 Expr *build(Sema &S, SourceLocation Loc) const override { 11722 return assertNotNull( 11723 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 11724 } 11725 11726 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11727 }; 11728 11729 class SubscriptBuilder: public ExprBuilder { 11730 const ExprBuilder &Base; 11731 const ExprBuilder &Index; 11732 11733 public: 11734 Expr *build(Sema &S, SourceLocation Loc) const override { 11735 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 11736 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 11737 } 11738 11739 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 11740 : Base(Base), Index(Index) {} 11741 }; 11742 11743 } // end anonymous namespace 11744 11745 /// When generating a defaulted copy or move assignment operator, if a field 11746 /// should be copied with __builtin_memcpy rather than via explicit assignments, 11747 /// do so. This optimization only applies for arrays of scalars, and for arrays 11748 /// of class type where the selected copy/move-assignment operator is trivial. 11749 static StmtResult 11750 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 11751 const ExprBuilder &ToB, const ExprBuilder &FromB) { 11752 // Compute the size of the memory buffer to be copied. 11753 QualType SizeType = S.Context.getSizeType(); 11754 llvm::APInt Size(S.Context.getTypeSize(SizeType), 11755 S.Context.getTypeSizeInChars(T).getQuantity()); 11756 11757 // Take the address of the field references for "from" and "to". We 11758 // directly construct UnaryOperators here because semantic analysis 11759 // does not permit us to take the address of an xvalue. 11760 Expr *From = FromB.build(S, Loc); 11761 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 11762 S.Context.getPointerType(From->getType()), 11763 VK_RValue, OK_Ordinary, Loc, false); 11764 Expr *To = ToB.build(S, Loc); 11765 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 11766 S.Context.getPointerType(To->getType()), 11767 VK_RValue, OK_Ordinary, Loc, false); 11768 11769 const Type *E = T->getBaseElementTypeUnsafe(); 11770 bool NeedsCollectableMemCpy = 11771 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 11772 11773 // Create a reference to the __builtin_objc_memmove_collectable function 11774 StringRef MemCpyName = NeedsCollectableMemCpy ? 11775 "__builtin_objc_memmove_collectable" : 11776 "__builtin_memcpy"; 11777 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 11778 Sema::LookupOrdinaryName); 11779 S.LookupName(R, S.TUScope, true); 11780 11781 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 11782 if (!MemCpy) 11783 // Something went horribly wrong earlier, and we will have complained 11784 // about it. 11785 return StmtError(); 11786 11787 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 11788 VK_RValue, Loc, nullptr); 11789 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 11790 11791 Expr *CallArgs[] = { 11792 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 11793 }; 11794 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 11795 Loc, CallArgs, Loc); 11796 11797 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 11798 return Call.getAs<Stmt>(); 11799 } 11800 11801 /// Builds a statement that copies/moves the given entity from \p From to 11802 /// \c To. 11803 /// 11804 /// This routine is used to copy/move the members of a class with an 11805 /// implicitly-declared copy/move assignment operator. When the entities being 11806 /// copied are arrays, this routine builds for loops to copy them. 11807 /// 11808 /// \param S The Sema object used for type-checking. 11809 /// 11810 /// \param Loc The location where the implicit copy/move is being generated. 11811 /// 11812 /// \param T The type of the expressions being copied/moved. Both expressions 11813 /// must have this type. 11814 /// 11815 /// \param To The expression we are copying/moving to. 11816 /// 11817 /// \param From The expression we are copying/moving from. 11818 /// 11819 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 11820 /// Otherwise, it's a non-static member subobject. 11821 /// 11822 /// \param Copying Whether we're copying or moving. 11823 /// 11824 /// \param Depth Internal parameter recording the depth of the recursion. 11825 /// 11826 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 11827 /// if a memcpy should be used instead. 11828 static StmtResult 11829 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 11830 const ExprBuilder &To, const ExprBuilder &From, 11831 bool CopyingBaseSubobject, bool Copying, 11832 unsigned Depth = 0) { 11833 // C++11 [class.copy]p28: 11834 // Each subobject is assigned in the manner appropriate to its type: 11835 // 11836 // - if the subobject is of class type, as if by a call to operator= with 11837 // the subobject as the object expression and the corresponding 11838 // subobject of x as a single function argument (as if by explicit 11839 // qualification; that is, ignoring any possible virtual overriding 11840 // functions in more derived classes); 11841 // 11842 // C++03 [class.copy]p13: 11843 // - if the subobject is of class type, the copy assignment operator for 11844 // the class is used (as if by explicit qualification; that is, 11845 // ignoring any possible virtual overriding functions in more derived 11846 // classes); 11847 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 11848 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 11849 11850 // Look for operator=. 11851 DeclarationName Name 11852 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11853 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 11854 S.LookupQualifiedName(OpLookup, ClassDecl, false); 11855 11856 // Prior to C++11, filter out any result that isn't a copy/move-assignment 11857 // operator. 11858 if (!S.getLangOpts().CPlusPlus11) { 11859 LookupResult::Filter F = OpLookup.makeFilter(); 11860 while (F.hasNext()) { 11861 NamedDecl *D = F.next(); 11862 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 11863 if (Method->isCopyAssignmentOperator() || 11864 (!Copying && Method->isMoveAssignmentOperator())) 11865 continue; 11866 11867 F.erase(); 11868 } 11869 F.done(); 11870 } 11871 11872 // Suppress the protected check (C++ [class.protected]) for each of the 11873 // assignment operators we found. This strange dance is required when 11874 // we're assigning via a base classes's copy-assignment operator. To 11875 // ensure that we're getting the right base class subobject (without 11876 // ambiguities), we need to cast "this" to that subobject type; to 11877 // ensure that we don't go through the virtual call mechanism, we need 11878 // to qualify the operator= name with the base class (see below). However, 11879 // this means that if the base class has a protected copy assignment 11880 // operator, the protected member access check will fail. So, we 11881 // rewrite "protected" access to "public" access in this case, since we 11882 // know by construction that we're calling from a derived class. 11883 if (CopyingBaseSubobject) { 11884 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 11885 L != LEnd; ++L) { 11886 if (L.getAccess() == AS_protected) 11887 L.setAccess(AS_public); 11888 } 11889 } 11890 11891 // Create the nested-name-specifier that will be used to qualify the 11892 // reference to operator=; this is required to suppress the virtual 11893 // call mechanism. 11894 CXXScopeSpec SS; 11895 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 11896 SS.MakeTrivial(S.Context, 11897 NestedNameSpecifier::Create(S.Context, nullptr, false, 11898 CanonicalT), 11899 Loc); 11900 11901 // Create the reference to operator=. 11902 ExprResult OpEqualRef 11903 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 11904 SS, /*TemplateKWLoc=*/SourceLocation(), 11905 /*FirstQualifierInScope=*/nullptr, 11906 OpLookup, 11907 /*TemplateArgs=*/nullptr, /*S*/nullptr, 11908 /*SuppressQualifierCheck=*/true); 11909 if (OpEqualRef.isInvalid()) 11910 return StmtError(); 11911 11912 // Build the call to the assignment operator. 11913 11914 Expr *FromInst = From.build(S, Loc); 11915 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 11916 OpEqualRef.getAs<Expr>(), 11917 Loc, FromInst, Loc); 11918 if (Call.isInvalid()) 11919 return StmtError(); 11920 11921 // If we built a call to a trivial 'operator=' while copying an array, 11922 // bail out. We'll replace the whole shebang with a memcpy. 11923 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 11924 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 11925 return StmtResult((Stmt*)nullptr); 11926 11927 // Convert to an expression-statement, and clean up any produced 11928 // temporaries. 11929 return S.ActOnExprStmt(Call); 11930 } 11931 11932 // - if the subobject is of scalar type, the built-in assignment 11933 // operator is used. 11934 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 11935 if (!ArrayTy) { 11936 ExprResult Assignment = S.CreateBuiltinBinOp( 11937 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 11938 if (Assignment.isInvalid()) 11939 return StmtError(); 11940 return S.ActOnExprStmt(Assignment); 11941 } 11942 11943 // - if the subobject is an array, each element is assigned, in the 11944 // manner appropriate to the element type; 11945 11946 // Construct a loop over the array bounds, e.g., 11947 // 11948 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 11949 // 11950 // that will copy each of the array elements. 11951 QualType SizeType = S.Context.getSizeType(); 11952 11953 // Create the iteration variable. 11954 IdentifierInfo *IterationVarName = nullptr; 11955 { 11956 SmallString<8> Str; 11957 llvm::raw_svector_ostream OS(Str); 11958 OS << "__i" << Depth; 11959 IterationVarName = &S.Context.Idents.get(OS.str()); 11960 } 11961 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11962 IterationVarName, SizeType, 11963 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11964 SC_None); 11965 11966 // Initialize the iteration variable to zero. 11967 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 11968 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 11969 11970 // Creates a reference to the iteration variable. 11971 RefBuilder IterationVarRef(IterationVar, SizeType); 11972 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 11973 11974 // Create the DeclStmt that holds the iteration variable. 11975 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 11976 11977 // Subscript the "from" and "to" expressions with the iteration variable. 11978 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 11979 MoveCastBuilder FromIndexMove(FromIndexCopy); 11980 const ExprBuilder *FromIndex; 11981 if (Copying) 11982 FromIndex = &FromIndexCopy; 11983 else 11984 FromIndex = &FromIndexMove; 11985 11986 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 11987 11988 // Build the copy/move for an individual element of the array. 11989 StmtResult Copy = 11990 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 11991 ToIndex, *FromIndex, CopyingBaseSubobject, 11992 Copying, Depth + 1); 11993 // Bail out if copying fails or if we determined that we should use memcpy. 11994 if (Copy.isInvalid() || !Copy.get()) 11995 return Copy; 11996 11997 // Create the comparison against the array bound. 11998 llvm::APInt Upper 11999 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 12000 Expr *Comparison 12001 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 12002 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 12003 BO_NE, S.Context.BoolTy, 12004 VK_RValue, OK_Ordinary, Loc, FPOptions()); 12005 12006 // Create the pre-increment of the iteration variable. We can determine 12007 // whether the increment will overflow based on the value of the array 12008 // bound. 12009 Expr *Increment = new (S.Context) 12010 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType, 12011 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue()); 12012 12013 // Construct the loop that copies all elements of this array. 12014 return S.ActOnForStmt( 12015 Loc, Loc, InitStmt, 12016 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 12017 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 12018 } 12019 12020 static StmtResult 12021 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 12022 const ExprBuilder &To, const ExprBuilder &From, 12023 bool CopyingBaseSubobject, bool Copying) { 12024 // Maybe we should use a memcpy? 12025 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 12026 T.isTriviallyCopyableType(S.Context)) 12027 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 12028 12029 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 12030 CopyingBaseSubobject, 12031 Copying, 0)); 12032 12033 // If we ended up picking a trivial assignment operator for an array of a 12034 // non-trivially-copyable class type, just emit a memcpy. 12035 if (!Result.isInvalid() && !Result.get()) 12036 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 12037 12038 return Result; 12039 } 12040 12041 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 12042 // Note: The following rules are largely analoguous to the copy 12043 // constructor rules. Note that virtual bases are not taken into account 12044 // for determining the argument type of the operator. Note also that 12045 // operators taking an object instead of a reference are allowed. 12046 assert(ClassDecl->needsImplicitCopyAssignment()); 12047 12048 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 12049 if (DSM.isAlreadyBeingDeclared()) 12050 return nullptr; 12051 12052 QualType ArgType = Context.getTypeDeclType(ClassDecl); 12053 if (Context.getLangOpts().OpenCLCPlusPlus) 12054 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); 12055 QualType RetType = Context.getLValueReferenceType(ArgType); 12056 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 12057 if (Const) 12058 ArgType = ArgType.withConst(); 12059 12060 ArgType = Context.getLValueReferenceType(ArgType); 12061 12062 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12063 CXXCopyAssignment, 12064 Const); 12065 12066 // An implicitly-declared copy assignment operator is an inline public 12067 // member of its class. 12068 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 12069 SourceLocation ClassLoc = ClassDecl->getLocation(); 12070 DeclarationNameInfo NameInfo(Name, ClassLoc); 12071 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 12072 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 12073 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 12074 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 12075 SourceLocation()); 12076 CopyAssignment->setAccess(AS_public); 12077 CopyAssignment->setDefaulted(); 12078 CopyAssignment->setImplicit(); 12079 12080 if (getLangOpts().CUDA) { 12081 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 12082 CopyAssignment, 12083 /* ConstRHS */ Const, 12084 /* Diagnose */ false); 12085 } 12086 12087 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 12088 12089 // Add the parameter to the operator. 12090 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 12091 ClassLoc, ClassLoc, 12092 /*Id=*/nullptr, ArgType, 12093 /*TInfo=*/nullptr, SC_None, 12094 nullptr); 12095 CopyAssignment->setParams(FromParam); 12096 12097 CopyAssignment->setTrivial( 12098 ClassDecl->needsOverloadResolutionForCopyAssignment() 12099 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 12100 : ClassDecl->hasTrivialCopyAssignment()); 12101 12102 // Note that we have added this copy-assignment operator. 12103 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 12104 12105 Scope *S = getScopeForContext(ClassDecl); 12106 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 12107 12108 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 12109 SetDeclDeleted(CopyAssignment, ClassLoc); 12110 12111 if (S) 12112 PushOnScopeChains(CopyAssignment, S, false); 12113 ClassDecl->addDecl(CopyAssignment); 12114 12115 return CopyAssignment; 12116 } 12117 12118 /// Diagnose an implicit copy operation for a class which is odr-used, but 12119 /// which is deprecated because the class has a user-declared copy constructor, 12120 /// copy assignment operator, or destructor. 12121 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 12122 assert(CopyOp->isImplicit()); 12123 12124 CXXRecordDecl *RD = CopyOp->getParent(); 12125 CXXMethodDecl *UserDeclaredOperation = nullptr; 12126 12127 // In Microsoft mode, assignment operations don't affect constructors and 12128 // vice versa. 12129 if (RD->hasUserDeclaredDestructor()) { 12130 UserDeclaredOperation = RD->getDestructor(); 12131 } else if (!isa<CXXConstructorDecl>(CopyOp) && 12132 RD->hasUserDeclaredCopyConstructor() && 12133 !S.getLangOpts().MSVCCompat) { 12134 // Find any user-declared copy constructor. 12135 for (auto *I : RD->ctors()) { 12136 if (I->isCopyConstructor()) { 12137 UserDeclaredOperation = I; 12138 break; 12139 } 12140 } 12141 assert(UserDeclaredOperation); 12142 } else if (isa<CXXConstructorDecl>(CopyOp) && 12143 RD->hasUserDeclaredCopyAssignment() && 12144 !S.getLangOpts().MSVCCompat) { 12145 // Find any user-declared move assignment operator. 12146 for (auto *I : RD->methods()) { 12147 if (I->isCopyAssignmentOperator()) { 12148 UserDeclaredOperation = I; 12149 break; 12150 } 12151 } 12152 assert(UserDeclaredOperation); 12153 } 12154 12155 if (UserDeclaredOperation) { 12156 S.Diag(UserDeclaredOperation->getLocation(), 12157 diag::warn_deprecated_copy_operation) 12158 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 12159 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 12160 } 12161 } 12162 12163 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 12164 CXXMethodDecl *CopyAssignOperator) { 12165 assert((CopyAssignOperator->isDefaulted() && 12166 CopyAssignOperator->isOverloadedOperator() && 12167 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 12168 !CopyAssignOperator->doesThisDeclarationHaveABody() && 12169 !CopyAssignOperator->isDeleted()) && 12170 "DefineImplicitCopyAssignment called for wrong function"); 12171 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 12172 return; 12173 12174 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 12175 if (ClassDecl->isInvalidDecl()) { 12176 CopyAssignOperator->setInvalidDecl(); 12177 return; 12178 } 12179 12180 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 12181 12182 // The exception specification is needed because we are defining the 12183 // function. 12184 ResolveExceptionSpec(CurrentLocation, 12185 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 12186 12187 // Add a context note for diagnostics produced after this point. 12188 Scope.addContextNote(CurrentLocation); 12189 12190 // C++11 [class.copy]p18: 12191 // The [definition of an implicitly declared copy assignment operator] is 12192 // deprecated if the class has a user-declared copy constructor or a 12193 // user-declared destructor. 12194 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 12195 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 12196 12197 // C++0x [class.copy]p30: 12198 // The implicitly-defined or explicitly-defaulted copy assignment operator 12199 // for a non-union class X performs memberwise copy assignment of its 12200 // subobjects. The direct base classes of X are assigned first, in the 12201 // order of their declaration in the base-specifier-list, and then the 12202 // immediate non-static data members of X are assigned, in the order in 12203 // which they were declared in the class definition. 12204 12205 // The statements that form the synthesized function body. 12206 SmallVector<Stmt*, 8> Statements; 12207 12208 // The parameter for the "other" object, which we are copying from. 12209 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 12210 Qualifiers OtherQuals = Other->getType().getQualifiers(); 12211 QualType OtherRefType = Other->getType(); 12212 if (const LValueReferenceType *OtherRef 12213 = OtherRefType->getAs<LValueReferenceType>()) { 12214 OtherRefType = OtherRef->getPointeeType(); 12215 OtherQuals = OtherRefType.getQualifiers(); 12216 } 12217 12218 // Our location for everything implicitly-generated. 12219 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 12220 ? CopyAssignOperator->getEndLoc() 12221 : CopyAssignOperator->getLocation(); 12222 12223 // Builds a DeclRefExpr for the "other" object. 12224 RefBuilder OtherRef(Other, OtherRefType); 12225 12226 // Builds the "this" pointer. 12227 ThisBuilder This; 12228 12229 // Assign base classes. 12230 bool Invalid = false; 12231 for (auto &Base : ClassDecl->bases()) { 12232 // Form the assignment: 12233 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 12234 QualType BaseType = Base.getType().getUnqualifiedType(); 12235 if (!BaseType->isRecordType()) { 12236 Invalid = true; 12237 continue; 12238 } 12239 12240 CXXCastPath BasePath; 12241 BasePath.push_back(&Base); 12242 12243 // Construct the "from" expression, which is an implicit cast to the 12244 // appropriately-qualified base type. 12245 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 12246 VK_LValue, BasePath); 12247 12248 // Dereference "this". 12249 DerefBuilder DerefThis(This); 12250 CastBuilder To(DerefThis, 12251 Context.getQualifiedType( 12252 BaseType, CopyAssignOperator->getMethodQualifiers()), 12253 VK_LValue, BasePath); 12254 12255 // Build the copy. 12256 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 12257 To, From, 12258 /*CopyingBaseSubobject=*/true, 12259 /*Copying=*/true); 12260 if (Copy.isInvalid()) { 12261 CopyAssignOperator->setInvalidDecl(); 12262 return; 12263 } 12264 12265 // Success! Record the copy. 12266 Statements.push_back(Copy.getAs<Expr>()); 12267 } 12268 12269 // Assign non-static members. 12270 for (auto *Field : ClassDecl->fields()) { 12271 // FIXME: We should form some kind of AST representation for the implied 12272 // memcpy in a union copy operation. 12273 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 12274 continue; 12275 12276 if (Field->isInvalidDecl()) { 12277 Invalid = true; 12278 continue; 12279 } 12280 12281 // Check for members of reference type; we can't copy those. 12282 if (Field->getType()->isReferenceType()) { 12283 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12284 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12285 Diag(Field->getLocation(), diag::note_declared_at); 12286 Invalid = true; 12287 continue; 12288 } 12289 12290 // Check for members of const-qualified, non-class type. 12291 QualType BaseType = Context.getBaseElementType(Field->getType()); 12292 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12293 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12294 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12295 Diag(Field->getLocation(), diag::note_declared_at); 12296 Invalid = true; 12297 continue; 12298 } 12299 12300 // Suppress assigning zero-width bitfields. 12301 if (Field->isZeroLengthBitField(Context)) 12302 continue; 12303 12304 QualType FieldType = Field->getType().getNonReferenceType(); 12305 if (FieldType->isIncompleteArrayType()) { 12306 assert(ClassDecl->hasFlexibleArrayMember() && 12307 "Incomplete array type is not valid"); 12308 continue; 12309 } 12310 12311 // Build references to the field in the object we're copying from and to. 12312 CXXScopeSpec SS; // Intentionally empty 12313 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12314 LookupMemberName); 12315 MemberLookup.addDecl(Field); 12316 MemberLookup.resolveKind(); 12317 12318 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 12319 12320 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 12321 12322 // Build the copy of this field. 12323 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 12324 To, From, 12325 /*CopyingBaseSubobject=*/false, 12326 /*Copying=*/true); 12327 if (Copy.isInvalid()) { 12328 CopyAssignOperator->setInvalidDecl(); 12329 return; 12330 } 12331 12332 // Success! Record the copy. 12333 Statements.push_back(Copy.getAs<Stmt>()); 12334 } 12335 12336 if (!Invalid) { 12337 // Add a "return *this;" 12338 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12339 12340 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12341 if (Return.isInvalid()) 12342 Invalid = true; 12343 else 12344 Statements.push_back(Return.getAs<Stmt>()); 12345 } 12346 12347 if (Invalid) { 12348 CopyAssignOperator->setInvalidDecl(); 12349 return; 12350 } 12351 12352 StmtResult Body; 12353 { 12354 CompoundScopeRAII CompoundScope(*this); 12355 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12356 /*isStmtExpr=*/false); 12357 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12358 } 12359 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 12360 CopyAssignOperator->markUsed(Context); 12361 12362 if (ASTMutationListener *L = getASTMutationListener()) { 12363 L->CompletedImplicitDefinition(CopyAssignOperator); 12364 } 12365 } 12366 12367 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 12368 assert(ClassDecl->needsImplicitMoveAssignment()); 12369 12370 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 12371 if (DSM.isAlreadyBeingDeclared()) 12372 return nullptr; 12373 12374 // Note: The following rules are largely analoguous to the move 12375 // constructor rules. 12376 12377 QualType ArgType = Context.getTypeDeclType(ClassDecl); 12378 if (Context.getLangOpts().OpenCLCPlusPlus) 12379 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); 12380 QualType RetType = Context.getLValueReferenceType(ArgType); 12381 ArgType = Context.getRValueReferenceType(ArgType); 12382 12383 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12384 CXXMoveAssignment, 12385 false); 12386 12387 // An implicitly-declared move assignment operator is an inline public 12388 // member of its class. 12389 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 12390 SourceLocation ClassLoc = ClassDecl->getLocation(); 12391 DeclarationNameInfo NameInfo(Name, ClassLoc); 12392 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 12393 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 12394 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 12395 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 12396 SourceLocation()); 12397 MoveAssignment->setAccess(AS_public); 12398 MoveAssignment->setDefaulted(); 12399 MoveAssignment->setImplicit(); 12400 12401 if (getLangOpts().CUDA) { 12402 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 12403 MoveAssignment, 12404 /* ConstRHS */ false, 12405 /* Diagnose */ false); 12406 } 12407 12408 // Build an exception specification pointing back at this member. 12409 FunctionProtoType::ExtProtoInfo EPI = 12410 getImplicitMethodEPI(*this, MoveAssignment); 12411 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 12412 12413 // Add the parameter to the operator. 12414 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 12415 ClassLoc, ClassLoc, 12416 /*Id=*/nullptr, ArgType, 12417 /*TInfo=*/nullptr, SC_None, 12418 nullptr); 12419 MoveAssignment->setParams(FromParam); 12420 12421 MoveAssignment->setTrivial( 12422 ClassDecl->needsOverloadResolutionForMoveAssignment() 12423 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 12424 : ClassDecl->hasTrivialMoveAssignment()); 12425 12426 // Note that we have added this copy-assignment operator. 12427 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 12428 12429 Scope *S = getScopeForContext(ClassDecl); 12430 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 12431 12432 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 12433 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 12434 SetDeclDeleted(MoveAssignment, ClassLoc); 12435 } 12436 12437 if (S) 12438 PushOnScopeChains(MoveAssignment, S, false); 12439 ClassDecl->addDecl(MoveAssignment); 12440 12441 return MoveAssignment; 12442 } 12443 12444 /// Check if we're implicitly defining a move assignment operator for a class 12445 /// with virtual bases. Such a move assignment might move-assign the virtual 12446 /// base multiple times. 12447 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 12448 SourceLocation CurrentLocation) { 12449 assert(!Class->isDependentContext() && "should not define dependent move"); 12450 12451 // Only a virtual base could get implicitly move-assigned multiple times. 12452 // Only a non-trivial move assignment can observe this. We only want to 12453 // diagnose if we implicitly define an assignment operator that assigns 12454 // two base classes, both of which move-assign the same virtual base. 12455 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 12456 Class->getNumBases() < 2) 12457 return; 12458 12459 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 12460 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 12461 VBaseMap VBases; 12462 12463 for (auto &BI : Class->bases()) { 12464 Worklist.push_back(&BI); 12465 while (!Worklist.empty()) { 12466 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 12467 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 12468 12469 // If the base has no non-trivial move assignment operators, 12470 // we don't care about moves from it. 12471 if (!Base->hasNonTrivialMoveAssignment()) 12472 continue; 12473 12474 // If there's nothing virtual here, skip it. 12475 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 12476 continue; 12477 12478 // If we're not actually going to call a move assignment for this base, 12479 // or the selected move assignment is trivial, skip it. 12480 Sema::SpecialMemberOverloadResult SMOR = 12481 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 12482 /*ConstArg*/false, /*VolatileArg*/false, 12483 /*RValueThis*/true, /*ConstThis*/false, 12484 /*VolatileThis*/false); 12485 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 12486 !SMOR.getMethod()->isMoveAssignmentOperator()) 12487 continue; 12488 12489 if (BaseSpec->isVirtual()) { 12490 // We're going to move-assign this virtual base, and its move 12491 // assignment operator is not trivial. If this can happen for 12492 // multiple distinct direct bases of Class, diagnose it. (If it 12493 // only happens in one base, we'll diagnose it when synthesizing 12494 // that base class's move assignment operator.) 12495 CXXBaseSpecifier *&Existing = 12496 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 12497 .first->second; 12498 if (Existing && Existing != &BI) { 12499 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 12500 << Class << Base; 12501 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 12502 << (Base->getCanonicalDecl() == 12503 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12504 << Base << Existing->getType() << Existing->getSourceRange(); 12505 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 12506 << (Base->getCanonicalDecl() == 12507 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12508 << Base << BI.getType() << BaseSpec->getSourceRange(); 12509 12510 // Only diagnose each vbase once. 12511 Existing = nullptr; 12512 } 12513 } else { 12514 // Only walk over bases that have defaulted move assignment operators. 12515 // We assume that any user-provided move assignment operator handles 12516 // the multiple-moves-of-vbase case itself somehow. 12517 if (!SMOR.getMethod()->isDefaulted()) 12518 continue; 12519 12520 // We're going to move the base classes of Base. Add them to the list. 12521 for (auto &BI : Base->bases()) 12522 Worklist.push_back(&BI); 12523 } 12524 } 12525 } 12526 } 12527 12528 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 12529 CXXMethodDecl *MoveAssignOperator) { 12530 assert((MoveAssignOperator->isDefaulted() && 12531 MoveAssignOperator->isOverloadedOperator() && 12532 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 12533 !MoveAssignOperator->doesThisDeclarationHaveABody() && 12534 !MoveAssignOperator->isDeleted()) && 12535 "DefineImplicitMoveAssignment called for wrong function"); 12536 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 12537 return; 12538 12539 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 12540 if (ClassDecl->isInvalidDecl()) { 12541 MoveAssignOperator->setInvalidDecl(); 12542 return; 12543 } 12544 12545 // C++0x [class.copy]p28: 12546 // The implicitly-defined or move assignment operator for a non-union class 12547 // X performs memberwise move assignment of its subobjects. The direct base 12548 // classes of X are assigned first, in the order of their declaration in the 12549 // base-specifier-list, and then the immediate non-static data members of X 12550 // are assigned, in the order in which they were declared in the class 12551 // definition. 12552 12553 // Issue a warning if our implicit move assignment operator will move 12554 // from a virtual base more than once. 12555 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 12556 12557 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 12558 12559 // The exception specification is needed because we are defining the 12560 // function. 12561 ResolveExceptionSpec(CurrentLocation, 12562 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 12563 12564 // Add a context note for diagnostics produced after this point. 12565 Scope.addContextNote(CurrentLocation); 12566 12567 // The statements that form the synthesized function body. 12568 SmallVector<Stmt*, 8> Statements; 12569 12570 // The parameter for the "other" object, which we are move from. 12571 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 12572 QualType OtherRefType = Other->getType()-> 12573 getAs<RValueReferenceType>()->getPointeeType(); 12574 12575 // Our location for everything implicitly-generated. 12576 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 12577 ? MoveAssignOperator->getEndLoc() 12578 : MoveAssignOperator->getLocation(); 12579 12580 // Builds a reference to the "other" object. 12581 RefBuilder OtherRef(Other, OtherRefType); 12582 // Cast to rvalue. 12583 MoveCastBuilder MoveOther(OtherRef); 12584 12585 // Builds the "this" pointer. 12586 ThisBuilder This; 12587 12588 // Assign base classes. 12589 bool Invalid = false; 12590 for (auto &Base : ClassDecl->bases()) { 12591 // C++11 [class.copy]p28: 12592 // It is unspecified whether subobjects representing virtual base classes 12593 // are assigned more than once by the implicitly-defined copy assignment 12594 // operator. 12595 // FIXME: Do not assign to a vbase that will be assigned by some other base 12596 // class. For a move-assignment, this can result in the vbase being moved 12597 // multiple times. 12598 12599 // Form the assignment: 12600 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 12601 QualType BaseType = Base.getType().getUnqualifiedType(); 12602 if (!BaseType->isRecordType()) { 12603 Invalid = true; 12604 continue; 12605 } 12606 12607 CXXCastPath BasePath; 12608 BasePath.push_back(&Base); 12609 12610 // Construct the "from" expression, which is an implicit cast to the 12611 // appropriately-qualified base type. 12612 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 12613 12614 // Dereference "this". 12615 DerefBuilder DerefThis(This); 12616 12617 // Implicitly cast "this" to the appropriately-qualified base type. 12618 CastBuilder To(DerefThis, 12619 Context.getQualifiedType( 12620 BaseType, MoveAssignOperator->getMethodQualifiers()), 12621 VK_LValue, BasePath); 12622 12623 // Build the move. 12624 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 12625 To, From, 12626 /*CopyingBaseSubobject=*/true, 12627 /*Copying=*/false); 12628 if (Move.isInvalid()) { 12629 MoveAssignOperator->setInvalidDecl(); 12630 return; 12631 } 12632 12633 // Success! Record the move. 12634 Statements.push_back(Move.getAs<Expr>()); 12635 } 12636 12637 // Assign non-static members. 12638 for (auto *Field : ClassDecl->fields()) { 12639 // FIXME: We should form some kind of AST representation for the implied 12640 // memcpy in a union copy operation. 12641 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 12642 continue; 12643 12644 if (Field->isInvalidDecl()) { 12645 Invalid = true; 12646 continue; 12647 } 12648 12649 // Check for members of reference type; we can't move those. 12650 if (Field->getType()->isReferenceType()) { 12651 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12652 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12653 Diag(Field->getLocation(), diag::note_declared_at); 12654 Invalid = true; 12655 continue; 12656 } 12657 12658 // Check for members of const-qualified, non-class type. 12659 QualType BaseType = Context.getBaseElementType(Field->getType()); 12660 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12661 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12662 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12663 Diag(Field->getLocation(), diag::note_declared_at); 12664 Invalid = true; 12665 continue; 12666 } 12667 12668 // Suppress assigning zero-width bitfields. 12669 if (Field->isZeroLengthBitField(Context)) 12670 continue; 12671 12672 QualType FieldType = Field->getType().getNonReferenceType(); 12673 if (FieldType->isIncompleteArrayType()) { 12674 assert(ClassDecl->hasFlexibleArrayMember() && 12675 "Incomplete array type is not valid"); 12676 continue; 12677 } 12678 12679 // Build references to the field in the object we're copying from and to. 12680 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12681 LookupMemberName); 12682 MemberLookup.addDecl(Field); 12683 MemberLookup.resolveKind(); 12684 MemberBuilder From(MoveOther, OtherRefType, 12685 /*IsArrow=*/false, MemberLookup); 12686 MemberBuilder To(This, getCurrentThisType(), 12687 /*IsArrow=*/true, MemberLookup); 12688 12689 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 12690 "Member reference with rvalue base must be rvalue except for reference " 12691 "members, which aren't allowed for move assignment."); 12692 12693 // Build the move of this field. 12694 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 12695 To, From, 12696 /*CopyingBaseSubobject=*/false, 12697 /*Copying=*/false); 12698 if (Move.isInvalid()) { 12699 MoveAssignOperator->setInvalidDecl(); 12700 return; 12701 } 12702 12703 // Success! Record the copy. 12704 Statements.push_back(Move.getAs<Stmt>()); 12705 } 12706 12707 if (!Invalid) { 12708 // Add a "return *this;" 12709 ExprResult ThisObj = 12710 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12711 12712 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12713 if (Return.isInvalid()) 12714 Invalid = true; 12715 else 12716 Statements.push_back(Return.getAs<Stmt>()); 12717 } 12718 12719 if (Invalid) { 12720 MoveAssignOperator->setInvalidDecl(); 12721 return; 12722 } 12723 12724 StmtResult Body; 12725 { 12726 CompoundScopeRAII CompoundScope(*this); 12727 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12728 /*isStmtExpr=*/false); 12729 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12730 } 12731 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 12732 MoveAssignOperator->markUsed(Context); 12733 12734 if (ASTMutationListener *L = getASTMutationListener()) { 12735 L->CompletedImplicitDefinition(MoveAssignOperator); 12736 } 12737 } 12738 12739 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 12740 CXXRecordDecl *ClassDecl) { 12741 // C++ [class.copy]p4: 12742 // If the class definition does not explicitly declare a copy 12743 // constructor, one is declared implicitly. 12744 assert(ClassDecl->needsImplicitCopyConstructor()); 12745 12746 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 12747 if (DSM.isAlreadyBeingDeclared()) 12748 return nullptr; 12749 12750 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12751 QualType ArgType = ClassType; 12752 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 12753 if (Const) 12754 ArgType = ArgType.withConst(); 12755 12756 if (Context.getLangOpts().OpenCLCPlusPlus) 12757 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); 12758 12759 ArgType = Context.getLValueReferenceType(ArgType); 12760 12761 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12762 CXXCopyConstructor, 12763 Const); 12764 12765 DeclarationName Name 12766 = Context.DeclarationNames.getCXXConstructorName( 12767 Context.getCanonicalType(ClassType)); 12768 SourceLocation ClassLoc = ClassDecl->getLocation(); 12769 DeclarationNameInfo NameInfo(Name, ClassLoc); 12770 12771 // An implicitly-declared copy constructor is an inline public 12772 // member of its class. 12773 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 12774 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12775 ExplicitSpecifier(), 12776 /*isInline=*/true, 12777 /*isImplicitlyDeclared=*/true, 12778 Constexpr ? CSK_constexpr : CSK_unspecified); 12779 CopyConstructor->setAccess(AS_public); 12780 CopyConstructor->setDefaulted(); 12781 12782 if (getLangOpts().CUDA) { 12783 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 12784 CopyConstructor, 12785 /* ConstRHS */ Const, 12786 /* Diagnose */ false); 12787 } 12788 12789 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 12790 12791 // Add the parameter to the constructor. 12792 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 12793 ClassLoc, ClassLoc, 12794 /*IdentifierInfo=*/nullptr, 12795 ArgType, /*TInfo=*/nullptr, 12796 SC_None, nullptr); 12797 CopyConstructor->setParams(FromParam); 12798 12799 CopyConstructor->setTrivial( 12800 ClassDecl->needsOverloadResolutionForCopyConstructor() 12801 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 12802 : ClassDecl->hasTrivialCopyConstructor()); 12803 12804 CopyConstructor->setTrivialForCall( 12805 ClassDecl->hasAttr<TrivialABIAttr>() || 12806 (ClassDecl->needsOverloadResolutionForCopyConstructor() 12807 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 12808 TAH_ConsiderTrivialABI) 12809 : ClassDecl->hasTrivialCopyConstructorForCall())); 12810 12811 // Note that we have declared this constructor. 12812 ++getASTContext().NumImplicitCopyConstructorsDeclared; 12813 12814 Scope *S = getScopeForContext(ClassDecl); 12815 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 12816 12817 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 12818 ClassDecl->setImplicitCopyConstructorIsDeleted(); 12819 SetDeclDeleted(CopyConstructor, ClassLoc); 12820 } 12821 12822 if (S) 12823 PushOnScopeChains(CopyConstructor, S, false); 12824 ClassDecl->addDecl(CopyConstructor); 12825 12826 return CopyConstructor; 12827 } 12828 12829 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 12830 CXXConstructorDecl *CopyConstructor) { 12831 assert((CopyConstructor->isDefaulted() && 12832 CopyConstructor->isCopyConstructor() && 12833 !CopyConstructor->doesThisDeclarationHaveABody() && 12834 !CopyConstructor->isDeleted()) && 12835 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 12836 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 12837 return; 12838 12839 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 12840 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 12841 12842 SynthesizedFunctionScope Scope(*this, CopyConstructor); 12843 12844 // The exception specification is needed because we are defining the 12845 // function. 12846 ResolveExceptionSpec(CurrentLocation, 12847 CopyConstructor->getType()->castAs<FunctionProtoType>()); 12848 MarkVTableUsed(CurrentLocation, ClassDecl); 12849 12850 // Add a context note for diagnostics produced after this point. 12851 Scope.addContextNote(CurrentLocation); 12852 12853 // C++11 [class.copy]p7: 12854 // The [definition of an implicitly declared copy constructor] is 12855 // deprecated if the class has a user-declared copy assignment operator 12856 // or a user-declared destructor. 12857 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 12858 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 12859 12860 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 12861 CopyConstructor->setInvalidDecl(); 12862 } else { 12863 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 12864 ? CopyConstructor->getEndLoc() 12865 : CopyConstructor->getLocation(); 12866 Sema::CompoundScopeRAII CompoundScope(*this); 12867 CopyConstructor->setBody( 12868 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 12869 CopyConstructor->markUsed(Context); 12870 } 12871 12872 if (ASTMutationListener *L = getASTMutationListener()) { 12873 L->CompletedImplicitDefinition(CopyConstructor); 12874 } 12875 } 12876 12877 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 12878 CXXRecordDecl *ClassDecl) { 12879 assert(ClassDecl->needsImplicitMoveConstructor()); 12880 12881 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 12882 if (DSM.isAlreadyBeingDeclared()) 12883 return nullptr; 12884 12885 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12886 12887 QualType ArgType = ClassType; 12888 if (Context.getLangOpts().OpenCLCPlusPlus) 12889 ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic); 12890 ArgType = Context.getRValueReferenceType(ArgType); 12891 12892 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12893 CXXMoveConstructor, 12894 false); 12895 12896 DeclarationName Name 12897 = Context.DeclarationNames.getCXXConstructorName( 12898 Context.getCanonicalType(ClassType)); 12899 SourceLocation ClassLoc = ClassDecl->getLocation(); 12900 DeclarationNameInfo NameInfo(Name, ClassLoc); 12901 12902 // C++11 [class.copy]p11: 12903 // An implicitly-declared copy/move constructor is an inline public 12904 // member of its class. 12905 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 12906 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12907 ExplicitSpecifier(), 12908 /*isInline=*/true, 12909 /*isImplicitlyDeclared=*/true, 12910 Constexpr ? CSK_constexpr : CSK_unspecified); 12911 MoveConstructor->setAccess(AS_public); 12912 MoveConstructor->setDefaulted(); 12913 12914 if (getLangOpts().CUDA) { 12915 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 12916 MoveConstructor, 12917 /* ConstRHS */ false, 12918 /* Diagnose */ false); 12919 } 12920 12921 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 12922 12923 // Add the parameter to the constructor. 12924 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 12925 ClassLoc, ClassLoc, 12926 /*IdentifierInfo=*/nullptr, 12927 ArgType, /*TInfo=*/nullptr, 12928 SC_None, nullptr); 12929 MoveConstructor->setParams(FromParam); 12930 12931 MoveConstructor->setTrivial( 12932 ClassDecl->needsOverloadResolutionForMoveConstructor() 12933 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 12934 : ClassDecl->hasTrivialMoveConstructor()); 12935 12936 MoveConstructor->setTrivialForCall( 12937 ClassDecl->hasAttr<TrivialABIAttr>() || 12938 (ClassDecl->needsOverloadResolutionForMoveConstructor() 12939 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 12940 TAH_ConsiderTrivialABI) 12941 : ClassDecl->hasTrivialMoveConstructorForCall())); 12942 12943 // Note that we have declared this constructor. 12944 ++getASTContext().NumImplicitMoveConstructorsDeclared; 12945 12946 Scope *S = getScopeForContext(ClassDecl); 12947 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 12948 12949 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 12950 ClassDecl->setImplicitMoveConstructorIsDeleted(); 12951 SetDeclDeleted(MoveConstructor, ClassLoc); 12952 } 12953 12954 if (S) 12955 PushOnScopeChains(MoveConstructor, S, false); 12956 ClassDecl->addDecl(MoveConstructor); 12957 12958 return MoveConstructor; 12959 } 12960 12961 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12962 CXXConstructorDecl *MoveConstructor) { 12963 assert((MoveConstructor->isDefaulted() && 12964 MoveConstructor->isMoveConstructor() && 12965 !MoveConstructor->doesThisDeclarationHaveABody() && 12966 !MoveConstructor->isDeleted()) && 12967 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12968 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 12969 return; 12970 12971 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12972 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12973 12974 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12975 12976 // The exception specification is needed because we are defining the 12977 // function. 12978 ResolveExceptionSpec(CurrentLocation, 12979 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12980 MarkVTableUsed(CurrentLocation, ClassDecl); 12981 12982 // Add a context note for diagnostics produced after this point. 12983 Scope.addContextNote(CurrentLocation); 12984 12985 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 12986 MoveConstructor->setInvalidDecl(); 12987 } else { 12988 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 12989 ? MoveConstructor->getEndLoc() 12990 : MoveConstructor->getLocation(); 12991 Sema::CompoundScopeRAII CompoundScope(*this); 12992 MoveConstructor->setBody(ActOnCompoundStmt( 12993 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12994 MoveConstructor->markUsed(Context); 12995 } 12996 12997 if (ASTMutationListener *L = getASTMutationListener()) { 12998 L->CompletedImplicitDefinition(MoveConstructor); 12999 } 13000 } 13001 13002 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 13003 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 13004 } 13005 13006 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 13007 SourceLocation CurrentLocation, 13008 CXXConversionDecl *Conv) { 13009 SynthesizedFunctionScope Scope(*this, Conv); 13010 assert(!Conv->getReturnType()->isUndeducedType()); 13011 13012 CXXRecordDecl *Lambda = Conv->getParent(); 13013 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 13014 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); 13015 13016 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 13017 CallOp = InstantiateFunctionDeclaration( 13018 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 13019 if (!CallOp) 13020 return; 13021 13022 Invoker = InstantiateFunctionDeclaration( 13023 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 13024 if (!Invoker) 13025 return; 13026 } 13027 13028 if (CallOp->isInvalidDecl()) 13029 return; 13030 13031 // Mark the call operator referenced (and add to pending instantiations 13032 // if necessary). 13033 // For both the conversion and static-invoker template specializations 13034 // we construct their body's in this function, so no need to add them 13035 // to the PendingInstantiations. 13036 MarkFunctionReferenced(CurrentLocation, CallOp); 13037 13038 // Fill in the __invoke function with a dummy implementation. IR generation 13039 // will fill in the actual details. Update its type in case it contained 13040 // an 'auto'. 13041 Invoker->markUsed(Context); 13042 Invoker->setReferenced(); 13043 Invoker->setType(Conv->getReturnType()->getPointeeType()); 13044 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 13045 13046 // Construct the body of the conversion function { return __invoke; }. 13047 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 13048 VK_LValue, Conv->getLocation()); 13049 assert(FunctionRef && "Can't refer to __invoke function?"); 13050 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 13051 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 13052 Conv->getLocation())); 13053 Conv->markUsed(Context); 13054 Conv->setReferenced(); 13055 13056 if (ASTMutationListener *L = getASTMutationListener()) { 13057 L->CompletedImplicitDefinition(Conv); 13058 L->CompletedImplicitDefinition(Invoker); 13059 } 13060 } 13061 13062 13063 13064 void Sema::DefineImplicitLambdaToBlockPointerConversion( 13065 SourceLocation CurrentLocation, 13066 CXXConversionDecl *Conv) 13067 { 13068 assert(!Conv->getParent()->isGenericLambda()); 13069 13070 SynthesizedFunctionScope Scope(*this, Conv); 13071 13072 // Copy-initialize the lambda object as needed to capture it. 13073 Expr *This = ActOnCXXThis(CurrentLocation).get(); 13074 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 13075 13076 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 13077 Conv->getLocation(), 13078 Conv, DerefThis); 13079 13080 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 13081 // behavior. Note that only the general conversion function does this 13082 // (since it's unusable otherwise); in the case where we inline the 13083 // block literal, it has block literal lifetime semantics. 13084 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 13085 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 13086 CK_CopyAndAutoreleaseBlockObject, 13087 BuildBlock.get(), nullptr, VK_RValue); 13088 13089 if (BuildBlock.isInvalid()) { 13090 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 13091 Conv->setInvalidDecl(); 13092 return; 13093 } 13094 13095 // Create the return statement that returns the block from the conversion 13096 // function. 13097 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 13098 if (Return.isInvalid()) { 13099 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 13100 Conv->setInvalidDecl(); 13101 return; 13102 } 13103 13104 // Set the body of the conversion function. 13105 Stmt *ReturnS = Return.get(); 13106 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 13107 Conv->getLocation())); 13108 Conv->markUsed(Context); 13109 13110 // We're done; notify the mutation listener, if any. 13111 if (ASTMutationListener *L = getASTMutationListener()) { 13112 L->CompletedImplicitDefinition(Conv); 13113 } 13114 } 13115 13116 /// Determine whether the given list arguments contains exactly one 13117 /// "real" (non-default) argument. 13118 static bool hasOneRealArgument(MultiExprArg Args) { 13119 switch (Args.size()) { 13120 case 0: 13121 return false; 13122 13123 default: 13124 if (!Args[1]->isDefaultArgument()) 13125 return false; 13126 13127 LLVM_FALLTHROUGH; 13128 case 1: 13129 return !Args[0]->isDefaultArgument(); 13130 } 13131 13132 return false; 13133 } 13134 13135 ExprResult 13136 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 13137 NamedDecl *FoundDecl, 13138 CXXConstructorDecl *Constructor, 13139 MultiExprArg ExprArgs, 13140 bool HadMultipleCandidates, 13141 bool IsListInitialization, 13142 bool IsStdInitListInitialization, 13143 bool RequiresZeroInit, 13144 unsigned ConstructKind, 13145 SourceRange ParenRange) { 13146 bool Elidable = false; 13147 13148 // C++0x [class.copy]p34: 13149 // When certain criteria are met, an implementation is allowed to 13150 // omit the copy/move construction of a class object, even if the 13151 // copy/move constructor and/or destructor for the object have 13152 // side effects. [...] 13153 // - when a temporary class object that has not been bound to a 13154 // reference (12.2) would be copied/moved to a class object 13155 // with the same cv-unqualified type, the copy/move operation 13156 // can be omitted by constructing the temporary object 13157 // directly into the target of the omitted copy/move 13158 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 13159 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 13160 Expr *SubExpr = ExprArgs[0]; 13161 Elidable = SubExpr->isTemporaryObject( 13162 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 13163 } 13164 13165 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 13166 FoundDecl, Constructor, 13167 Elidable, ExprArgs, HadMultipleCandidates, 13168 IsListInitialization, 13169 IsStdInitListInitialization, RequiresZeroInit, 13170 ConstructKind, ParenRange); 13171 } 13172 13173 ExprResult 13174 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 13175 NamedDecl *FoundDecl, 13176 CXXConstructorDecl *Constructor, 13177 bool Elidable, 13178 MultiExprArg ExprArgs, 13179 bool HadMultipleCandidates, 13180 bool IsListInitialization, 13181 bool IsStdInitListInitialization, 13182 bool RequiresZeroInit, 13183 unsigned ConstructKind, 13184 SourceRange ParenRange) { 13185 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 13186 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 13187 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 13188 return ExprError(); 13189 } 13190 13191 return BuildCXXConstructExpr( 13192 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 13193 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 13194 RequiresZeroInit, ConstructKind, ParenRange); 13195 } 13196 13197 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 13198 /// including handling of its default argument expressions. 13199 ExprResult 13200 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 13201 CXXConstructorDecl *Constructor, 13202 bool Elidable, 13203 MultiExprArg ExprArgs, 13204 bool HadMultipleCandidates, 13205 bool IsListInitialization, 13206 bool IsStdInitListInitialization, 13207 bool RequiresZeroInit, 13208 unsigned ConstructKind, 13209 SourceRange ParenRange) { 13210 assert(declaresSameEntity( 13211 Constructor->getParent(), 13212 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 13213 "given constructor for wrong type"); 13214 MarkFunctionReferenced(ConstructLoc, Constructor); 13215 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 13216 return ExprError(); 13217 13218 return CXXConstructExpr::Create( 13219 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 13220 ExprArgs, HadMultipleCandidates, IsListInitialization, 13221 IsStdInitListInitialization, RequiresZeroInit, 13222 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 13223 ParenRange); 13224 } 13225 13226 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 13227 assert(Field->hasInClassInitializer()); 13228 13229 // If we already have the in-class initializer nothing needs to be done. 13230 if (Field->getInClassInitializer()) 13231 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 13232 13233 // If we might have already tried and failed to instantiate, don't try again. 13234 if (Field->isInvalidDecl()) 13235 return ExprError(); 13236 13237 // Maybe we haven't instantiated the in-class initializer. Go check the 13238 // pattern FieldDecl to see if it has one. 13239 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 13240 13241 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 13242 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 13243 DeclContext::lookup_result Lookup = 13244 ClassPattern->lookup(Field->getDeclName()); 13245 13246 // Lookup can return at most two results: the pattern for the field, or the 13247 // injected class name of the parent record. No other member can have the 13248 // same name as the field. 13249 // In modules mode, lookup can return multiple results (coming from 13250 // different modules). 13251 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 13252 "more than two lookup results for field name"); 13253 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 13254 if (!Pattern) { 13255 assert(isa<CXXRecordDecl>(Lookup[0]) && 13256 "cannot have other non-field member with same name"); 13257 for (auto L : Lookup) 13258 if (isa<FieldDecl>(L)) { 13259 Pattern = cast<FieldDecl>(L); 13260 break; 13261 } 13262 assert(Pattern && "We must have set the Pattern!"); 13263 } 13264 13265 if (!Pattern->hasInClassInitializer() || 13266 InstantiateInClassInitializer(Loc, Field, Pattern, 13267 getTemplateInstantiationArgs(Field))) { 13268 // Don't diagnose this again. 13269 Field->setInvalidDecl(); 13270 return ExprError(); 13271 } 13272 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 13273 } 13274 13275 // DR1351: 13276 // If the brace-or-equal-initializer of a non-static data member 13277 // invokes a defaulted default constructor of its class or of an 13278 // enclosing class in a potentially evaluated subexpression, the 13279 // program is ill-formed. 13280 // 13281 // This resolution is unworkable: the exception specification of the 13282 // default constructor can be needed in an unevaluated context, in 13283 // particular, in the operand of a noexcept-expression, and we can be 13284 // unable to compute an exception specification for an enclosed class. 13285 // 13286 // Any attempt to resolve the exception specification of a defaulted default 13287 // constructor before the initializer is lexically complete will ultimately 13288 // come here at which point we can diagnose it. 13289 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 13290 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 13291 << OutermostClass << Field; 13292 Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed); 13293 // Recover by marking the field invalid, unless we're in a SFINAE context. 13294 if (!isSFINAEContext()) 13295 Field->setInvalidDecl(); 13296 return ExprError(); 13297 } 13298 13299 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 13300 if (VD->isInvalidDecl()) return; 13301 13302 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 13303 if (ClassDecl->isInvalidDecl()) return; 13304 if (ClassDecl->hasIrrelevantDestructor()) return; 13305 if (ClassDecl->isDependentContext()) return; 13306 13307 if (VD->isNoDestroy(getASTContext())) 13308 return; 13309 13310 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13311 13312 // If this is an array, we'll require the destructor during initialization, so 13313 // we can skip over this. We still want to emit exit-time destructor warnings 13314 // though. 13315 if (!VD->getType()->isArrayType()) { 13316 MarkFunctionReferenced(VD->getLocation(), Destructor); 13317 CheckDestructorAccess(VD->getLocation(), Destructor, 13318 PDiag(diag::err_access_dtor_var) 13319 << VD->getDeclName() << VD->getType()); 13320 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 13321 } 13322 13323 if (Destructor->isTrivial()) return; 13324 if (!VD->hasGlobalStorage()) return; 13325 13326 // Emit warning for non-trivial dtor in global scope (a real global, 13327 // class-static, function-static). 13328 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 13329 13330 // TODO: this should be re-enabled for static locals by !CXAAtExit 13331 if (!VD->isStaticLocal()) 13332 Diag(VD->getLocation(), diag::warn_global_destructor); 13333 } 13334 13335 /// Given a constructor and the set of arguments provided for the 13336 /// constructor, convert the arguments and add any required default arguments 13337 /// to form a proper call to this constructor. 13338 /// 13339 /// \returns true if an error occurred, false otherwise. 13340 bool 13341 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 13342 MultiExprArg ArgsPtr, 13343 SourceLocation Loc, 13344 SmallVectorImpl<Expr*> &ConvertedArgs, 13345 bool AllowExplicit, 13346 bool IsListInitialization) { 13347 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 13348 unsigned NumArgs = ArgsPtr.size(); 13349 Expr **Args = ArgsPtr.data(); 13350 13351 const FunctionProtoType *Proto 13352 = Constructor->getType()->getAs<FunctionProtoType>(); 13353 assert(Proto && "Constructor without a prototype?"); 13354 unsigned NumParams = Proto->getNumParams(); 13355 13356 // If too few arguments are available, we'll fill in the rest with defaults. 13357 if (NumArgs < NumParams) 13358 ConvertedArgs.reserve(NumParams); 13359 else 13360 ConvertedArgs.reserve(NumArgs); 13361 13362 VariadicCallType CallType = 13363 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 13364 SmallVector<Expr *, 8> AllArgs; 13365 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 13366 Proto, 0, 13367 llvm::makeArrayRef(Args, NumArgs), 13368 AllArgs, 13369 CallType, AllowExplicit, 13370 IsListInitialization); 13371 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 13372 13373 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 13374 13375 CheckConstructorCall(Constructor, 13376 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 13377 Proto, Loc); 13378 13379 return Invalid; 13380 } 13381 13382 static inline bool 13383 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 13384 const FunctionDecl *FnDecl) { 13385 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 13386 if (isa<NamespaceDecl>(DC)) { 13387 return SemaRef.Diag(FnDecl->getLocation(), 13388 diag::err_operator_new_delete_declared_in_namespace) 13389 << FnDecl->getDeclName(); 13390 } 13391 13392 if (isa<TranslationUnitDecl>(DC) && 13393 FnDecl->getStorageClass() == SC_Static) { 13394 return SemaRef.Diag(FnDecl->getLocation(), 13395 diag::err_operator_new_delete_declared_static) 13396 << FnDecl->getDeclName(); 13397 } 13398 13399 return false; 13400 } 13401 13402 static QualType 13403 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { 13404 QualType QTy = PtrTy->getPointeeType(); 13405 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); 13406 return SemaRef.Context.getPointerType(QTy); 13407 } 13408 13409 static inline bool 13410 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 13411 CanQualType ExpectedResultType, 13412 CanQualType ExpectedFirstParamType, 13413 unsigned DependentParamTypeDiag, 13414 unsigned InvalidParamTypeDiag) { 13415 QualType ResultType = 13416 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 13417 13418 // Check that the result type is not dependent. 13419 if (ResultType->isDependentType()) 13420 return SemaRef.Diag(FnDecl->getLocation(), 13421 diag::err_operator_new_delete_dependent_result_type) 13422 << FnDecl->getDeclName() << ExpectedResultType; 13423 13424 // The operator is valid on any address space for OpenCL. 13425 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13426 if (auto *PtrTy = ResultType->getAs<PointerType>()) { 13427 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13428 } 13429 } 13430 13431 // Check that the result type is what we expect. 13432 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 13433 return SemaRef.Diag(FnDecl->getLocation(), 13434 diag::err_operator_new_delete_invalid_result_type) 13435 << FnDecl->getDeclName() << ExpectedResultType; 13436 13437 // A function template must have at least 2 parameters. 13438 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 13439 return SemaRef.Diag(FnDecl->getLocation(), 13440 diag::err_operator_new_delete_template_too_few_parameters) 13441 << FnDecl->getDeclName(); 13442 13443 // The function decl must have at least 1 parameter. 13444 if (FnDecl->getNumParams() == 0) 13445 return SemaRef.Diag(FnDecl->getLocation(), 13446 diag::err_operator_new_delete_too_few_parameters) 13447 << FnDecl->getDeclName(); 13448 13449 // Check the first parameter type is not dependent. 13450 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 13451 if (FirstParamType->isDependentType()) 13452 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 13453 << FnDecl->getDeclName() << ExpectedFirstParamType; 13454 13455 // Check that the first parameter type is what we expect. 13456 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13457 // The operator is valid on any address space for OpenCL. 13458 if (auto *PtrTy = 13459 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { 13460 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13461 } 13462 } 13463 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 13464 ExpectedFirstParamType) 13465 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 13466 << FnDecl->getDeclName() << ExpectedFirstParamType; 13467 13468 return false; 13469 } 13470 13471 static bool 13472 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 13473 // C++ [basic.stc.dynamic.allocation]p1: 13474 // A program is ill-formed if an allocation function is declared in a 13475 // namespace scope other than global scope or declared static in global 13476 // scope. 13477 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13478 return true; 13479 13480 CanQualType SizeTy = 13481 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 13482 13483 // C++ [basic.stc.dynamic.allocation]p1: 13484 // The return type shall be void*. The first parameter shall have type 13485 // std::size_t. 13486 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 13487 SizeTy, 13488 diag::err_operator_new_dependent_param_type, 13489 diag::err_operator_new_param_type)) 13490 return true; 13491 13492 // C++ [basic.stc.dynamic.allocation]p1: 13493 // The first parameter shall not have an associated default argument. 13494 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 13495 return SemaRef.Diag(FnDecl->getLocation(), 13496 diag::err_operator_new_default_arg) 13497 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 13498 13499 return false; 13500 } 13501 13502 static bool 13503 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 13504 // C++ [basic.stc.dynamic.deallocation]p1: 13505 // A program is ill-formed if deallocation functions are declared in a 13506 // namespace scope other than global scope or declared static in global 13507 // scope. 13508 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13509 return true; 13510 13511 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 13512 13513 // C++ P0722: 13514 // Within a class C, the first parameter of a destroying operator delete 13515 // shall be of type C *. The first parameter of any other deallocation 13516 // function shall be of type void *. 13517 CanQualType ExpectedFirstParamType = 13518 MD && MD->isDestroyingOperatorDelete() 13519 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 13520 SemaRef.Context.getRecordType(MD->getParent()))) 13521 : SemaRef.Context.VoidPtrTy; 13522 13523 // C++ [basic.stc.dynamic.deallocation]p2: 13524 // Each deallocation function shall return void 13525 if (CheckOperatorNewDeleteTypes( 13526 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 13527 diag::err_operator_delete_dependent_param_type, 13528 diag::err_operator_delete_param_type)) 13529 return true; 13530 13531 // C++ P0722: 13532 // A destroying operator delete shall be a usual deallocation function. 13533 if (MD && !MD->getParent()->isDependentContext() && 13534 MD->isDestroyingOperatorDelete() && 13535 !SemaRef.isUsualDeallocationFunction(MD)) { 13536 SemaRef.Diag(MD->getLocation(), 13537 diag::err_destroying_operator_delete_not_usual); 13538 return true; 13539 } 13540 13541 return false; 13542 } 13543 13544 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 13545 /// of this overloaded operator is well-formed. If so, returns false; 13546 /// otherwise, emits appropriate diagnostics and returns true. 13547 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 13548 assert(FnDecl && FnDecl->isOverloadedOperator() && 13549 "Expected an overloaded operator declaration"); 13550 13551 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 13552 13553 // C++ [over.oper]p5: 13554 // The allocation and deallocation functions, operator new, 13555 // operator new[], operator delete and operator delete[], are 13556 // described completely in 3.7.3. The attributes and restrictions 13557 // found in the rest of this subclause do not apply to them unless 13558 // explicitly stated in 3.7.3. 13559 if (Op == OO_Delete || Op == OO_Array_Delete) 13560 return CheckOperatorDeleteDeclaration(*this, FnDecl); 13561 13562 if (Op == OO_New || Op == OO_Array_New) 13563 return CheckOperatorNewDeclaration(*this, FnDecl); 13564 13565 // C++ [over.oper]p6: 13566 // An operator function shall either be a non-static member 13567 // function or be a non-member function and have at least one 13568 // parameter whose type is a class, a reference to a class, an 13569 // enumeration, or a reference to an enumeration. 13570 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 13571 if (MethodDecl->isStatic()) 13572 return Diag(FnDecl->getLocation(), 13573 diag::err_operator_overload_static) << FnDecl->getDeclName(); 13574 } else { 13575 bool ClassOrEnumParam = false; 13576 for (auto Param : FnDecl->parameters()) { 13577 QualType ParamType = Param->getType().getNonReferenceType(); 13578 if (ParamType->isDependentType() || ParamType->isRecordType() || 13579 ParamType->isEnumeralType()) { 13580 ClassOrEnumParam = true; 13581 break; 13582 } 13583 } 13584 13585 if (!ClassOrEnumParam) 13586 return Diag(FnDecl->getLocation(), 13587 diag::err_operator_overload_needs_class_or_enum) 13588 << FnDecl->getDeclName(); 13589 } 13590 13591 // C++ [over.oper]p8: 13592 // An operator function cannot have default arguments (8.3.6), 13593 // except where explicitly stated below. 13594 // 13595 // Only the function-call operator allows default arguments 13596 // (C++ [over.call]p1). 13597 if (Op != OO_Call) { 13598 for (auto Param : FnDecl->parameters()) { 13599 if (Param->hasDefaultArg()) 13600 return Diag(Param->getLocation(), 13601 diag::err_operator_overload_default_arg) 13602 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 13603 } 13604 } 13605 13606 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 13607 { false, false, false } 13608 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 13609 , { Unary, Binary, MemberOnly } 13610 #include "clang/Basic/OperatorKinds.def" 13611 }; 13612 13613 bool CanBeUnaryOperator = OperatorUses[Op][0]; 13614 bool CanBeBinaryOperator = OperatorUses[Op][1]; 13615 bool MustBeMemberOperator = OperatorUses[Op][2]; 13616 13617 // C++ [over.oper]p8: 13618 // [...] Operator functions cannot have more or fewer parameters 13619 // than the number required for the corresponding operator, as 13620 // described in the rest of this subclause. 13621 unsigned NumParams = FnDecl->getNumParams() 13622 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 13623 if (Op != OO_Call && 13624 ((NumParams == 1 && !CanBeUnaryOperator) || 13625 (NumParams == 2 && !CanBeBinaryOperator) || 13626 (NumParams < 1) || (NumParams > 2))) { 13627 // We have the wrong number of parameters. 13628 unsigned ErrorKind; 13629 if (CanBeUnaryOperator && CanBeBinaryOperator) { 13630 ErrorKind = 2; // 2 -> unary or binary. 13631 } else if (CanBeUnaryOperator) { 13632 ErrorKind = 0; // 0 -> unary 13633 } else { 13634 assert(CanBeBinaryOperator && 13635 "All non-call overloaded operators are unary or binary!"); 13636 ErrorKind = 1; // 1 -> binary 13637 } 13638 13639 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 13640 << FnDecl->getDeclName() << NumParams << ErrorKind; 13641 } 13642 13643 // Overloaded operators other than operator() cannot be variadic. 13644 if (Op != OO_Call && 13645 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 13646 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 13647 << FnDecl->getDeclName(); 13648 } 13649 13650 // Some operators must be non-static member functions. 13651 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 13652 return Diag(FnDecl->getLocation(), 13653 diag::err_operator_overload_must_be_member) 13654 << FnDecl->getDeclName(); 13655 } 13656 13657 // C++ [over.inc]p1: 13658 // The user-defined function called operator++ implements the 13659 // prefix and postfix ++ operator. If this function is a member 13660 // function with no parameters, or a non-member function with one 13661 // parameter of class or enumeration type, it defines the prefix 13662 // increment operator ++ for objects of that type. If the function 13663 // is a member function with one parameter (which shall be of type 13664 // int) or a non-member function with two parameters (the second 13665 // of which shall be of type int), it defines the postfix 13666 // increment operator ++ for objects of that type. 13667 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 13668 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 13669 QualType ParamType = LastParam->getType(); 13670 13671 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 13672 !ParamType->isDependentType()) 13673 return Diag(LastParam->getLocation(), 13674 diag::err_operator_overload_post_incdec_must_be_int) 13675 << LastParam->getType() << (Op == OO_MinusMinus); 13676 } 13677 13678 return false; 13679 } 13680 13681 static bool 13682 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 13683 FunctionTemplateDecl *TpDecl) { 13684 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 13685 13686 // Must have one or two template parameters. 13687 if (TemplateParams->size() == 1) { 13688 NonTypeTemplateParmDecl *PmDecl = 13689 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 13690 13691 // The template parameter must be a char parameter pack. 13692 if (PmDecl && PmDecl->isTemplateParameterPack() && 13693 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 13694 return false; 13695 13696 } else if (TemplateParams->size() == 2) { 13697 TemplateTypeParmDecl *PmType = 13698 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 13699 NonTypeTemplateParmDecl *PmArgs = 13700 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 13701 13702 // The second template parameter must be a parameter pack with the 13703 // first template parameter as its type. 13704 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 13705 PmArgs->isTemplateParameterPack()) { 13706 const TemplateTypeParmType *TArgs = 13707 PmArgs->getType()->getAs<TemplateTypeParmType>(); 13708 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 13709 TArgs->getIndex() == PmType->getIndex()) { 13710 if (!SemaRef.inTemplateInstantiation()) 13711 SemaRef.Diag(TpDecl->getLocation(), 13712 diag::ext_string_literal_operator_template); 13713 return false; 13714 } 13715 } 13716 } 13717 13718 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 13719 diag::err_literal_operator_template) 13720 << TpDecl->getTemplateParameters()->getSourceRange(); 13721 return true; 13722 } 13723 13724 /// CheckLiteralOperatorDeclaration - Check whether the declaration 13725 /// of this literal operator function is well-formed. If so, returns 13726 /// false; otherwise, emits appropriate diagnostics and returns true. 13727 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 13728 if (isa<CXXMethodDecl>(FnDecl)) { 13729 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 13730 << FnDecl->getDeclName(); 13731 return true; 13732 } 13733 13734 if (FnDecl->isExternC()) { 13735 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 13736 if (const LinkageSpecDecl *LSD = 13737 FnDecl->getDeclContext()->getExternCContext()) 13738 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 13739 return true; 13740 } 13741 13742 // This might be the definition of a literal operator template. 13743 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 13744 13745 // This might be a specialization of a literal operator template. 13746 if (!TpDecl) 13747 TpDecl = FnDecl->getPrimaryTemplate(); 13748 13749 // template <char...> type operator "" name() and 13750 // template <class T, T...> type operator "" name() are the only valid 13751 // template signatures, and the only valid signatures with no parameters. 13752 if (TpDecl) { 13753 if (FnDecl->param_size() != 0) { 13754 Diag(FnDecl->getLocation(), 13755 diag::err_literal_operator_template_with_params); 13756 return true; 13757 } 13758 13759 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 13760 return true; 13761 13762 } else if (FnDecl->param_size() == 1) { 13763 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 13764 13765 QualType ParamType = Param->getType().getUnqualifiedType(); 13766 13767 // Only unsigned long long int, long double, any character type, and const 13768 // char * are allowed as the only parameters. 13769 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 13770 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 13771 Context.hasSameType(ParamType, Context.CharTy) || 13772 Context.hasSameType(ParamType, Context.WideCharTy) || 13773 Context.hasSameType(ParamType, Context.Char8Ty) || 13774 Context.hasSameType(ParamType, Context.Char16Ty) || 13775 Context.hasSameType(ParamType, Context.Char32Ty)) { 13776 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 13777 QualType InnerType = Ptr->getPointeeType(); 13778 13779 // Pointer parameter must be a const char *. 13780 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 13781 Context.CharTy) && 13782 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 13783 Diag(Param->getSourceRange().getBegin(), 13784 diag::err_literal_operator_param) 13785 << ParamType << "'const char *'" << Param->getSourceRange(); 13786 return true; 13787 } 13788 13789 } else if (ParamType->isRealFloatingType()) { 13790 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13791 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 13792 return true; 13793 13794 } else if (ParamType->isIntegerType()) { 13795 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13796 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 13797 return true; 13798 13799 } else { 13800 Diag(Param->getSourceRange().getBegin(), 13801 diag::err_literal_operator_invalid_param) 13802 << ParamType << Param->getSourceRange(); 13803 return true; 13804 } 13805 13806 } else if (FnDecl->param_size() == 2) { 13807 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 13808 13809 // First, verify that the first parameter is correct. 13810 13811 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 13812 13813 // Two parameter function must have a pointer to const as a 13814 // first parameter; let's strip those qualifiers. 13815 const PointerType *PT = FirstParamType->getAs<PointerType>(); 13816 13817 if (!PT) { 13818 Diag((*Param)->getSourceRange().getBegin(), 13819 diag::err_literal_operator_param) 13820 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13821 return true; 13822 } 13823 13824 QualType PointeeType = PT->getPointeeType(); 13825 // First parameter must be const 13826 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 13827 Diag((*Param)->getSourceRange().getBegin(), 13828 diag::err_literal_operator_param) 13829 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13830 return true; 13831 } 13832 13833 QualType InnerType = PointeeType.getUnqualifiedType(); 13834 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 13835 // const char32_t* are allowed as the first parameter to a two-parameter 13836 // function 13837 if (!(Context.hasSameType(InnerType, Context.CharTy) || 13838 Context.hasSameType(InnerType, Context.WideCharTy) || 13839 Context.hasSameType(InnerType, Context.Char8Ty) || 13840 Context.hasSameType(InnerType, Context.Char16Ty) || 13841 Context.hasSameType(InnerType, Context.Char32Ty))) { 13842 Diag((*Param)->getSourceRange().getBegin(), 13843 diag::err_literal_operator_param) 13844 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13845 return true; 13846 } 13847 13848 // Move on to the second and final parameter. 13849 ++Param; 13850 13851 // The second parameter must be a std::size_t. 13852 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 13853 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 13854 Diag((*Param)->getSourceRange().getBegin(), 13855 diag::err_literal_operator_param) 13856 << SecondParamType << Context.getSizeType() 13857 << (*Param)->getSourceRange(); 13858 return true; 13859 } 13860 } else { 13861 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 13862 return true; 13863 } 13864 13865 // Parameters are good. 13866 13867 // A parameter-declaration-clause containing a default argument is not 13868 // equivalent to any of the permitted forms. 13869 for (auto Param : FnDecl->parameters()) { 13870 if (Param->hasDefaultArg()) { 13871 Diag(Param->getDefaultArgRange().getBegin(), 13872 diag::err_literal_operator_default_argument) 13873 << Param->getDefaultArgRange(); 13874 break; 13875 } 13876 } 13877 13878 StringRef LiteralName 13879 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 13880 if (LiteralName[0] != '_' && 13881 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 13882 // C++11 [usrlit.suffix]p1: 13883 // Literal suffix identifiers that do not start with an underscore 13884 // are reserved for future standardization. 13885 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 13886 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 13887 } 13888 13889 return false; 13890 } 13891 13892 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 13893 /// linkage specification, including the language and (if present) 13894 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 13895 /// language string literal. LBraceLoc, if valid, provides the location of 13896 /// the '{' brace. Otherwise, this linkage specification does not 13897 /// have any braces. 13898 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 13899 Expr *LangStr, 13900 SourceLocation LBraceLoc) { 13901 StringLiteral *Lit = cast<StringLiteral>(LangStr); 13902 if (!Lit->isAscii()) { 13903 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 13904 << LangStr->getSourceRange(); 13905 return nullptr; 13906 } 13907 13908 StringRef Lang = Lit->getString(); 13909 LinkageSpecDecl::LanguageIDs Language; 13910 if (Lang == "C") 13911 Language = LinkageSpecDecl::lang_c; 13912 else if (Lang == "C++") 13913 Language = LinkageSpecDecl::lang_cxx; 13914 else { 13915 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 13916 << LangStr->getSourceRange(); 13917 return nullptr; 13918 } 13919 13920 // FIXME: Add all the various semantics of linkage specifications 13921 13922 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 13923 LangStr->getExprLoc(), Language, 13924 LBraceLoc.isValid()); 13925 CurContext->addDecl(D); 13926 PushDeclContext(S, D); 13927 return D; 13928 } 13929 13930 /// ActOnFinishLinkageSpecification - Complete the definition of 13931 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 13932 /// valid, it's the position of the closing '}' brace in a linkage 13933 /// specification that uses braces. 13934 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 13935 Decl *LinkageSpec, 13936 SourceLocation RBraceLoc) { 13937 if (RBraceLoc.isValid()) { 13938 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 13939 LSDecl->setRBraceLoc(RBraceLoc); 13940 } 13941 PopDeclContext(); 13942 return LinkageSpec; 13943 } 13944 13945 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 13946 const ParsedAttributesView &AttrList, 13947 SourceLocation SemiLoc) { 13948 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 13949 // Attribute declarations appertain to empty declaration so we handle 13950 // them here. 13951 ProcessDeclAttributeList(S, ED, AttrList); 13952 13953 CurContext->addDecl(ED); 13954 return ED; 13955 } 13956 13957 /// Perform semantic analysis for the variable declaration that 13958 /// occurs within a C++ catch clause, returning the newly-created 13959 /// variable. 13960 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 13961 TypeSourceInfo *TInfo, 13962 SourceLocation StartLoc, 13963 SourceLocation Loc, 13964 IdentifierInfo *Name) { 13965 bool Invalid = false; 13966 QualType ExDeclType = TInfo->getType(); 13967 13968 // Arrays and functions decay. 13969 if (ExDeclType->isArrayType()) 13970 ExDeclType = Context.getArrayDecayedType(ExDeclType); 13971 else if (ExDeclType->isFunctionType()) 13972 ExDeclType = Context.getPointerType(ExDeclType); 13973 13974 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 13975 // The exception-declaration shall not denote a pointer or reference to an 13976 // incomplete type, other than [cv] void*. 13977 // N2844 forbids rvalue references. 13978 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 13979 Diag(Loc, diag::err_catch_rvalue_ref); 13980 Invalid = true; 13981 } 13982 13983 if (ExDeclType->isVariablyModifiedType()) { 13984 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 13985 Invalid = true; 13986 } 13987 13988 QualType BaseType = ExDeclType; 13989 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 13990 unsigned DK = diag::err_catch_incomplete; 13991 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 13992 BaseType = Ptr->getPointeeType(); 13993 Mode = 1; 13994 DK = diag::err_catch_incomplete_ptr; 13995 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 13996 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 13997 BaseType = Ref->getPointeeType(); 13998 Mode = 2; 13999 DK = diag::err_catch_incomplete_ref; 14000 } 14001 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 14002 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 14003 Invalid = true; 14004 14005 if (!Invalid && !ExDeclType->isDependentType() && 14006 RequireNonAbstractType(Loc, ExDeclType, 14007 diag::err_abstract_type_in_decl, 14008 AbstractVariableType)) 14009 Invalid = true; 14010 14011 // Only the non-fragile NeXT runtime currently supports C++ catches 14012 // of ObjC types, and no runtime supports catching ObjC types by value. 14013 if (!Invalid && getLangOpts().ObjC) { 14014 QualType T = ExDeclType; 14015 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 14016 T = RT->getPointeeType(); 14017 14018 if (T->isObjCObjectType()) { 14019 Diag(Loc, diag::err_objc_object_catch); 14020 Invalid = true; 14021 } else if (T->isObjCObjectPointerType()) { 14022 // FIXME: should this be a test for macosx-fragile specifically? 14023 if (getLangOpts().ObjCRuntime.isFragile()) 14024 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 14025 } 14026 } 14027 14028 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 14029 ExDeclType, TInfo, SC_None); 14030 ExDecl->setExceptionVariable(true); 14031 14032 // In ARC, infer 'retaining' for variables of retainable type. 14033 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 14034 Invalid = true; 14035 14036 if (!Invalid && !ExDeclType->isDependentType()) { 14037 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 14038 // Insulate this from anything else we might currently be parsing. 14039 EnterExpressionEvaluationContext scope( 14040 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 14041 14042 // C++ [except.handle]p16: 14043 // The object declared in an exception-declaration or, if the 14044 // exception-declaration does not specify a name, a temporary (12.2) is 14045 // copy-initialized (8.5) from the exception object. [...] 14046 // The object is destroyed when the handler exits, after the destruction 14047 // of any automatic objects initialized within the handler. 14048 // 14049 // We just pretend to initialize the object with itself, then make sure 14050 // it can be destroyed later. 14051 QualType initType = Context.getExceptionObjectType(ExDeclType); 14052 14053 InitializedEntity entity = 14054 InitializedEntity::InitializeVariable(ExDecl); 14055 InitializationKind initKind = 14056 InitializationKind::CreateCopy(Loc, SourceLocation()); 14057 14058 Expr *opaqueValue = 14059 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 14060 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 14061 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 14062 if (result.isInvalid()) 14063 Invalid = true; 14064 else { 14065 // If the constructor used was non-trivial, set this as the 14066 // "initializer". 14067 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 14068 if (!construct->getConstructor()->isTrivial()) { 14069 Expr *init = MaybeCreateExprWithCleanups(construct); 14070 ExDecl->setInit(init); 14071 } 14072 14073 // And make sure it's destructable. 14074 FinalizeVarWithDestructor(ExDecl, recordType); 14075 } 14076 } 14077 } 14078 14079 if (Invalid) 14080 ExDecl->setInvalidDecl(); 14081 14082 return ExDecl; 14083 } 14084 14085 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 14086 /// handler. 14087 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 14088 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14089 bool Invalid = D.isInvalidType(); 14090 14091 // Check for unexpanded parameter packs. 14092 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14093 UPPC_ExceptionType)) { 14094 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 14095 D.getIdentifierLoc()); 14096 Invalid = true; 14097 } 14098 14099 IdentifierInfo *II = D.getIdentifier(); 14100 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 14101 LookupOrdinaryName, 14102 ForVisibleRedeclaration)) { 14103 // The scope should be freshly made just for us. There is just no way 14104 // it contains any previous declaration, except for function parameters in 14105 // a function-try-block's catch statement. 14106 assert(!S->isDeclScope(PrevDecl)); 14107 if (isDeclInScope(PrevDecl, CurContext, S)) { 14108 Diag(D.getIdentifierLoc(), diag::err_redefinition) 14109 << D.getIdentifier(); 14110 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 14111 Invalid = true; 14112 } else if (PrevDecl->isTemplateParameter()) 14113 // Maybe we will complain about the shadowed template parameter. 14114 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14115 } 14116 14117 if (D.getCXXScopeSpec().isSet() && !Invalid) { 14118 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 14119 << D.getCXXScopeSpec().getRange(); 14120 Invalid = true; 14121 } 14122 14123 VarDecl *ExDecl = BuildExceptionDeclaration( 14124 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 14125 if (Invalid) 14126 ExDecl->setInvalidDecl(); 14127 14128 // Add the exception declaration into this scope. 14129 if (II) 14130 PushOnScopeChains(ExDecl, S); 14131 else 14132 CurContext->addDecl(ExDecl); 14133 14134 ProcessDeclAttributes(S, ExDecl, D); 14135 return ExDecl; 14136 } 14137 14138 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 14139 Expr *AssertExpr, 14140 Expr *AssertMessageExpr, 14141 SourceLocation RParenLoc) { 14142 StringLiteral *AssertMessage = 14143 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 14144 14145 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 14146 return nullptr; 14147 14148 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 14149 AssertMessage, RParenLoc, false); 14150 } 14151 14152 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 14153 Expr *AssertExpr, 14154 StringLiteral *AssertMessage, 14155 SourceLocation RParenLoc, 14156 bool Failed) { 14157 assert(AssertExpr != nullptr && "Expected non-null condition"); 14158 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 14159 !Failed) { 14160 // In a static_assert-declaration, the constant-expression shall be a 14161 // constant expression that can be contextually converted to bool. 14162 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 14163 if (Converted.isInvalid()) 14164 Failed = true; 14165 14166 llvm::APSInt Cond; 14167 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 14168 diag::err_static_assert_expression_is_not_constant, 14169 /*AllowFold=*/false).isInvalid()) 14170 Failed = true; 14171 14172 if (!Failed && !Cond) { 14173 SmallString<256> MsgBuffer; 14174 llvm::raw_svector_ostream Msg(MsgBuffer); 14175 if (AssertMessage) 14176 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 14177 14178 Expr *InnerCond = nullptr; 14179 std::string InnerCondDescription; 14180 std::tie(InnerCond, InnerCondDescription) = 14181 findFailedBooleanCondition(Converted.get()); 14182 if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 14183 && !isa<IntegerLiteral>(InnerCond)) { 14184 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 14185 << InnerCondDescription << !AssertMessage 14186 << Msg.str() << InnerCond->getSourceRange(); 14187 } else { 14188 Diag(StaticAssertLoc, diag::err_static_assert_failed) 14189 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 14190 } 14191 Failed = true; 14192 } 14193 } 14194 14195 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 14196 /*DiscardedValue*/false, 14197 /*IsConstexpr*/true); 14198 if (FullAssertExpr.isInvalid()) 14199 Failed = true; 14200 else 14201 AssertExpr = FullAssertExpr.get(); 14202 14203 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 14204 AssertExpr, AssertMessage, RParenLoc, 14205 Failed); 14206 14207 CurContext->addDecl(Decl); 14208 return Decl; 14209 } 14210 14211 /// Perform semantic analysis of the given friend type declaration. 14212 /// 14213 /// \returns A friend declaration that. 14214 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 14215 SourceLocation FriendLoc, 14216 TypeSourceInfo *TSInfo) { 14217 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 14218 14219 QualType T = TSInfo->getType(); 14220 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 14221 14222 // C++03 [class.friend]p2: 14223 // An elaborated-type-specifier shall be used in a friend declaration 14224 // for a class.* 14225 // 14226 // * The class-key of the elaborated-type-specifier is required. 14227 if (!CodeSynthesisContexts.empty()) { 14228 // Do not complain about the form of friend template types during any kind 14229 // of code synthesis. For template instantiation, we will have complained 14230 // when the template was defined. 14231 } else { 14232 if (!T->isElaboratedTypeSpecifier()) { 14233 // If we evaluated the type to a record type, suggest putting 14234 // a tag in front. 14235 if (const RecordType *RT = T->getAs<RecordType>()) { 14236 RecordDecl *RD = RT->getDecl(); 14237 14238 SmallString<16> InsertionText(" "); 14239 InsertionText += RD->getKindName(); 14240 14241 Diag(TypeRange.getBegin(), 14242 getLangOpts().CPlusPlus11 ? 14243 diag::warn_cxx98_compat_unelaborated_friend_type : 14244 diag::ext_unelaborated_friend_type) 14245 << (unsigned) RD->getTagKind() 14246 << T 14247 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 14248 InsertionText); 14249 } else { 14250 Diag(FriendLoc, 14251 getLangOpts().CPlusPlus11 ? 14252 diag::warn_cxx98_compat_nonclass_type_friend : 14253 diag::ext_nonclass_type_friend) 14254 << T 14255 << TypeRange; 14256 } 14257 } else if (T->getAs<EnumType>()) { 14258 Diag(FriendLoc, 14259 getLangOpts().CPlusPlus11 ? 14260 diag::warn_cxx98_compat_enum_friend : 14261 diag::ext_enum_friend) 14262 << T 14263 << TypeRange; 14264 } 14265 14266 // C++11 [class.friend]p3: 14267 // A friend declaration that does not declare a function shall have one 14268 // of the following forms: 14269 // friend elaborated-type-specifier ; 14270 // friend simple-type-specifier ; 14271 // friend typename-specifier ; 14272 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 14273 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 14274 } 14275 14276 // If the type specifier in a friend declaration designates a (possibly 14277 // cv-qualified) class type, that class is declared as a friend; otherwise, 14278 // the friend declaration is ignored. 14279 return FriendDecl::Create(Context, CurContext, 14280 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 14281 FriendLoc); 14282 } 14283 14284 /// Handle a friend tag declaration where the scope specifier was 14285 /// templated. 14286 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 14287 unsigned TagSpec, SourceLocation TagLoc, 14288 CXXScopeSpec &SS, IdentifierInfo *Name, 14289 SourceLocation NameLoc, 14290 const ParsedAttributesView &Attr, 14291 MultiTemplateParamsArg TempParamLists) { 14292 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 14293 14294 bool IsMemberSpecialization = false; 14295 bool Invalid = false; 14296 14297 if (TemplateParameterList *TemplateParams = 14298 MatchTemplateParametersToScopeSpecifier( 14299 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 14300 IsMemberSpecialization, Invalid)) { 14301 if (TemplateParams->size() > 0) { 14302 // This is a declaration of a class template. 14303 if (Invalid) 14304 return nullptr; 14305 14306 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 14307 NameLoc, Attr, TemplateParams, AS_public, 14308 /*ModulePrivateLoc=*/SourceLocation(), 14309 FriendLoc, TempParamLists.size() - 1, 14310 TempParamLists.data()).get(); 14311 } else { 14312 // The "template<>" header is extraneous. 14313 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 14314 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 14315 IsMemberSpecialization = true; 14316 } 14317 } 14318 14319 if (Invalid) return nullptr; 14320 14321 bool isAllExplicitSpecializations = true; 14322 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 14323 if (TempParamLists[I]->size()) { 14324 isAllExplicitSpecializations = false; 14325 break; 14326 } 14327 } 14328 14329 // FIXME: don't ignore attributes. 14330 14331 // If it's explicit specializations all the way down, just forget 14332 // about the template header and build an appropriate non-templated 14333 // friend. TODO: for source fidelity, remember the headers. 14334 if (isAllExplicitSpecializations) { 14335 if (SS.isEmpty()) { 14336 bool Owned = false; 14337 bool IsDependent = false; 14338 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 14339 Attr, AS_public, 14340 /*ModulePrivateLoc=*/SourceLocation(), 14341 MultiTemplateParamsArg(), Owned, IsDependent, 14342 /*ScopedEnumKWLoc=*/SourceLocation(), 14343 /*ScopedEnumUsesClassTag=*/false, 14344 /*UnderlyingType=*/TypeResult(), 14345 /*IsTypeSpecifier=*/false, 14346 /*IsTemplateParamOrArg=*/false); 14347 } 14348 14349 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 14350 ElaboratedTypeKeyword Keyword 14351 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 14352 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 14353 *Name, NameLoc); 14354 if (T.isNull()) 14355 return nullptr; 14356 14357 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 14358 if (isa<DependentNameType>(T)) { 14359 DependentNameTypeLoc TL = 14360 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 14361 TL.setElaboratedKeywordLoc(TagLoc); 14362 TL.setQualifierLoc(QualifierLoc); 14363 TL.setNameLoc(NameLoc); 14364 } else { 14365 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 14366 TL.setElaboratedKeywordLoc(TagLoc); 14367 TL.setQualifierLoc(QualifierLoc); 14368 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 14369 } 14370 14371 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 14372 TSI, FriendLoc, TempParamLists); 14373 Friend->setAccess(AS_public); 14374 CurContext->addDecl(Friend); 14375 return Friend; 14376 } 14377 14378 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 14379 14380 14381 14382 // Handle the case of a templated-scope friend class. e.g. 14383 // template <class T> class A<T>::B; 14384 // FIXME: we don't support these right now. 14385 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 14386 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 14387 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 14388 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 14389 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 14390 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 14391 TL.setElaboratedKeywordLoc(TagLoc); 14392 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 14393 TL.setNameLoc(NameLoc); 14394 14395 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 14396 TSI, FriendLoc, TempParamLists); 14397 Friend->setAccess(AS_public); 14398 Friend->setUnsupportedFriend(true); 14399 CurContext->addDecl(Friend); 14400 return Friend; 14401 } 14402 14403 /// Handle a friend type declaration. This works in tandem with 14404 /// ActOnTag. 14405 /// 14406 /// Notes on friend class templates: 14407 /// 14408 /// We generally treat friend class declarations as if they were 14409 /// declaring a class. So, for example, the elaborated type specifier 14410 /// in a friend declaration is required to obey the restrictions of a 14411 /// class-head (i.e. no typedefs in the scope chain), template 14412 /// parameters are required to match up with simple template-ids, &c. 14413 /// However, unlike when declaring a template specialization, it's 14414 /// okay to refer to a template specialization without an empty 14415 /// template parameter declaration, e.g. 14416 /// friend class A<T>::B<unsigned>; 14417 /// We permit this as a special case; if there are any template 14418 /// parameters present at all, require proper matching, i.e. 14419 /// template <> template \<class T> friend class A<int>::B; 14420 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 14421 MultiTemplateParamsArg TempParams) { 14422 SourceLocation Loc = DS.getBeginLoc(); 14423 14424 assert(DS.isFriendSpecified()); 14425 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14426 14427 // C++ [class.friend]p3: 14428 // A friend declaration that does not declare a function shall have one of 14429 // the following forms: 14430 // friend elaborated-type-specifier ; 14431 // friend simple-type-specifier ; 14432 // friend typename-specifier ; 14433 // 14434 // Any declaration with a type qualifier does not have that form. (It's 14435 // legal to specify a qualified type as a friend, you just can't write the 14436 // keywords.) 14437 if (DS.getTypeQualifiers()) { 14438 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 14439 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 14440 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 14441 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 14442 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 14443 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 14444 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 14445 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 14446 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 14447 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 14448 } 14449 14450 // Try to convert the decl specifier to a type. This works for 14451 // friend templates because ActOnTag never produces a ClassTemplateDecl 14452 // for a TUK_Friend. 14453 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); 14454 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 14455 QualType T = TSI->getType(); 14456 if (TheDeclarator.isInvalidType()) 14457 return nullptr; 14458 14459 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 14460 return nullptr; 14461 14462 // This is definitely an error in C++98. It's probably meant to 14463 // be forbidden in C++0x, too, but the specification is just 14464 // poorly written. 14465 // 14466 // The problem is with declarations like the following: 14467 // template <T> friend A<T>::foo; 14468 // where deciding whether a class C is a friend or not now hinges 14469 // on whether there exists an instantiation of A that causes 14470 // 'foo' to equal C. There are restrictions on class-heads 14471 // (which we declare (by fiat) elaborated friend declarations to 14472 // be) that makes this tractable. 14473 // 14474 // FIXME: handle "template <> friend class A<T>;", which 14475 // is possibly well-formed? Who even knows? 14476 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 14477 Diag(Loc, diag::err_tagless_friend_type_template) 14478 << DS.getSourceRange(); 14479 return nullptr; 14480 } 14481 14482 // C++98 [class.friend]p1: A friend of a class is a function 14483 // or class that is not a member of the class . . . 14484 // This is fixed in DR77, which just barely didn't make the C++03 14485 // deadline. It's also a very silly restriction that seriously 14486 // affects inner classes and which nobody else seems to implement; 14487 // thus we never diagnose it, not even in -pedantic. 14488 // 14489 // But note that we could warn about it: it's always useless to 14490 // friend one of your own members (it's not, however, worthless to 14491 // friend a member of an arbitrary specialization of your template). 14492 14493 Decl *D; 14494 if (!TempParams.empty()) 14495 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 14496 TempParams, 14497 TSI, 14498 DS.getFriendSpecLoc()); 14499 else 14500 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 14501 14502 if (!D) 14503 return nullptr; 14504 14505 D->setAccess(AS_public); 14506 CurContext->addDecl(D); 14507 14508 return D; 14509 } 14510 14511 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 14512 MultiTemplateParamsArg TemplateParams) { 14513 const DeclSpec &DS = D.getDeclSpec(); 14514 14515 assert(DS.isFriendSpecified()); 14516 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14517 14518 SourceLocation Loc = D.getIdentifierLoc(); 14519 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14520 14521 // C++ [class.friend]p1 14522 // A friend of a class is a function or class.... 14523 // Note that this sees through typedefs, which is intended. 14524 // It *doesn't* see through dependent types, which is correct 14525 // according to [temp.arg.type]p3: 14526 // If a declaration acquires a function type through a 14527 // type dependent on a template-parameter and this causes 14528 // a declaration that does not use the syntactic form of a 14529 // function declarator to have a function type, the program 14530 // is ill-formed. 14531 if (!TInfo->getType()->isFunctionType()) { 14532 Diag(Loc, diag::err_unexpected_friend); 14533 14534 // It might be worthwhile to try to recover by creating an 14535 // appropriate declaration. 14536 return nullptr; 14537 } 14538 14539 // C++ [namespace.memdef]p3 14540 // - If a friend declaration in a non-local class first declares a 14541 // class or function, the friend class or function is a member 14542 // of the innermost enclosing namespace. 14543 // - The name of the friend is not found by simple name lookup 14544 // until a matching declaration is provided in that namespace 14545 // scope (either before or after the class declaration granting 14546 // friendship). 14547 // - If a friend function is called, its name may be found by the 14548 // name lookup that considers functions from namespaces and 14549 // classes associated with the types of the function arguments. 14550 // - When looking for a prior declaration of a class or a function 14551 // declared as a friend, scopes outside the innermost enclosing 14552 // namespace scope are not considered. 14553 14554 CXXScopeSpec &SS = D.getCXXScopeSpec(); 14555 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 14556 assert(NameInfo.getName()); 14557 14558 // Check for unexpanded parameter packs. 14559 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 14560 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 14561 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 14562 return nullptr; 14563 14564 // The context we found the declaration in, or in which we should 14565 // create the declaration. 14566 DeclContext *DC; 14567 Scope *DCScope = S; 14568 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 14569 ForExternalRedeclaration); 14570 14571 // There are five cases here. 14572 // - There's no scope specifier and we're in a local class. Only look 14573 // for functions declared in the immediately-enclosing block scope. 14574 // We recover from invalid scope qualifiers as if they just weren't there. 14575 FunctionDecl *FunctionContainingLocalClass = nullptr; 14576 if ((SS.isInvalid() || !SS.isSet()) && 14577 (FunctionContainingLocalClass = 14578 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 14579 // C++11 [class.friend]p11: 14580 // If a friend declaration appears in a local class and the name 14581 // specified is an unqualified name, a prior declaration is 14582 // looked up without considering scopes that are outside the 14583 // innermost enclosing non-class scope. For a friend function 14584 // declaration, if there is no prior declaration, the program is 14585 // ill-formed. 14586 14587 // Find the innermost enclosing non-class scope. This is the block 14588 // scope containing the local class definition (or for a nested class, 14589 // the outer local class). 14590 DCScope = S->getFnParent(); 14591 14592 // Look up the function name in the scope. 14593 Previous.clear(LookupLocalFriendName); 14594 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 14595 14596 if (!Previous.empty()) { 14597 // All possible previous declarations must have the same context: 14598 // either they were declared at block scope or they are members of 14599 // one of the enclosing local classes. 14600 DC = Previous.getRepresentativeDecl()->getDeclContext(); 14601 } else { 14602 // This is ill-formed, but provide the context that we would have 14603 // declared the function in, if we were permitted to, for error recovery. 14604 DC = FunctionContainingLocalClass; 14605 } 14606 adjustContextForLocalExternDecl(DC); 14607 14608 // C++ [class.friend]p6: 14609 // A function can be defined in a friend declaration of a class if and 14610 // only if the class is a non-local class (9.8), the function name is 14611 // unqualified, and the function has namespace scope. 14612 if (D.isFunctionDefinition()) { 14613 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 14614 } 14615 14616 // - There's no scope specifier, in which case we just go to the 14617 // appropriate scope and look for a function or function template 14618 // there as appropriate. 14619 } else if (SS.isInvalid() || !SS.isSet()) { 14620 // C++11 [namespace.memdef]p3: 14621 // If the name in a friend declaration is neither qualified nor 14622 // a template-id and the declaration is a function or an 14623 // elaborated-type-specifier, the lookup to determine whether 14624 // the entity has been previously declared shall not consider 14625 // any scopes outside the innermost enclosing namespace. 14626 bool isTemplateId = 14627 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 14628 14629 // Find the appropriate context according to the above. 14630 DC = CurContext; 14631 14632 // Skip class contexts. If someone can cite chapter and verse 14633 // for this behavior, that would be nice --- it's what GCC and 14634 // EDG do, and it seems like a reasonable intent, but the spec 14635 // really only says that checks for unqualified existing 14636 // declarations should stop at the nearest enclosing namespace, 14637 // not that they should only consider the nearest enclosing 14638 // namespace. 14639 while (DC->isRecord()) 14640 DC = DC->getParent(); 14641 14642 DeclContext *LookupDC = DC; 14643 while (LookupDC->isTransparentContext()) 14644 LookupDC = LookupDC->getParent(); 14645 14646 while (true) { 14647 LookupQualifiedName(Previous, LookupDC); 14648 14649 if (!Previous.empty()) { 14650 DC = LookupDC; 14651 break; 14652 } 14653 14654 if (isTemplateId) { 14655 if (isa<TranslationUnitDecl>(LookupDC)) break; 14656 } else { 14657 if (LookupDC->isFileContext()) break; 14658 } 14659 LookupDC = LookupDC->getParent(); 14660 } 14661 14662 DCScope = getScopeForDeclContext(S, DC); 14663 14664 // - There's a non-dependent scope specifier, in which case we 14665 // compute it and do a previous lookup there for a function 14666 // or function template. 14667 } else if (!SS.getScopeRep()->isDependent()) { 14668 DC = computeDeclContext(SS); 14669 if (!DC) return nullptr; 14670 14671 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 14672 14673 LookupQualifiedName(Previous, DC); 14674 14675 // C++ [class.friend]p1: A friend of a class is a function or 14676 // class that is not a member of the class . . . 14677 if (DC->Equals(CurContext)) 14678 Diag(DS.getFriendSpecLoc(), 14679 getLangOpts().CPlusPlus11 ? 14680 diag::warn_cxx98_compat_friend_is_member : 14681 diag::err_friend_is_member); 14682 14683 if (D.isFunctionDefinition()) { 14684 // C++ [class.friend]p6: 14685 // A function can be defined in a friend declaration of a class if and 14686 // only if the class is a non-local class (9.8), the function name is 14687 // unqualified, and the function has namespace scope. 14688 // 14689 // FIXME: We should only do this if the scope specifier names the 14690 // innermost enclosing namespace; otherwise the fixit changes the 14691 // meaning of the code. 14692 SemaDiagnosticBuilder DB 14693 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 14694 14695 DB << SS.getScopeRep(); 14696 if (DC->isFileContext()) 14697 DB << FixItHint::CreateRemoval(SS.getRange()); 14698 SS.clear(); 14699 } 14700 14701 // - There's a scope specifier that does not match any template 14702 // parameter lists, in which case we use some arbitrary context, 14703 // create a method or method template, and wait for instantiation. 14704 // - There's a scope specifier that does match some template 14705 // parameter lists, which we don't handle right now. 14706 } else { 14707 if (D.isFunctionDefinition()) { 14708 // C++ [class.friend]p6: 14709 // A function can be defined in a friend declaration of a class if and 14710 // only if the class is a non-local class (9.8), the function name is 14711 // unqualified, and the function has namespace scope. 14712 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 14713 << SS.getScopeRep(); 14714 } 14715 14716 DC = CurContext; 14717 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 14718 } 14719 14720 if (!DC->isRecord()) { 14721 int DiagArg = -1; 14722 switch (D.getName().getKind()) { 14723 case UnqualifiedIdKind::IK_ConstructorTemplateId: 14724 case UnqualifiedIdKind::IK_ConstructorName: 14725 DiagArg = 0; 14726 break; 14727 case UnqualifiedIdKind::IK_DestructorName: 14728 DiagArg = 1; 14729 break; 14730 case UnqualifiedIdKind::IK_ConversionFunctionId: 14731 DiagArg = 2; 14732 break; 14733 case UnqualifiedIdKind::IK_DeductionGuideName: 14734 DiagArg = 3; 14735 break; 14736 case UnqualifiedIdKind::IK_Identifier: 14737 case UnqualifiedIdKind::IK_ImplicitSelfParam: 14738 case UnqualifiedIdKind::IK_LiteralOperatorId: 14739 case UnqualifiedIdKind::IK_OperatorFunctionId: 14740 case UnqualifiedIdKind::IK_TemplateId: 14741 break; 14742 } 14743 // This implies that it has to be an operator or function. 14744 if (DiagArg >= 0) { 14745 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 14746 return nullptr; 14747 } 14748 } 14749 14750 // FIXME: This is an egregious hack to cope with cases where the scope stack 14751 // does not contain the declaration context, i.e., in an out-of-line 14752 // definition of a class. 14753 Scope FakeDCScope(S, Scope::DeclScope, Diags); 14754 if (!DCScope) { 14755 FakeDCScope.setEntity(DC); 14756 DCScope = &FakeDCScope; 14757 } 14758 14759 bool AddToScope = true; 14760 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 14761 TemplateParams, AddToScope); 14762 if (!ND) return nullptr; 14763 14764 assert(ND->getLexicalDeclContext() == CurContext); 14765 14766 // If we performed typo correction, we might have added a scope specifier 14767 // and changed the decl context. 14768 DC = ND->getDeclContext(); 14769 14770 // Add the function declaration to the appropriate lookup tables, 14771 // adjusting the redeclarations list as necessary. We don't 14772 // want to do this yet if the friending class is dependent. 14773 // 14774 // Also update the scope-based lookup if the target context's 14775 // lookup context is in lexical scope. 14776 if (!CurContext->isDependentContext()) { 14777 DC = DC->getRedeclContext(); 14778 DC->makeDeclVisibleInContext(ND); 14779 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14780 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 14781 } 14782 14783 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 14784 D.getIdentifierLoc(), ND, 14785 DS.getFriendSpecLoc()); 14786 FrD->setAccess(AS_public); 14787 CurContext->addDecl(FrD); 14788 14789 if (ND->isInvalidDecl()) { 14790 FrD->setInvalidDecl(); 14791 } else { 14792 if (DC->isRecord()) CheckFriendAccess(ND); 14793 14794 FunctionDecl *FD; 14795 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 14796 FD = FTD->getTemplatedDecl(); 14797 else 14798 FD = cast<FunctionDecl>(ND); 14799 14800 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 14801 // default argument expression, that declaration shall be a definition 14802 // and shall be the only declaration of the function or function 14803 // template in the translation unit. 14804 if (functionDeclHasDefaultArgument(FD)) { 14805 // We can't look at FD->getPreviousDecl() because it may not have been set 14806 // if we're in a dependent context. If the function is known to be a 14807 // redeclaration, we will have narrowed Previous down to the right decl. 14808 if (D.isRedeclaration()) { 14809 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 14810 Diag(Previous.getRepresentativeDecl()->getLocation(), 14811 diag::note_previous_declaration); 14812 } else if (!D.isFunctionDefinition()) 14813 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 14814 } 14815 14816 // Mark templated-scope function declarations as unsupported. 14817 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 14818 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 14819 << SS.getScopeRep() << SS.getRange() 14820 << cast<CXXRecordDecl>(CurContext); 14821 FrD->setUnsupportedFriend(true); 14822 } 14823 } 14824 14825 return ND; 14826 } 14827 14828 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 14829 AdjustDeclIfTemplate(Dcl); 14830 14831 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 14832 if (!Fn) { 14833 Diag(DelLoc, diag::err_deleted_non_function); 14834 return; 14835 } 14836 14837 // Deleted function does not have a body. 14838 Fn->setWillHaveBody(false); 14839 14840 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 14841 // Don't consider the implicit declaration we generate for explicit 14842 // specializations. FIXME: Do not generate these implicit declarations. 14843 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 14844 Prev->getPreviousDecl()) && 14845 !Prev->isDefined()) { 14846 Diag(DelLoc, diag::err_deleted_decl_not_first); 14847 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 14848 Prev->isImplicit() ? diag::note_previous_implicit_declaration 14849 : diag::note_previous_declaration); 14850 } 14851 // If the declaration wasn't the first, we delete the function anyway for 14852 // recovery. 14853 Fn = Fn->getCanonicalDecl(); 14854 } 14855 14856 // dllimport/dllexport cannot be deleted. 14857 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 14858 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 14859 Fn->setInvalidDecl(); 14860 } 14861 14862 if (Fn->isDeleted()) 14863 return; 14864 14865 // See if we're deleting a function which is already known to override a 14866 // non-deleted virtual function. 14867 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 14868 bool IssuedDiagnostic = false; 14869 for (const CXXMethodDecl *O : MD->overridden_methods()) { 14870 if (!(*MD->begin_overridden_methods())->isDeleted()) { 14871 if (!IssuedDiagnostic) { 14872 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 14873 IssuedDiagnostic = true; 14874 } 14875 Diag(O->getLocation(), diag::note_overridden_virtual_function); 14876 } 14877 } 14878 // If this function was implicitly deleted because it was defaulted, 14879 // explain why it was deleted. 14880 if (IssuedDiagnostic && MD->isDefaulted()) 14881 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, 14882 /*Diagnose*/true); 14883 } 14884 14885 // C++11 [basic.start.main]p3: 14886 // A program that defines main as deleted [...] is ill-formed. 14887 if (Fn->isMain()) 14888 Diag(DelLoc, diag::err_deleted_main); 14889 14890 // C++11 [dcl.fct.def.delete]p4: 14891 // A deleted function is implicitly inline. 14892 Fn->setImplicitlyInline(); 14893 Fn->setDeletedAsWritten(); 14894 } 14895 14896 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 14897 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 14898 14899 if (MD) { 14900 if (MD->getParent()->isDependentType()) { 14901 MD->setDefaulted(); 14902 MD->setExplicitlyDefaulted(); 14903 return; 14904 } 14905 14906 CXXSpecialMember Member = getSpecialMember(MD); 14907 if (Member == CXXInvalid) { 14908 if (!MD->isInvalidDecl()) 14909 Diag(DefaultLoc, diag::err_default_special_members); 14910 return; 14911 } 14912 14913 MD->setDefaulted(); 14914 MD->setExplicitlyDefaulted(); 14915 14916 // Unset that we will have a body for this function. We might not, 14917 // if it turns out to be trivial, and we don't need this marking now 14918 // that we've marked it as defaulted. 14919 MD->setWillHaveBody(false); 14920 14921 // If this definition appears within the record, do the checking when 14922 // the record is complete. 14923 const FunctionDecl *Primary = MD; 14924 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 14925 // Ask the template instantiation pattern that actually had the 14926 // '= default' on it. 14927 Primary = Pattern; 14928 14929 // If the method was defaulted on its first declaration, we will have 14930 // already performed the checking in CheckCompletedCXXClass. Such a 14931 // declaration doesn't trigger an implicit definition. 14932 if (Primary->getCanonicalDecl()->isDefaulted()) 14933 return; 14934 14935 CheckExplicitlyDefaultedSpecialMember(MD); 14936 14937 if (!MD->isInvalidDecl()) 14938 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 14939 } else { 14940 Diag(DefaultLoc, diag::err_default_special_members); 14941 } 14942 } 14943 14944 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 14945 for (Stmt *SubStmt : S->children()) { 14946 if (!SubStmt) 14947 continue; 14948 if (isa<ReturnStmt>(SubStmt)) 14949 Self.Diag(SubStmt->getBeginLoc(), 14950 diag::err_return_in_constructor_handler); 14951 if (!isa<Expr>(SubStmt)) 14952 SearchForReturnInStmt(Self, SubStmt); 14953 } 14954 } 14955 14956 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 14957 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 14958 CXXCatchStmt *Handler = TryBlock->getHandler(I); 14959 SearchForReturnInStmt(*this, Handler); 14960 } 14961 } 14962 14963 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 14964 const CXXMethodDecl *Old) { 14965 const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); 14966 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); 14967 14968 if (OldFT->hasExtParameterInfos()) { 14969 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 14970 // A parameter of the overriding method should be annotated with noescape 14971 // if the corresponding parameter of the overridden method is annotated. 14972 if (OldFT->getExtParameterInfo(I).isNoEscape() && 14973 !NewFT->getExtParameterInfo(I).isNoEscape()) { 14974 Diag(New->getParamDecl(I)->getLocation(), 14975 diag::warn_overriding_method_missing_noescape); 14976 Diag(Old->getParamDecl(I)->getLocation(), 14977 diag::note_overridden_marked_noescape); 14978 } 14979 } 14980 14981 // Virtual overrides must have the same code_seg. 14982 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 14983 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 14984 if ((NewCSA || OldCSA) && 14985 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 14986 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 14987 Diag(Old->getLocation(), diag::note_previous_declaration); 14988 return true; 14989 } 14990 14991 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 14992 14993 // If the calling conventions match, everything is fine 14994 if (NewCC == OldCC) 14995 return false; 14996 14997 // If the calling conventions mismatch because the new function is static, 14998 // suppress the calling convention mismatch error; the error about static 14999 // function override (err_static_overrides_virtual from 15000 // Sema::CheckFunctionDeclaration) is more clear. 15001 if (New->getStorageClass() == SC_Static) 15002 return false; 15003 15004 Diag(New->getLocation(), 15005 diag::err_conflicting_overriding_cc_attributes) 15006 << New->getDeclName() << New->getType() << Old->getType(); 15007 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 15008 return true; 15009 } 15010 15011 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 15012 const CXXMethodDecl *Old) { 15013 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 15014 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 15015 15016 if (Context.hasSameType(NewTy, OldTy) || 15017 NewTy->isDependentType() || OldTy->isDependentType()) 15018 return false; 15019 15020 // Check if the return types are covariant 15021 QualType NewClassTy, OldClassTy; 15022 15023 /// Both types must be pointers or references to classes. 15024 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 15025 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 15026 NewClassTy = NewPT->getPointeeType(); 15027 OldClassTy = OldPT->getPointeeType(); 15028 } 15029 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 15030 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 15031 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 15032 NewClassTy = NewRT->getPointeeType(); 15033 OldClassTy = OldRT->getPointeeType(); 15034 } 15035 } 15036 } 15037 15038 // The return types aren't either both pointers or references to a class type. 15039 if (NewClassTy.isNull()) { 15040 Diag(New->getLocation(), 15041 diag::err_different_return_type_for_overriding_virtual_function) 15042 << New->getDeclName() << NewTy << OldTy 15043 << New->getReturnTypeSourceRange(); 15044 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 15045 << Old->getReturnTypeSourceRange(); 15046 15047 return true; 15048 } 15049 15050 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 15051 // C++14 [class.virtual]p8: 15052 // If the class type in the covariant return type of D::f differs from 15053 // that of B::f, the class type in the return type of D::f shall be 15054 // complete at the point of declaration of D::f or shall be the class 15055 // type D. 15056 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 15057 if (!RT->isBeingDefined() && 15058 RequireCompleteType(New->getLocation(), NewClassTy, 15059 diag::err_covariant_return_incomplete, 15060 New->getDeclName())) 15061 return true; 15062 } 15063 15064 // Check if the new class derives from the old class. 15065 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 15066 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 15067 << New->getDeclName() << NewTy << OldTy 15068 << New->getReturnTypeSourceRange(); 15069 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 15070 << Old->getReturnTypeSourceRange(); 15071 return true; 15072 } 15073 15074 // Check if we the conversion from derived to base is valid. 15075 if (CheckDerivedToBaseConversion( 15076 NewClassTy, OldClassTy, 15077 diag::err_covariant_return_inaccessible_base, 15078 diag::err_covariant_return_ambiguous_derived_to_base_conv, 15079 New->getLocation(), New->getReturnTypeSourceRange(), 15080 New->getDeclName(), nullptr)) { 15081 // FIXME: this note won't trigger for delayed access control 15082 // diagnostics, and it's impossible to get an undelayed error 15083 // here from access control during the original parse because 15084 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 15085 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 15086 << Old->getReturnTypeSourceRange(); 15087 return true; 15088 } 15089 } 15090 15091 // The qualifiers of the return types must be the same. 15092 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 15093 Diag(New->getLocation(), 15094 diag::err_covariant_return_type_different_qualifications) 15095 << New->getDeclName() << NewTy << OldTy 15096 << New->getReturnTypeSourceRange(); 15097 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 15098 << Old->getReturnTypeSourceRange(); 15099 return true; 15100 } 15101 15102 15103 // The new class type must have the same or less qualifiers as the old type. 15104 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 15105 Diag(New->getLocation(), 15106 diag::err_covariant_return_type_class_type_more_qualified) 15107 << New->getDeclName() << NewTy << OldTy 15108 << New->getReturnTypeSourceRange(); 15109 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 15110 << Old->getReturnTypeSourceRange(); 15111 return true; 15112 } 15113 15114 return false; 15115 } 15116 15117 /// Mark the given method pure. 15118 /// 15119 /// \param Method the method to be marked pure. 15120 /// 15121 /// \param InitRange the source range that covers the "0" initializer. 15122 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 15123 SourceLocation EndLoc = InitRange.getEnd(); 15124 if (EndLoc.isValid()) 15125 Method->setRangeEnd(EndLoc); 15126 15127 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 15128 Method->setPure(); 15129 return false; 15130 } 15131 15132 if (!Method->isInvalidDecl()) 15133 Diag(Method->getLocation(), diag::err_non_virtual_pure) 15134 << Method->getDeclName() << InitRange; 15135 return true; 15136 } 15137 15138 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 15139 if (D->getFriendObjectKind()) 15140 Diag(D->getLocation(), diag::err_pure_friend); 15141 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 15142 CheckPureMethod(M, ZeroLoc); 15143 else 15144 Diag(D->getLocation(), diag::err_illegal_initializer); 15145 } 15146 15147 /// Determine whether the given declaration is a global variable or 15148 /// static data member. 15149 static bool isNonlocalVariable(const Decl *D) { 15150 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 15151 return Var->hasGlobalStorage(); 15152 15153 return false; 15154 } 15155 15156 /// Invoked when we are about to parse an initializer for the declaration 15157 /// 'Dcl'. 15158 /// 15159 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 15160 /// static data member of class X, names should be looked up in the scope of 15161 /// class X. If the declaration had a scope specifier, a scope will have 15162 /// been created and passed in for this purpose. Otherwise, S will be null. 15163 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 15164 // If there is no declaration, there was an error parsing it. 15165 if (!D || D->isInvalidDecl()) 15166 return; 15167 15168 // We will always have a nested name specifier here, but this declaration 15169 // might not be out of line if the specifier names the current namespace: 15170 // extern int n; 15171 // int ::n = 0; 15172 if (S && D->isOutOfLine()) 15173 EnterDeclaratorContext(S, D->getDeclContext()); 15174 15175 // If we are parsing the initializer for a static data member, push a 15176 // new expression evaluation context that is associated with this static 15177 // data member. 15178 if (isNonlocalVariable(D)) 15179 PushExpressionEvaluationContext( 15180 ExpressionEvaluationContext::PotentiallyEvaluated, D); 15181 } 15182 15183 /// Invoked after we are finished parsing an initializer for the declaration D. 15184 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 15185 // If there is no declaration, there was an error parsing it. 15186 if (!D || D->isInvalidDecl()) 15187 return; 15188 15189 if (isNonlocalVariable(D)) 15190 PopExpressionEvaluationContext(); 15191 15192 if (S && D->isOutOfLine()) 15193 ExitDeclaratorContext(S); 15194 } 15195 15196 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 15197 /// C++ if/switch/while/for statement. 15198 /// e.g: "if (int x = f()) {...}" 15199 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 15200 // C++ 6.4p2: 15201 // The declarator shall not specify a function or an array. 15202 // The type-specifier-seq shall not contain typedef and shall not declare a 15203 // new class or enumeration. 15204 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 15205 "Parser allowed 'typedef' as storage class of condition decl."); 15206 15207 Decl *Dcl = ActOnDeclarator(S, D); 15208 if (!Dcl) 15209 return true; 15210 15211 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 15212 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 15213 << D.getSourceRange(); 15214 return true; 15215 } 15216 15217 return Dcl; 15218 } 15219 15220 void Sema::LoadExternalVTableUses() { 15221 if (!ExternalSource) 15222 return; 15223 15224 SmallVector<ExternalVTableUse, 4> VTables; 15225 ExternalSource->ReadUsedVTables(VTables); 15226 SmallVector<VTableUse, 4> NewUses; 15227 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 15228 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 15229 = VTablesUsed.find(VTables[I].Record); 15230 // Even if a definition wasn't required before, it may be required now. 15231 if (Pos != VTablesUsed.end()) { 15232 if (!Pos->second && VTables[I].DefinitionRequired) 15233 Pos->second = true; 15234 continue; 15235 } 15236 15237 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 15238 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 15239 } 15240 15241 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 15242 } 15243 15244 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 15245 bool DefinitionRequired) { 15246 // Ignore any vtable uses in unevaluated operands or for classes that do 15247 // not have a vtable. 15248 if (!Class->isDynamicClass() || Class->isDependentContext() || 15249 CurContext->isDependentContext() || isUnevaluatedContext()) 15250 return; 15251 // Do not mark as used if compiling for the device outside of the target 15252 // region. 15253 if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 15254 !isInOpenMPDeclareTargetContext() && 15255 !isInOpenMPTargetExecutionDirective()) { 15256 if (!DefinitionRequired) 15257 MarkVirtualMembersReferenced(Loc, Class); 15258 return; 15259 } 15260 15261 // Try to insert this class into the map. 15262 LoadExternalVTableUses(); 15263 Class = Class->getCanonicalDecl(); 15264 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 15265 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 15266 if (!Pos.second) { 15267 // If we already had an entry, check to see if we are promoting this vtable 15268 // to require a definition. If so, we need to reappend to the VTableUses 15269 // list, since we may have already processed the first entry. 15270 if (DefinitionRequired && !Pos.first->second) { 15271 Pos.first->second = true; 15272 } else { 15273 // Otherwise, we can early exit. 15274 return; 15275 } 15276 } else { 15277 // The Microsoft ABI requires that we perform the destructor body 15278 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 15279 // the deleting destructor is emitted with the vtable, not with the 15280 // destructor definition as in the Itanium ABI. 15281 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 15282 CXXDestructorDecl *DD = Class->getDestructor(); 15283 if (DD && DD->isVirtual() && !DD->isDeleted()) { 15284 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 15285 // If this is an out-of-line declaration, marking it referenced will 15286 // not do anything. Manually call CheckDestructor to look up operator 15287 // delete(). 15288 ContextRAII SavedContext(*this, DD); 15289 CheckDestructor(DD); 15290 } else { 15291 MarkFunctionReferenced(Loc, Class->getDestructor()); 15292 } 15293 } 15294 } 15295 } 15296 15297 // Local classes need to have their virtual members marked 15298 // immediately. For all other classes, we mark their virtual members 15299 // at the end of the translation unit. 15300 if (Class->isLocalClass()) 15301 MarkVirtualMembersReferenced(Loc, Class); 15302 else 15303 VTableUses.push_back(std::make_pair(Class, Loc)); 15304 } 15305 15306 bool Sema::DefineUsedVTables() { 15307 LoadExternalVTableUses(); 15308 if (VTableUses.empty()) 15309 return false; 15310 15311 // Note: The VTableUses vector could grow as a result of marking 15312 // the members of a class as "used", so we check the size each 15313 // time through the loop and prefer indices (which are stable) to 15314 // iterators (which are not). 15315 bool DefinedAnything = false; 15316 for (unsigned I = 0; I != VTableUses.size(); ++I) { 15317 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 15318 if (!Class) 15319 continue; 15320 TemplateSpecializationKind ClassTSK = 15321 Class->getTemplateSpecializationKind(); 15322 15323 SourceLocation Loc = VTableUses[I].second; 15324 15325 bool DefineVTable = true; 15326 15327 // If this class has a key function, but that key function is 15328 // defined in another translation unit, we don't need to emit the 15329 // vtable even though we're using it. 15330 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 15331 if (KeyFunction && !KeyFunction->hasBody()) { 15332 // The key function is in another translation unit. 15333 DefineVTable = false; 15334 TemplateSpecializationKind TSK = 15335 KeyFunction->getTemplateSpecializationKind(); 15336 assert(TSK != TSK_ExplicitInstantiationDefinition && 15337 TSK != TSK_ImplicitInstantiation && 15338 "Instantiations don't have key functions"); 15339 (void)TSK; 15340 } else if (!KeyFunction) { 15341 // If we have a class with no key function that is the subject 15342 // of an explicit instantiation declaration, suppress the 15343 // vtable; it will live with the explicit instantiation 15344 // definition. 15345 bool IsExplicitInstantiationDeclaration = 15346 ClassTSK == TSK_ExplicitInstantiationDeclaration; 15347 for (auto R : Class->redecls()) { 15348 TemplateSpecializationKind TSK 15349 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 15350 if (TSK == TSK_ExplicitInstantiationDeclaration) 15351 IsExplicitInstantiationDeclaration = true; 15352 else if (TSK == TSK_ExplicitInstantiationDefinition) { 15353 IsExplicitInstantiationDeclaration = false; 15354 break; 15355 } 15356 } 15357 15358 if (IsExplicitInstantiationDeclaration) 15359 DefineVTable = false; 15360 } 15361 15362 // The exception specifications for all virtual members may be needed even 15363 // if we are not providing an authoritative form of the vtable in this TU. 15364 // We may choose to emit it available_externally anyway. 15365 if (!DefineVTable) { 15366 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 15367 continue; 15368 } 15369 15370 // Mark all of the virtual members of this class as referenced, so 15371 // that we can build a vtable. Then, tell the AST consumer that a 15372 // vtable for this class is required. 15373 DefinedAnything = true; 15374 MarkVirtualMembersReferenced(Loc, Class); 15375 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 15376 if (VTablesUsed[Canonical]) 15377 Consumer.HandleVTable(Class); 15378 15379 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 15380 // no key function or the key function is inlined. Don't warn in C++ ABIs 15381 // that lack key functions, since the user won't be able to make one. 15382 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 15383 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 15384 const FunctionDecl *KeyFunctionDef = nullptr; 15385 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 15386 KeyFunctionDef->isInlined())) { 15387 Diag(Class->getLocation(), 15388 ClassTSK == TSK_ExplicitInstantiationDefinition 15389 ? diag::warn_weak_template_vtable 15390 : diag::warn_weak_vtable) 15391 << Class; 15392 } 15393 } 15394 } 15395 VTableUses.clear(); 15396 15397 return DefinedAnything; 15398 } 15399 15400 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 15401 const CXXRecordDecl *RD) { 15402 for (const auto *I : RD->methods()) 15403 if (I->isVirtual() && !I->isPure()) 15404 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 15405 } 15406 15407 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 15408 const CXXRecordDecl *RD, 15409 bool ConstexprOnly) { 15410 // Mark all functions which will appear in RD's vtable as used. 15411 CXXFinalOverriderMap FinalOverriders; 15412 RD->getFinalOverriders(FinalOverriders); 15413 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 15414 E = FinalOverriders.end(); 15415 I != E; ++I) { 15416 for (OverridingMethods::const_iterator OI = I->second.begin(), 15417 OE = I->second.end(); 15418 OI != OE; ++OI) { 15419 assert(OI->second.size() > 0 && "no final overrider"); 15420 CXXMethodDecl *Overrider = OI->second.front().Method; 15421 15422 // C++ [basic.def.odr]p2: 15423 // [...] A virtual member function is used if it is not pure. [...] 15424 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 15425 MarkFunctionReferenced(Loc, Overrider); 15426 } 15427 } 15428 15429 // Only classes that have virtual bases need a VTT. 15430 if (RD->getNumVBases() == 0) 15431 return; 15432 15433 for (const auto &I : RD->bases()) { 15434 const CXXRecordDecl *Base = 15435 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 15436 if (Base->getNumVBases() == 0) 15437 continue; 15438 MarkVirtualMembersReferenced(Loc, Base); 15439 } 15440 } 15441 15442 /// SetIvarInitializers - This routine builds initialization ASTs for the 15443 /// Objective-C implementation whose ivars need be initialized. 15444 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 15445 if (!getLangOpts().CPlusPlus) 15446 return; 15447 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 15448 SmallVector<ObjCIvarDecl*, 8> ivars; 15449 CollectIvarsToConstructOrDestruct(OID, ivars); 15450 if (ivars.empty()) 15451 return; 15452 SmallVector<CXXCtorInitializer*, 32> AllToInit; 15453 for (unsigned i = 0; i < ivars.size(); i++) { 15454 FieldDecl *Field = ivars[i]; 15455 if (Field->isInvalidDecl()) 15456 continue; 15457 15458 CXXCtorInitializer *Member; 15459 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 15460 InitializationKind InitKind = 15461 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 15462 15463 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 15464 ExprResult MemberInit = 15465 InitSeq.Perform(*this, InitEntity, InitKind, None); 15466 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 15467 // Note, MemberInit could actually come back empty if no initialization 15468 // is required (e.g., because it would call a trivial default constructor) 15469 if (!MemberInit.get() || MemberInit.isInvalid()) 15470 continue; 15471 15472 Member = 15473 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 15474 SourceLocation(), 15475 MemberInit.getAs<Expr>(), 15476 SourceLocation()); 15477 AllToInit.push_back(Member); 15478 15479 // Be sure that the destructor is accessible and is marked as referenced. 15480 if (const RecordType *RecordTy = 15481 Context.getBaseElementType(Field->getType()) 15482 ->getAs<RecordType>()) { 15483 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 15484 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 15485 MarkFunctionReferenced(Field->getLocation(), Destructor); 15486 CheckDestructorAccess(Field->getLocation(), Destructor, 15487 PDiag(diag::err_access_dtor_ivar) 15488 << Context.getBaseElementType(Field->getType())); 15489 } 15490 } 15491 } 15492 ObjCImplementation->setIvarInitializers(Context, 15493 AllToInit.data(), AllToInit.size()); 15494 } 15495 } 15496 15497 static 15498 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 15499 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 15500 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 15501 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 15502 Sema &S) { 15503 if (Ctor->isInvalidDecl()) 15504 return; 15505 15506 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 15507 15508 // Target may not be determinable yet, for instance if this is a dependent 15509 // call in an uninstantiated template. 15510 if (Target) { 15511 const FunctionDecl *FNTarget = nullptr; 15512 (void)Target->hasBody(FNTarget); 15513 Target = const_cast<CXXConstructorDecl*>( 15514 cast_or_null<CXXConstructorDecl>(FNTarget)); 15515 } 15516 15517 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 15518 // Avoid dereferencing a null pointer here. 15519 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 15520 15521 if (!Current.insert(Canonical).second) 15522 return; 15523 15524 // We know that beyond here, we aren't chaining into a cycle. 15525 if (!Target || !Target->isDelegatingConstructor() || 15526 Target->isInvalidDecl() || Valid.count(TCanonical)) { 15527 Valid.insert(Current.begin(), Current.end()); 15528 Current.clear(); 15529 // We've hit a cycle. 15530 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 15531 Current.count(TCanonical)) { 15532 // If we haven't diagnosed this cycle yet, do so now. 15533 if (!Invalid.count(TCanonical)) { 15534 S.Diag((*Ctor->init_begin())->getSourceLocation(), 15535 diag::warn_delegating_ctor_cycle) 15536 << Ctor; 15537 15538 // Don't add a note for a function delegating directly to itself. 15539 if (TCanonical != Canonical) 15540 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 15541 15542 CXXConstructorDecl *C = Target; 15543 while (C->getCanonicalDecl() != Canonical) { 15544 const FunctionDecl *FNTarget = nullptr; 15545 (void)C->getTargetConstructor()->hasBody(FNTarget); 15546 assert(FNTarget && "Ctor cycle through bodiless function"); 15547 15548 C = const_cast<CXXConstructorDecl*>( 15549 cast<CXXConstructorDecl>(FNTarget)); 15550 S.Diag(C->getLocation(), diag::note_which_delegates_to); 15551 } 15552 } 15553 15554 Invalid.insert(Current.begin(), Current.end()); 15555 Current.clear(); 15556 } else { 15557 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 15558 } 15559 } 15560 15561 15562 void Sema::CheckDelegatingCtorCycles() { 15563 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 15564 15565 for (DelegatingCtorDeclsType::iterator 15566 I = DelegatingCtorDecls.begin(ExternalSource), 15567 E = DelegatingCtorDecls.end(); 15568 I != E; ++I) 15569 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 15570 15571 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 15572 (*CI)->setInvalidDecl(); 15573 } 15574 15575 namespace { 15576 /// AST visitor that finds references to the 'this' expression. 15577 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 15578 Sema &S; 15579 15580 public: 15581 explicit FindCXXThisExpr(Sema &S) : S(S) { } 15582 15583 bool VisitCXXThisExpr(CXXThisExpr *E) { 15584 S.Diag(E->getLocation(), diag::err_this_static_member_func) 15585 << E->isImplicit(); 15586 return false; 15587 } 15588 }; 15589 } 15590 15591 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 15592 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15593 if (!TSInfo) 15594 return false; 15595 15596 TypeLoc TL = TSInfo->getTypeLoc(); 15597 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15598 if (!ProtoTL) 15599 return false; 15600 15601 // C++11 [expr.prim.general]p3: 15602 // [The expression this] shall not appear before the optional 15603 // cv-qualifier-seq and it shall not appear within the declaration of a 15604 // static member function (although its type and value category are defined 15605 // within a static member function as they are within a non-static member 15606 // function). [ Note: this is because declaration matching does not occur 15607 // until the complete declarator is known. - end note ] 15608 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15609 FindCXXThisExpr Finder(*this); 15610 15611 // If the return type came after the cv-qualifier-seq, check it now. 15612 if (Proto->hasTrailingReturn() && 15613 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 15614 return true; 15615 15616 // Check the exception specification. 15617 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 15618 return true; 15619 15620 return checkThisInStaticMemberFunctionAttributes(Method); 15621 } 15622 15623 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 15624 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15625 if (!TSInfo) 15626 return false; 15627 15628 TypeLoc TL = TSInfo->getTypeLoc(); 15629 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15630 if (!ProtoTL) 15631 return false; 15632 15633 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15634 FindCXXThisExpr Finder(*this); 15635 15636 switch (Proto->getExceptionSpecType()) { 15637 case EST_Unparsed: 15638 case EST_Uninstantiated: 15639 case EST_Unevaluated: 15640 case EST_BasicNoexcept: 15641 case EST_NoThrow: 15642 case EST_DynamicNone: 15643 case EST_MSAny: 15644 case EST_None: 15645 break; 15646 15647 case EST_DependentNoexcept: 15648 case EST_NoexceptFalse: 15649 case EST_NoexceptTrue: 15650 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 15651 return true; 15652 LLVM_FALLTHROUGH; 15653 15654 case EST_Dynamic: 15655 for (const auto &E : Proto->exceptions()) { 15656 if (!Finder.TraverseType(E)) 15657 return true; 15658 } 15659 break; 15660 } 15661 15662 return false; 15663 } 15664 15665 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 15666 FindCXXThisExpr Finder(*this); 15667 15668 // Check attributes. 15669 for (const auto *A : Method->attrs()) { 15670 // FIXME: This should be emitted by tblgen. 15671 Expr *Arg = nullptr; 15672 ArrayRef<Expr *> Args; 15673 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 15674 Arg = G->getArg(); 15675 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 15676 Arg = G->getArg(); 15677 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 15678 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 15679 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 15680 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 15681 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 15682 Arg = ETLF->getSuccessValue(); 15683 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 15684 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 15685 Arg = STLF->getSuccessValue(); 15686 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 15687 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 15688 Arg = LR->getArg(); 15689 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 15690 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 15691 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 15692 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15693 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 15694 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15695 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 15696 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15697 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 15698 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15699 15700 if (Arg && !Finder.TraverseStmt(Arg)) 15701 return true; 15702 15703 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 15704 if (!Finder.TraverseStmt(Args[I])) 15705 return true; 15706 } 15707 } 15708 15709 return false; 15710 } 15711 15712 void Sema::checkExceptionSpecification( 15713 bool IsTopLevel, ExceptionSpecificationType EST, 15714 ArrayRef<ParsedType> DynamicExceptions, 15715 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 15716 SmallVectorImpl<QualType> &Exceptions, 15717 FunctionProtoType::ExceptionSpecInfo &ESI) { 15718 Exceptions.clear(); 15719 ESI.Type = EST; 15720 if (EST == EST_Dynamic) { 15721 Exceptions.reserve(DynamicExceptions.size()); 15722 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 15723 // FIXME: Preserve type source info. 15724 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 15725 15726 if (IsTopLevel) { 15727 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 15728 collectUnexpandedParameterPacks(ET, Unexpanded); 15729 if (!Unexpanded.empty()) { 15730 DiagnoseUnexpandedParameterPacks( 15731 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 15732 Unexpanded); 15733 continue; 15734 } 15735 } 15736 15737 // Check that the type is valid for an exception spec, and 15738 // drop it if not. 15739 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 15740 Exceptions.push_back(ET); 15741 } 15742 ESI.Exceptions = Exceptions; 15743 return; 15744 } 15745 15746 if (isComputedNoexcept(EST)) { 15747 assert((NoexceptExpr->isTypeDependent() || 15748 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 15749 Context.BoolTy) && 15750 "Parser should have made sure that the expression is boolean"); 15751 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 15752 ESI.Type = EST_BasicNoexcept; 15753 return; 15754 } 15755 15756 ESI.NoexceptExpr = NoexceptExpr; 15757 return; 15758 } 15759 } 15760 15761 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 15762 ExceptionSpecificationType EST, 15763 SourceRange SpecificationRange, 15764 ArrayRef<ParsedType> DynamicExceptions, 15765 ArrayRef<SourceRange> DynamicExceptionRanges, 15766 Expr *NoexceptExpr) { 15767 if (!MethodD) 15768 return; 15769 15770 // Dig out the method we're referring to. 15771 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 15772 MethodD = FunTmpl->getTemplatedDecl(); 15773 15774 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 15775 if (!Method) 15776 return; 15777 15778 // Check the exception specification. 15779 llvm::SmallVector<QualType, 4> Exceptions; 15780 FunctionProtoType::ExceptionSpecInfo ESI; 15781 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 15782 DynamicExceptionRanges, NoexceptExpr, Exceptions, 15783 ESI); 15784 15785 // Update the exception specification on the function type. 15786 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 15787 15788 if (Method->isStatic()) 15789 checkThisInStaticMemberFunctionExceptionSpec(Method); 15790 15791 if (Method->isVirtual()) { 15792 // Check overrides, which we previously had to delay. 15793 for (const CXXMethodDecl *O : Method->overridden_methods()) 15794 CheckOverridingFunctionExceptionSpec(Method, O); 15795 } 15796 } 15797 15798 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 15799 /// 15800 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 15801 SourceLocation DeclStart, Declarator &D, 15802 Expr *BitWidth, 15803 InClassInitStyle InitStyle, 15804 AccessSpecifier AS, 15805 const ParsedAttr &MSPropertyAttr) { 15806 IdentifierInfo *II = D.getIdentifier(); 15807 if (!II) { 15808 Diag(DeclStart, diag::err_anonymous_property); 15809 return nullptr; 15810 } 15811 SourceLocation Loc = D.getIdentifierLoc(); 15812 15813 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15814 QualType T = TInfo->getType(); 15815 if (getLangOpts().CPlusPlus) { 15816 CheckExtraCXXDefaultArguments(D); 15817 15818 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15819 UPPC_DataMemberType)) { 15820 D.setInvalidType(); 15821 T = Context.IntTy; 15822 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15823 } 15824 } 15825 15826 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15827 15828 if (D.getDeclSpec().isInlineSpecified()) 15829 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15830 << getLangOpts().CPlusPlus17; 15831 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15832 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15833 diag::err_invalid_thread) 15834 << DeclSpec::getSpecifierName(TSCS); 15835 15836 // Check to see if this name was declared as a member previously 15837 NamedDecl *PrevDecl = nullptr; 15838 LookupResult Previous(*this, II, Loc, LookupMemberName, 15839 ForVisibleRedeclaration); 15840 LookupName(Previous, S); 15841 switch (Previous.getResultKind()) { 15842 case LookupResult::Found: 15843 case LookupResult::FoundUnresolvedValue: 15844 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15845 break; 15846 15847 case LookupResult::FoundOverloaded: 15848 PrevDecl = Previous.getRepresentativeDecl(); 15849 break; 15850 15851 case LookupResult::NotFound: 15852 case LookupResult::NotFoundInCurrentInstantiation: 15853 case LookupResult::Ambiguous: 15854 break; 15855 } 15856 15857 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15858 // Maybe we will complain about the shadowed template parameter. 15859 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15860 // Just pretend that we didn't see the previous declaration. 15861 PrevDecl = nullptr; 15862 } 15863 15864 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15865 PrevDecl = nullptr; 15866 15867 SourceLocation TSSL = D.getBeginLoc(); 15868 MSPropertyDecl *NewPD = 15869 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 15870 MSPropertyAttr.getPropertyDataGetter(), 15871 MSPropertyAttr.getPropertyDataSetter()); 15872 ProcessDeclAttributes(TUScope, NewPD, D); 15873 NewPD->setAccess(AS); 15874 15875 if (NewPD->isInvalidDecl()) 15876 Record->setInvalidDecl(); 15877 15878 if (D.getDeclSpec().isModulePrivateSpecified()) 15879 NewPD->setModulePrivate(); 15880 15881 if (NewPD->isInvalidDecl() && PrevDecl) { 15882 // Don't introduce NewFD into scope; there's already something 15883 // with the same name in the same scope. 15884 } else if (II) { 15885 PushOnScopeChains(NewPD, S); 15886 } else 15887 Record->addDecl(NewPD); 15888 15889 return NewPD; 15890 } 15891