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/ScopeExit.h" 42 #include "llvm/ADT/SmallString.h" 43 #include "llvm/ADT/STLExtras.h" 44 #include "llvm/ADT/StringExtras.h" 45 #include <map> 46 #include <set> 47 48 using namespace clang; 49 50 //===----------------------------------------------------------------------===// 51 // CheckDefaultArgumentVisitor 52 //===----------------------------------------------------------------------===// 53 54 namespace { 55 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 56 /// the default argument of a parameter to determine whether it 57 /// contains any ill-formed subexpressions. For example, this will 58 /// diagnose the use of local variables or parameters within the 59 /// default argument expression. 60 class CheckDefaultArgumentVisitor 61 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> { 62 Sema &S; 63 const Expr *DefaultArg; 64 65 public: 66 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg) 67 : S(S), DefaultArg(DefaultArg) {} 68 69 bool VisitExpr(const Expr *Node); 70 bool VisitDeclRefExpr(const DeclRefExpr *DRE); 71 bool VisitCXXThisExpr(const CXXThisExpr *ThisE); 72 bool VisitLambdaExpr(const LambdaExpr *Lambda); 73 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE); 74 }; 75 76 /// VisitExpr - Visit all of the children of this expression. 77 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) { 78 bool IsInvalid = false; 79 for (const Stmt *SubStmt : Node->children()) 80 IsInvalid |= Visit(SubStmt); 81 return IsInvalid; 82 } 83 84 /// VisitDeclRefExpr - Visit a reference to a declaration, to 85 /// determine whether this declaration can be used in the default 86 /// argument expression. 87 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) { 88 const NamedDecl *Decl = DRE->getDecl(); 89 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) { 90 // C++ [dcl.fct.default]p9: 91 // [...] parameters of a function shall not be used in default 92 // argument expressions, even if they are not evaluated. [...] 93 // 94 // C++17 [dcl.fct.default]p9 (by CWG 2082): 95 // [...] A parameter shall not appear as a potentially-evaluated 96 // expression in a default argument. [...] 97 // 98 if (DRE->isNonOdrUse() != NOUR_Unevaluated) 99 return S.Diag(DRE->getBeginLoc(), 100 diag::err_param_default_argument_references_param) 101 << Param->getDeclName() << DefaultArg->getSourceRange(); 102 } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) { 103 // C++ [dcl.fct.default]p7: 104 // Local variables shall not be used in default argument 105 // expressions. 106 // 107 // C++17 [dcl.fct.default]p7 (by CWG 2082): 108 // A local variable shall not appear as a potentially-evaluated 109 // expression in a default argument. 110 // 111 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346): 112 // Note: A local variable cannot be odr-used (6.3) in a default argument. 113 // 114 if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse()) 115 return S.Diag(DRE->getBeginLoc(), 116 diag::err_param_default_argument_references_local) 117 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 118 } 119 120 return false; 121 } 122 123 /// VisitCXXThisExpr - Visit a C++ "this" expression. 124 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) { 125 // C++ [dcl.fct.default]p8: 126 // The keyword this shall not be used in a default argument of a 127 // member function. 128 return S.Diag(ThisE->getBeginLoc(), 129 diag::err_param_default_argument_references_this) 130 << ThisE->getSourceRange(); 131 } 132 133 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr( 134 const PseudoObjectExpr *POE) { 135 bool Invalid = false; 136 for (const Expr *E : POE->semantics()) { 137 // Look through bindings. 138 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) { 139 E = OVE->getSourceExpr(); 140 assert(E && "pseudo-object binding without source expression?"); 141 } 142 143 Invalid |= Visit(E); 144 } 145 return Invalid; 146 } 147 148 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) { 149 // C++11 [expr.lambda.prim]p13: 150 // A lambda-expression appearing in a default argument shall not 151 // implicitly or explicitly capture any entity. 152 if (Lambda->capture_begin() == Lambda->capture_end()) 153 return false; 154 155 return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); 156 } 157 } // namespace 158 159 void 160 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 161 const CXXMethodDecl *Method) { 162 // If we have an MSAny spec already, don't bother. 163 if (!Method || ComputedEST == EST_MSAny) 164 return; 165 166 const FunctionProtoType *Proto 167 = Method->getType()->getAs<FunctionProtoType>(); 168 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 169 if (!Proto) 170 return; 171 172 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 173 174 // If we have a throw-all spec at this point, ignore the function. 175 if (ComputedEST == EST_None) 176 return; 177 178 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 179 EST = EST_BasicNoexcept; 180 181 switch (EST) { 182 case EST_Unparsed: 183 case EST_Uninstantiated: 184 case EST_Unevaluated: 185 llvm_unreachable("should not see unresolved exception specs here"); 186 187 // If this function can throw any exceptions, make a note of that. 188 case EST_MSAny: 189 case EST_None: 190 // FIXME: Whichever we see last of MSAny and None determines our result. 191 // We should make a consistent, order-independent choice here. 192 ClearExceptions(); 193 ComputedEST = EST; 194 return; 195 case EST_NoexceptFalse: 196 ClearExceptions(); 197 ComputedEST = EST_None; 198 return; 199 // FIXME: If the call to this decl is using any of its default arguments, we 200 // need to search them for potentially-throwing calls. 201 // If this function has a basic noexcept, it doesn't affect the outcome. 202 case EST_BasicNoexcept: 203 case EST_NoexceptTrue: 204 case EST_NoThrow: 205 return; 206 // If we're still at noexcept(true) and there's a throw() callee, 207 // change to that specification. 208 case EST_DynamicNone: 209 if (ComputedEST == EST_BasicNoexcept) 210 ComputedEST = EST_DynamicNone; 211 return; 212 case EST_DependentNoexcept: 213 llvm_unreachable( 214 "should not generate implicit declarations for dependent cases"); 215 case EST_Dynamic: 216 break; 217 } 218 assert(EST == EST_Dynamic && "EST case not considered earlier."); 219 assert(ComputedEST != EST_None && 220 "Shouldn't collect exceptions when throw-all is guaranteed."); 221 ComputedEST = EST_Dynamic; 222 // Record the exceptions in this function's exception specification. 223 for (const auto &E : Proto->exceptions()) 224 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 225 Exceptions.push_back(E); 226 } 227 228 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) { 229 if (!S || ComputedEST == EST_MSAny) 230 return; 231 232 // FIXME: 233 // 234 // C++0x [except.spec]p14: 235 // [An] implicit exception-specification specifies the type-id T if and 236 // only if T is allowed by the exception-specification of a function directly 237 // invoked by f's implicit definition; f shall allow all exceptions if any 238 // function it directly invokes allows all exceptions, and f shall allow no 239 // exceptions if every function it directly invokes allows no exceptions. 240 // 241 // Note in particular that if an implicit exception-specification is generated 242 // for a function containing a throw-expression, that specification can still 243 // be noexcept(true). 244 // 245 // Note also that 'directly invoked' is not defined in the standard, and there 246 // is no indication that we should only consider potentially-evaluated calls. 247 // 248 // Ultimately we should implement the intent of the standard: the exception 249 // specification should be the set of exceptions which can be thrown by the 250 // implicit definition. For now, we assume that any non-nothrow expression can 251 // throw any exception. 252 253 if (Self->canThrow(S)) 254 ComputedEST = EST_None; 255 } 256 257 ExprResult Sema::ConvertParamDefaultArgument(const ParmVarDecl *Param, 258 Expr *Arg, 259 SourceLocation EqualLoc) { 260 if (RequireCompleteType(Param->getLocation(), Param->getType(), 261 diag::err_typecheck_decl_incomplete_type)) 262 return true; 263 264 // C++ [dcl.fct.default]p5 265 // A default argument expression is implicitly converted (clause 266 // 4) to the parameter type. The default argument expression has 267 // the same semantic constraints as the initializer expression in 268 // a declaration of a variable of the parameter type, using the 269 // copy-initialization semantics (8.5). 270 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 271 Param); 272 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 273 EqualLoc); 274 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 275 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 276 if (Result.isInvalid()) 277 return true; 278 Arg = Result.getAs<Expr>(); 279 280 CheckCompletedExpr(Arg, EqualLoc); 281 Arg = MaybeCreateExprWithCleanups(Arg); 282 283 return Arg; 284 } 285 286 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 287 SourceLocation EqualLoc) { 288 // Add the default argument to the parameter 289 Param->setDefaultArg(Arg); 290 291 // We have already instantiated this parameter; provide each of the 292 // instantiations with the uninstantiated default argument. 293 UnparsedDefaultArgInstantiationsMap::iterator InstPos 294 = UnparsedDefaultArgInstantiations.find(Param); 295 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 296 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 297 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 298 299 // We're done tracking this parameter's instantiations. 300 UnparsedDefaultArgInstantiations.erase(InstPos); 301 } 302 } 303 304 /// ActOnParamDefaultArgument - Check whether the default argument 305 /// provided for a function parameter is well-formed. If so, attach it 306 /// to the parameter declaration. 307 void 308 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 309 Expr *DefaultArg) { 310 if (!param || !DefaultArg) 311 return; 312 313 ParmVarDecl *Param = cast<ParmVarDecl>(param); 314 UnparsedDefaultArgLocs.erase(Param); 315 316 auto Fail = [&] { 317 Param->setInvalidDecl(); 318 Param->setDefaultArg(new (Context) OpaqueValueExpr( 319 EqualLoc, Param->getType().getNonReferenceType(), VK_RValue)); 320 }; 321 322 // Default arguments are only permitted in C++ 323 if (!getLangOpts().CPlusPlus) { 324 Diag(EqualLoc, diag::err_param_default_argument) 325 << DefaultArg->getSourceRange(); 326 return Fail(); 327 } 328 329 // Check for unexpanded parameter packs. 330 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 331 return Fail(); 332 } 333 334 // C++11 [dcl.fct.default]p3 335 // A default argument expression [...] shall not be specified for a 336 // parameter pack. 337 if (Param->isParameterPack()) { 338 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 339 << DefaultArg->getSourceRange(); 340 // Recover by discarding the default argument. 341 Param->setDefaultArg(nullptr); 342 return; 343 } 344 345 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc); 346 if (Result.isInvalid()) 347 return Fail(); 348 349 DefaultArg = Result.getAs<Expr>(); 350 351 // Check that the default argument is well-formed 352 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg); 353 if (DefaultArgChecker.Visit(DefaultArg)) 354 return Fail(); 355 356 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 357 } 358 359 /// ActOnParamUnparsedDefaultArgument - We've seen a default 360 /// argument for a function parameter, but we can't parse it yet 361 /// because we're inside a class definition. Note that this default 362 /// argument will be parsed later. 363 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 364 SourceLocation EqualLoc, 365 SourceLocation ArgLoc) { 366 if (!param) 367 return; 368 369 ParmVarDecl *Param = cast<ParmVarDecl>(param); 370 Param->setUnparsedDefaultArg(); 371 UnparsedDefaultArgLocs[Param] = ArgLoc; 372 } 373 374 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 375 /// the default argument for the parameter param failed. 376 void Sema::ActOnParamDefaultArgumentError(Decl *param, 377 SourceLocation EqualLoc) { 378 if (!param) 379 return; 380 381 ParmVarDecl *Param = cast<ParmVarDecl>(param); 382 Param->setInvalidDecl(); 383 UnparsedDefaultArgLocs.erase(Param); 384 Param->setDefaultArg(new(Context) 385 OpaqueValueExpr(EqualLoc, 386 Param->getType().getNonReferenceType(), 387 VK_RValue)); 388 } 389 390 /// CheckExtraCXXDefaultArguments - Check for any extra default 391 /// arguments in the declarator, which is not a function declaration 392 /// or definition and therefore is not permitted to have default 393 /// arguments. This routine should be invoked for every declarator 394 /// that is not a function declaration or definition. 395 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 396 // C++ [dcl.fct.default]p3 397 // A default argument expression shall be specified only in the 398 // parameter-declaration-clause of a function declaration or in a 399 // template-parameter (14.1). It shall not be specified for a 400 // parameter pack. If it is specified in a 401 // parameter-declaration-clause, it shall not occur within a 402 // declarator or abstract-declarator of a parameter-declaration. 403 bool MightBeFunction = D.isFunctionDeclarationContext(); 404 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 405 DeclaratorChunk &chunk = D.getTypeObject(i); 406 if (chunk.Kind == DeclaratorChunk::Function) { 407 if (MightBeFunction) { 408 // This is a function declaration. It can have default arguments, but 409 // keep looking in case its return type is a function type with default 410 // arguments. 411 MightBeFunction = false; 412 continue; 413 } 414 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 415 ++argIdx) { 416 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 417 if (Param->hasUnparsedDefaultArg()) { 418 std::unique_ptr<CachedTokens> Toks = 419 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 420 SourceRange SR; 421 if (Toks->size() > 1) 422 SR = SourceRange((*Toks)[1].getLocation(), 423 Toks->back().getLocation()); 424 else 425 SR = UnparsedDefaultArgLocs[Param]; 426 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 427 << SR; 428 } else if (Param->getDefaultArg()) { 429 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 430 << Param->getDefaultArg()->getSourceRange(); 431 Param->setDefaultArg(nullptr); 432 } 433 } 434 } else if (chunk.Kind != DeclaratorChunk::Paren) { 435 MightBeFunction = false; 436 } 437 } 438 } 439 440 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 441 return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) { 442 return P->hasDefaultArg() && !P->hasInheritedDefaultArg(); 443 }); 444 } 445 446 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 447 /// function, once we already know that they have the same 448 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 449 /// error, false otherwise. 450 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 451 Scope *S) { 452 bool Invalid = false; 453 454 // The declaration context corresponding to the scope is the semantic 455 // parent, unless this is a local function declaration, in which case 456 // it is that surrounding function. 457 DeclContext *ScopeDC = New->isLocalExternDecl() 458 ? New->getLexicalDeclContext() 459 : New->getDeclContext(); 460 461 // Find the previous declaration for the purpose of default arguments. 462 FunctionDecl *PrevForDefaultArgs = Old; 463 for (/**/; PrevForDefaultArgs; 464 // Don't bother looking back past the latest decl if this is a local 465 // extern declaration; nothing else could work. 466 PrevForDefaultArgs = New->isLocalExternDecl() 467 ? nullptr 468 : PrevForDefaultArgs->getPreviousDecl()) { 469 // Ignore hidden declarations. 470 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 471 continue; 472 473 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 474 !New->isCXXClassMember()) { 475 // Ignore default arguments of old decl if they are not in 476 // the same scope and this is not an out-of-line definition of 477 // a member function. 478 continue; 479 } 480 481 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 482 // If only one of these is a local function declaration, then they are 483 // declared in different scopes, even though isDeclInScope may think 484 // they're in the same scope. (If both are local, the scope check is 485 // sufficient, and if neither is local, then they are in the same scope.) 486 continue; 487 } 488 489 // We found the right previous declaration. 490 break; 491 } 492 493 // C++ [dcl.fct.default]p4: 494 // For non-template functions, default arguments can be added in 495 // later declarations of a function in the same 496 // scope. Declarations in different scopes have completely 497 // distinct sets of default arguments. That is, declarations in 498 // inner scopes do not acquire default arguments from 499 // declarations in outer scopes, and vice versa. In a given 500 // function declaration, all parameters subsequent to a 501 // parameter with a default argument shall have default 502 // arguments supplied in this or previous declarations. A 503 // default argument shall not be redefined by a later 504 // declaration (not even to the same value). 505 // 506 // C++ [dcl.fct.default]p6: 507 // Except for member functions of class templates, the default arguments 508 // in a member function definition that appears outside of the class 509 // definition are added to the set of default arguments provided by the 510 // member function declaration in the class definition. 511 for (unsigned p = 0, NumParams = PrevForDefaultArgs 512 ? PrevForDefaultArgs->getNumParams() 513 : 0; 514 p < NumParams; ++p) { 515 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 516 ParmVarDecl *NewParam = New->getParamDecl(p); 517 518 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 519 bool NewParamHasDfl = NewParam->hasDefaultArg(); 520 521 if (OldParamHasDfl && NewParamHasDfl) { 522 unsigned DiagDefaultParamID = 523 diag::err_param_default_argument_redefinition; 524 525 // MSVC accepts that default parameters be redefined for member functions 526 // of template class. The new default parameter's value is ignored. 527 Invalid = true; 528 if (getLangOpts().MicrosoftExt) { 529 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 530 if (MD && MD->getParent()->getDescribedClassTemplate()) { 531 // Merge the old default argument into the new parameter. 532 NewParam->setHasInheritedDefaultArg(); 533 if (OldParam->hasUninstantiatedDefaultArg()) 534 NewParam->setUninstantiatedDefaultArg( 535 OldParam->getUninstantiatedDefaultArg()); 536 else 537 NewParam->setDefaultArg(OldParam->getInit()); 538 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 539 Invalid = false; 540 } 541 } 542 543 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 544 // hint here. Alternatively, we could walk the type-source information 545 // for NewParam to find the last source location in the type... but it 546 // isn't worth the effort right now. This is the kind of test case that 547 // is hard to get right: 548 // int f(int); 549 // void g(int (*fp)(int) = f); 550 // void g(int (*fp)(int) = &f); 551 Diag(NewParam->getLocation(), DiagDefaultParamID) 552 << NewParam->getDefaultArgRange(); 553 554 // Look for the function declaration where the default argument was 555 // actually written, which may be a declaration prior to Old. 556 for (auto Older = PrevForDefaultArgs; 557 OldParam->hasInheritedDefaultArg(); /**/) { 558 Older = Older->getPreviousDecl(); 559 OldParam = Older->getParamDecl(p); 560 } 561 562 Diag(OldParam->getLocation(), diag::note_previous_definition) 563 << OldParam->getDefaultArgRange(); 564 } else if (OldParamHasDfl) { 565 // Merge the old default argument into the new parameter unless the new 566 // function is a friend declaration in a template class. In the latter 567 // case the default arguments will be inherited when the friend 568 // declaration will be instantiated. 569 if (New->getFriendObjectKind() == Decl::FOK_None || 570 !New->getLexicalDeclContext()->isDependentContext()) { 571 // It's important to use getInit() here; getDefaultArg() 572 // strips off any top-level ExprWithCleanups. 573 NewParam->setHasInheritedDefaultArg(); 574 if (OldParam->hasUnparsedDefaultArg()) 575 NewParam->setUnparsedDefaultArg(); 576 else if (OldParam->hasUninstantiatedDefaultArg()) 577 NewParam->setUninstantiatedDefaultArg( 578 OldParam->getUninstantiatedDefaultArg()); 579 else 580 NewParam->setDefaultArg(OldParam->getInit()); 581 } 582 } else if (NewParamHasDfl) { 583 if (New->getDescribedFunctionTemplate()) { 584 // Paragraph 4, quoted above, only applies to non-template functions. 585 Diag(NewParam->getLocation(), 586 diag::err_param_default_argument_template_redecl) 587 << NewParam->getDefaultArgRange(); 588 Diag(PrevForDefaultArgs->getLocation(), 589 diag::note_template_prev_declaration) 590 << false; 591 } else if (New->getTemplateSpecializationKind() 592 != TSK_ImplicitInstantiation && 593 New->getTemplateSpecializationKind() != TSK_Undeclared) { 594 // C++ [temp.expr.spec]p21: 595 // Default function arguments shall not be specified in a declaration 596 // or a definition for one of the following explicit specializations: 597 // - the explicit specialization of a function template; 598 // - the explicit specialization of a member function template; 599 // - the explicit specialization of a member function of a class 600 // template where the class template specialization to which the 601 // member function specialization belongs is implicitly 602 // instantiated. 603 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 604 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 605 << New->getDeclName() 606 << NewParam->getDefaultArgRange(); 607 } else if (New->getDeclContext()->isDependentContext()) { 608 // C++ [dcl.fct.default]p6 (DR217): 609 // Default arguments for a member function of a class template shall 610 // be specified on the initial declaration of the member function 611 // within the class template. 612 // 613 // Reading the tea leaves a bit in DR217 and its reference to DR205 614 // leads me to the conclusion that one cannot add default function 615 // arguments for an out-of-line definition of a member function of a 616 // dependent type. 617 int WhichKind = 2; 618 if (CXXRecordDecl *Record 619 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 620 if (Record->getDescribedClassTemplate()) 621 WhichKind = 0; 622 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 623 WhichKind = 1; 624 else 625 WhichKind = 2; 626 } 627 628 Diag(NewParam->getLocation(), 629 diag::err_param_default_argument_member_template_redecl) 630 << WhichKind 631 << NewParam->getDefaultArgRange(); 632 } 633 } 634 } 635 636 // DR1344: If a default argument is added outside a class definition and that 637 // default argument makes the function a special member function, the program 638 // is ill-formed. This can only happen for constructors. 639 if (isa<CXXConstructorDecl>(New) && 640 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 641 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 642 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 643 if (NewSM != OldSM) { 644 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 645 assert(NewParam->hasDefaultArg()); 646 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 647 << NewParam->getDefaultArgRange() << NewSM; 648 Diag(Old->getLocation(), diag::note_previous_declaration); 649 } 650 } 651 652 const FunctionDecl *Def; 653 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 654 // template has a constexpr specifier then all its declarations shall 655 // contain the constexpr specifier. 656 if (New->getConstexprKind() != Old->getConstexprKind()) { 657 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 658 << New << static_cast<int>(New->getConstexprKind()) 659 << static_cast<int>(Old->getConstexprKind()); 660 Diag(Old->getLocation(), diag::note_previous_declaration); 661 Invalid = true; 662 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 663 Old->isDefined(Def) && 664 // If a friend function is inlined but does not have 'inline' 665 // specifier, it is a definition. Do not report attribute conflict 666 // in this case, redefinition will be diagnosed later. 667 (New->isInlineSpecified() || 668 New->getFriendObjectKind() == Decl::FOK_None)) { 669 // C++11 [dcl.fcn.spec]p4: 670 // If the definition of a function appears in a translation unit before its 671 // first declaration as inline, the program is ill-formed. 672 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 673 Diag(Def->getLocation(), diag::note_previous_definition); 674 Invalid = true; 675 } 676 677 // C++17 [temp.deduct.guide]p3: 678 // Two deduction guide declarations in the same translation unit 679 // for the same class template shall not have equivalent 680 // parameter-declaration-clauses. 681 if (isa<CXXDeductionGuideDecl>(New) && 682 !New->isFunctionTemplateSpecialization() && isVisible(Old)) { 683 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 684 Diag(Old->getLocation(), diag::note_previous_declaration); 685 } 686 687 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 688 // argument expression, that declaration shall be a definition and shall be 689 // the only declaration of the function or function template in the 690 // translation unit. 691 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 692 functionDeclHasDefaultArgument(Old)) { 693 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 694 Diag(Old->getLocation(), diag::note_previous_declaration); 695 Invalid = true; 696 } 697 698 // C++11 [temp.friend]p4 (DR329): 699 // When a function is defined in a friend function declaration in a class 700 // template, the function is instantiated when the function is odr-used. 701 // The same restrictions on multiple declarations and definitions that 702 // apply to non-template function declarations and definitions also apply 703 // to these implicit definitions. 704 const FunctionDecl *OldDefinition = nullptr; 705 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() && 706 Old->isDefined(OldDefinition, true)) 707 CheckForFunctionRedefinition(New, OldDefinition); 708 709 return Invalid; 710 } 711 712 NamedDecl * 713 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 714 MultiTemplateParamsArg TemplateParamLists) { 715 assert(D.isDecompositionDeclarator()); 716 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 717 718 // The syntax only allows a decomposition declarator as a simple-declaration, 719 // a for-range-declaration, or a condition in Clang, but we parse it in more 720 // cases than that. 721 if (!D.mayHaveDecompositionDeclarator()) { 722 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 723 << Decomp.getSourceRange(); 724 return nullptr; 725 } 726 727 if (!TemplateParamLists.empty()) { 728 // FIXME: There's no rule against this, but there are also no rules that 729 // would actually make it usable, so we reject it for now. 730 Diag(TemplateParamLists.front()->getTemplateLoc(), 731 diag::err_decomp_decl_template); 732 return nullptr; 733 } 734 735 Diag(Decomp.getLSquareLoc(), 736 !getLangOpts().CPlusPlus17 737 ? diag::ext_decomp_decl 738 : D.getContext() == DeclaratorContext::Condition 739 ? diag::ext_decomp_decl_cond 740 : diag::warn_cxx14_compat_decomp_decl) 741 << Decomp.getSourceRange(); 742 743 // The semantic context is always just the current context. 744 DeclContext *const DC = CurContext; 745 746 // C++17 [dcl.dcl]/8: 747 // The decl-specifier-seq shall contain only the type-specifier auto 748 // and cv-qualifiers. 749 // C++2a [dcl.dcl]/8: 750 // If decl-specifier-seq contains any decl-specifier other than static, 751 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 752 auto &DS = D.getDeclSpec(); 753 { 754 SmallVector<StringRef, 8> BadSpecifiers; 755 SmallVector<SourceLocation, 8> BadSpecifierLocs; 756 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 757 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 758 if (auto SCS = DS.getStorageClassSpec()) { 759 if (SCS == DeclSpec::SCS_static) { 760 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 761 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 762 } else { 763 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 764 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 765 } 766 } 767 if (auto TSCS = DS.getThreadStorageClassSpec()) { 768 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 769 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 770 } 771 if (DS.hasConstexprSpecifier()) { 772 BadSpecifiers.push_back( 773 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 774 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 775 } 776 if (DS.isInlineSpecified()) { 777 BadSpecifiers.push_back("inline"); 778 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 779 } 780 if (!BadSpecifiers.empty()) { 781 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 782 Err << (int)BadSpecifiers.size() 783 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 784 // Don't add FixItHints to remove the specifiers; we do still respect 785 // them when building the underlying variable. 786 for (auto Loc : BadSpecifierLocs) 787 Err << SourceRange(Loc, Loc); 788 } else if (!CPlusPlus20Specifiers.empty()) { 789 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 790 getLangOpts().CPlusPlus20 791 ? diag::warn_cxx17_compat_decomp_decl_spec 792 : diag::ext_decomp_decl_spec); 793 Warn << (int)CPlusPlus20Specifiers.size() 794 << llvm::join(CPlusPlus20Specifiers.begin(), 795 CPlusPlus20Specifiers.end(), " "); 796 for (auto Loc : CPlusPlus20SpecifierLocs) 797 Warn << SourceRange(Loc, Loc); 798 } 799 // We can't recover from it being declared as a typedef. 800 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 801 return nullptr; 802 } 803 804 // C++2a [dcl.struct.bind]p1: 805 // A cv that includes volatile is deprecated 806 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && 807 getLangOpts().CPlusPlus20) 808 Diag(DS.getVolatileSpecLoc(), 809 diag::warn_deprecated_volatile_structured_binding); 810 811 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 812 QualType R = TInfo->getType(); 813 814 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 815 UPPC_DeclarationType)) 816 D.setInvalidType(); 817 818 // The syntax only allows a single ref-qualifier prior to the decomposition 819 // declarator. No other declarator chunks are permitted. Also check the type 820 // specifier here. 821 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 822 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 823 (D.getNumTypeObjects() == 1 && 824 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 825 Diag(Decomp.getLSquareLoc(), 826 (D.hasGroupingParens() || 827 (D.getNumTypeObjects() && 828 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 829 ? diag::err_decomp_decl_parens 830 : diag::err_decomp_decl_type) 831 << R; 832 833 // In most cases, there's no actual problem with an explicitly-specified 834 // type, but a function type won't work here, and ActOnVariableDeclarator 835 // shouldn't be called for such a type. 836 if (R->isFunctionType()) 837 D.setInvalidType(); 838 } 839 840 // Build the BindingDecls. 841 SmallVector<BindingDecl*, 8> Bindings; 842 843 // Build the BindingDecls. 844 for (auto &B : D.getDecompositionDeclarator().bindings()) { 845 // Check for name conflicts. 846 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 847 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 848 ForVisibleRedeclaration); 849 LookupName(Previous, S, 850 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 851 852 // It's not permitted to shadow a template parameter name. 853 if (Previous.isSingleResult() && 854 Previous.getFoundDecl()->isTemplateParameter()) { 855 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 856 Previous.getFoundDecl()); 857 Previous.clear(); 858 } 859 860 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 861 862 // Find the shadowed declaration before filtering for scope. 863 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 864 ? getShadowedDeclaration(BD, Previous) 865 : nullptr; 866 867 bool ConsiderLinkage = DC->isFunctionOrMethod() && 868 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 869 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 870 /*AllowInlineNamespace*/false); 871 872 if (!Previous.empty()) { 873 auto *Old = Previous.getRepresentativeDecl(); 874 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 875 Diag(Old->getLocation(), diag::note_previous_definition); 876 } else if (ShadowedDecl && !D.isRedeclaration()) { 877 CheckShadow(BD, ShadowedDecl, Previous); 878 } 879 PushOnScopeChains(BD, S, true); 880 Bindings.push_back(BD); 881 ParsingInitForAutoVars.insert(BD); 882 } 883 884 // There are no prior lookup results for the variable itself, because it 885 // is unnamed. 886 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 887 Decomp.getLSquareLoc()); 888 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 889 ForVisibleRedeclaration); 890 891 // Build the variable that holds the non-decomposed object. 892 bool AddToScope = true; 893 NamedDecl *New = 894 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 895 MultiTemplateParamsArg(), AddToScope, Bindings); 896 if (AddToScope) { 897 S->AddDecl(New); 898 CurContext->addHiddenDecl(New); 899 } 900 901 if (isInOpenMPDeclareTargetContext()) 902 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 903 904 return New; 905 } 906 907 static bool checkSimpleDecomposition( 908 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 909 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 910 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 911 if ((int64_t)Bindings.size() != NumElems) { 912 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 913 << DecompType << (unsigned)Bindings.size() 914 << (unsigned)NumElems.getLimitedValue(UINT_MAX) << NumElems.toString(10) 915 << (NumElems < Bindings.size()); 916 return true; 917 } 918 919 unsigned I = 0; 920 for (auto *B : Bindings) { 921 SourceLocation Loc = B->getLocation(); 922 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 923 if (E.isInvalid()) 924 return true; 925 E = GetInit(Loc, E.get(), I++); 926 if (E.isInvalid()) 927 return true; 928 B->setBinding(ElemType, E.get()); 929 } 930 931 return false; 932 } 933 934 static bool checkArrayLikeDecomposition(Sema &S, 935 ArrayRef<BindingDecl *> Bindings, 936 ValueDecl *Src, QualType DecompType, 937 const llvm::APSInt &NumElems, 938 QualType ElemType) { 939 return checkSimpleDecomposition( 940 S, Bindings, Src, DecompType, NumElems, ElemType, 941 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 942 ExprResult E = S.ActOnIntegerConstant(Loc, I); 943 if (E.isInvalid()) 944 return ExprError(); 945 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 946 }); 947 } 948 949 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 950 ValueDecl *Src, QualType DecompType, 951 const ConstantArrayType *CAT) { 952 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 953 llvm::APSInt(CAT->getSize()), 954 CAT->getElementType()); 955 } 956 957 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 958 ValueDecl *Src, QualType DecompType, 959 const VectorType *VT) { 960 return checkArrayLikeDecomposition( 961 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 962 S.Context.getQualifiedType(VT->getElementType(), 963 DecompType.getQualifiers())); 964 } 965 966 static bool checkComplexDecomposition(Sema &S, 967 ArrayRef<BindingDecl *> Bindings, 968 ValueDecl *Src, QualType DecompType, 969 const ComplexType *CT) { 970 return checkSimpleDecomposition( 971 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 972 S.Context.getQualifiedType(CT->getElementType(), 973 DecompType.getQualifiers()), 974 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 975 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 976 }); 977 } 978 979 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 980 TemplateArgumentListInfo &Args) { 981 SmallString<128> SS; 982 llvm::raw_svector_ostream OS(SS); 983 bool First = true; 984 for (auto &Arg : Args.arguments()) { 985 if (!First) 986 OS << ", "; 987 Arg.getArgument().print(PrintingPolicy, OS); 988 First = false; 989 } 990 return std::string(OS.str()); 991 } 992 993 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 994 SourceLocation Loc, StringRef Trait, 995 TemplateArgumentListInfo &Args, 996 unsigned DiagID) { 997 auto DiagnoseMissing = [&] { 998 if (DiagID) 999 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 1000 Args); 1001 return true; 1002 }; 1003 1004 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 1005 NamespaceDecl *Std = S.getStdNamespace(); 1006 if (!Std) 1007 return DiagnoseMissing(); 1008 1009 // Look up the trait itself, within namespace std. We can diagnose various 1010 // problems with this lookup even if we've been asked to not diagnose a 1011 // missing specialization, because this can only fail if the user has been 1012 // declaring their own names in namespace std or we don't support the 1013 // standard library implementation in use. 1014 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 1015 Loc, Sema::LookupOrdinaryName); 1016 if (!S.LookupQualifiedName(Result, Std)) 1017 return DiagnoseMissing(); 1018 if (Result.isAmbiguous()) 1019 return true; 1020 1021 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 1022 if (!TraitTD) { 1023 Result.suppressDiagnostics(); 1024 NamedDecl *Found = *Result.begin(); 1025 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 1026 S.Diag(Found->getLocation(), diag::note_declared_at); 1027 return true; 1028 } 1029 1030 // Build the template-id. 1031 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 1032 if (TraitTy.isNull()) 1033 return true; 1034 if (!S.isCompleteType(Loc, TraitTy)) { 1035 if (DiagID) 1036 S.RequireCompleteType( 1037 Loc, TraitTy, DiagID, 1038 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 1039 return true; 1040 } 1041 1042 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1043 assert(RD && "specialization of class template is not a class?"); 1044 1045 // Look up the member of the trait type. 1046 S.LookupQualifiedName(TraitMemberLookup, RD); 1047 return TraitMemberLookup.isAmbiguous(); 1048 } 1049 1050 static TemplateArgumentLoc 1051 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1052 uint64_t I) { 1053 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1054 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1055 } 1056 1057 static TemplateArgumentLoc 1058 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1059 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1060 } 1061 1062 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1063 1064 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1065 llvm::APSInt &Size) { 1066 EnterExpressionEvaluationContext ContextRAII( 1067 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1068 1069 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1070 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1071 1072 // Form template argument list for tuple_size<T>. 1073 TemplateArgumentListInfo Args(Loc, Loc); 1074 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1075 1076 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1077 // it's not tuple-like. 1078 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1079 R.empty()) 1080 return IsTupleLike::NotTupleLike; 1081 1082 // If we get this far, we've committed to the tuple interpretation, but 1083 // we can still fail if there actually isn't a usable ::value. 1084 1085 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1086 LookupResult &R; 1087 TemplateArgumentListInfo &Args; 1088 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1089 : R(R), Args(Args) {} 1090 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 1091 SourceLocation Loc) override { 1092 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1093 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1094 } 1095 } Diagnoser(R, Args); 1096 1097 ExprResult E = 1098 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1099 if (E.isInvalid()) 1100 return IsTupleLike::Error; 1101 1102 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser); 1103 if (E.isInvalid()) 1104 return IsTupleLike::Error; 1105 1106 return IsTupleLike::TupleLike; 1107 } 1108 1109 /// \return std::tuple_element<I, T>::type. 1110 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1111 unsigned I, QualType T) { 1112 // Form template argument list for tuple_element<I, T>. 1113 TemplateArgumentListInfo Args(Loc, Loc); 1114 Args.addArgument( 1115 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1116 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1117 1118 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1119 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1120 if (lookupStdTypeTraitMember( 1121 S, R, Loc, "tuple_element", Args, 1122 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1123 return QualType(); 1124 1125 auto *TD = R.getAsSingle<TypeDecl>(); 1126 if (!TD) { 1127 R.suppressDiagnostics(); 1128 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1129 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1130 if (!R.empty()) 1131 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1132 return QualType(); 1133 } 1134 1135 return S.Context.getTypeDeclType(TD); 1136 } 1137 1138 namespace { 1139 struct InitializingBinding { 1140 Sema &S; 1141 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) { 1142 Sema::CodeSynthesisContext Ctx; 1143 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding; 1144 Ctx.PointOfInstantiation = BD->getLocation(); 1145 Ctx.Entity = BD; 1146 S.pushCodeSynthesisContext(Ctx); 1147 } 1148 ~InitializingBinding() { 1149 S.popCodeSynthesisContext(); 1150 } 1151 }; 1152 } 1153 1154 static bool checkTupleLikeDecomposition(Sema &S, 1155 ArrayRef<BindingDecl *> Bindings, 1156 VarDecl *Src, QualType DecompType, 1157 const llvm::APSInt &TupleSize) { 1158 if ((int64_t)Bindings.size() != TupleSize) { 1159 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1160 << DecompType << (unsigned)Bindings.size() 1161 << (unsigned)TupleSize.getLimitedValue(UINT_MAX) 1162 << TupleSize.toString(10) << (TupleSize < Bindings.size()); 1163 return true; 1164 } 1165 1166 if (Bindings.empty()) 1167 return false; 1168 1169 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1170 1171 // [dcl.decomp]p3: 1172 // The unqualified-id get is looked up in the scope of E by class member 1173 // access lookup ... 1174 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1175 bool UseMemberGet = false; 1176 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1177 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1178 S.LookupQualifiedName(MemberGet, RD); 1179 if (MemberGet.isAmbiguous()) 1180 return true; 1181 // ... and if that finds at least one declaration that is a function 1182 // template whose first template parameter is a non-type parameter ... 1183 for (NamedDecl *D : MemberGet) { 1184 if (FunctionTemplateDecl *FTD = 1185 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1186 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1187 if (TPL->size() != 0 && 1188 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1189 // ... the initializer is e.get<i>(). 1190 UseMemberGet = true; 1191 break; 1192 } 1193 } 1194 } 1195 } 1196 1197 unsigned I = 0; 1198 for (auto *B : Bindings) { 1199 InitializingBinding InitContext(S, B); 1200 SourceLocation Loc = B->getLocation(); 1201 1202 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1203 if (E.isInvalid()) 1204 return true; 1205 1206 // e is an lvalue if the type of the entity is an lvalue reference and 1207 // an xvalue otherwise 1208 if (!Src->getType()->isLValueReferenceType()) 1209 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1210 E.get(), nullptr, VK_XValue, 1211 FPOptionsOverride()); 1212 1213 TemplateArgumentListInfo Args(Loc, Loc); 1214 Args.addArgument( 1215 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1216 1217 if (UseMemberGet) { 1218 // if [lookup of member get] finds at least one declaration, the 1219 // initializer is e.get<i-1>(). 1220 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1221 CXXScopeSpec(), SourceLocation(), nullptr, 1222 MemberGet, &Args, nullptr); 1223 if (E.isInvalid()) 1224 return true; 1225 1226 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1227 } else { 1228 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1229 // in the associated namespaces. 1230 Expr *Get = UnresolvedLookupExpr::Create( 1231 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1232 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1233 UnresolvedSetIterator(), UnresolvedSetIterator()); 1234 1235 Expr *Arg = E.get(); 1236 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1237 } 1238 if (E.isInvalid()) 1239 return true; 1240 Expr *Init = E.get(); 1241 1242 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1243 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1244 if (T.isNull()) 1245 return true; 1246 1247 // each vi is a variable of type "reference to T" initialized with the 1248 // initializer, where the reference is an lvalue reference if the 1249 // initializer is an lvalue and an rvalue reference otherwise 1250 QualType RefType = 1251 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1252 if (RefType.isNull()) 1253 return true; 1254 auto *RefVD = VarDecl::Create( 1255 S.Context, Src->getDeclContext(), Loc, Loc, 1256 B->getDeclName().getAsIdentifierInfo(), RefType, 1257 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1258 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1259 RefVD->setTSCSpec(Src->getTSCSpec()); 1260 RefVD->setImplicit(); 1261 if (Src->isInlineSpecified()) 1262 RefVD->setInlineSpecified(); 1263 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1264 1265 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1266 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1267 InitializationSequence Seq(S, Entity, Kind, Init); 1268 E = Seq.Perform(S, Entity, Kind, Init); 1269 if (E.isInvalid()) 1270 return true; 1271 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1272 if (E.isInvalid()) 1273 return true; 1274 RefVD->setInit(E.get()); 1275 S.CheckCompleteVariableDeclaration(RefVD); 1276 1277 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1278 DeclarationNameInfo(B->getDeclName(), Loc), 1279 RefVD); 1280 if (E.isInvalid()) 1281 return true; 1282 1283 B->setBinding(T, E.get()); 1284 I++; 1285 } 1286 1287 return false; 1288 } 1289 1290 /// Find the base class to decompose in a built-in decomposition of a class type. 1291 /// This base class search is, unfortunately, not quite like any other that we 1292 /// perform anywhere else in C++. 1293 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1294 const CXXRecordDecl *RD, 1295 CXXCastPath &BasePath) { 1296 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1297 CXXBasePath &Path) { 1298 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1299 }; 1300 1301 const CXXRecordDecl *ClassWithFields = nullptr; 1302 AccessSpecifier AS = AS_public; 1303 if (RD->hasDirectFields()) 1304 // [dcl.decomp]p4: 1305 // Otherwise, all of E's non-static data members shall be public direct 1306 // members of E ... 1307 ClassWithFields = RD; 1308 else { 1309 // ... or of ... 1310 CXXBasePaths Paths; 1311 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1312 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1313 // If no classes have fields, just decompose RD itself. (This will work 1314 // if and only if zero bindings were provided.) 1315 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1316 } 1317 1318 CXXBasePath *BestPath = nullptr; 1319 for (auto &P : Paths) { 1320 if (!BestPath) 1321 BestPath = &P; 1322 else if (!S.Context.hasSameType(P.back().Base->getType(), 1323 BestPath->back().Base->getType())) { 1324 // ... the same ... 1325 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1326 << false << RD << BestPath->back().Base->getType() 1327 << P.back().Base->getType(); 1328 return DeclAccessPair(); 1329 } else if (P.Access < BestPath->Access) { 1330 BestPath = &P; 1331 } 1332 } 1333 1334 // ... unambiguous ... 1335 QualType BaseType = BestPath->back().Base->getType(); 1336 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1337 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1338 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1339 return DeclAccessPair(); 1340 } 1341 1342 // ... [accessible, implied by other rules] base class of E. 1343 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1344 *BestPath, diag::err_decomp_decl_inaccessible_base); 1345 AS = BestPath->Access; 1346 1347 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1348 S.BuildBasePathArray(Paths, BasePath); 1349 } 1350 1351 // The above search did not check whether the selected class itself has base 1352 // classes with fields, so check that now. 1353 CXXBasePaths Paths; 1354 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1355 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1356 << (ClassWithFields == RD) << RD << ClassWithFields 1357 << Paths.front().back().Base->getType(); 1358 return DeclAccessPair(); 1359 } 1360 1361 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1362 } 1363 1364 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1365 ValueDecl *Src, QualType DecompType, 1366 const CXXRecordDecl *OrigRD) { 1367 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1368 diag::err_incomplete_type)) 1369 return true; 1370 1371 CXXCastPath BasePath; 1372 DeclAccessPair BasePair = 1373 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1374 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1375 if (!RD) 1376 return true; 1377 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1378 DecompType.getQualifiers()); 1379 1380 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1381 unsigned NumFields = 1382 std::count_if(RD->field_begin(), RD->field_end(), 1383 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1384 assert(Bindings.size() != NumFields); 1385 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1386 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields 1387 << (NumFields < Bindings.size()); 1388 return true; 1389 }; 1390 1391 // all of E's non-static data members shall be [...] well-formed 1392 // when named as e.name in the context of the structured binding, 1393 // E shall not have an anonymous union member, ... 1394 unsigned I = 0; 1395 for (auto *FD : RD->fields()) { 1396 if (FD->isUnnamedBitfield()) 1397 continue; 1398 1399 // All the non-static data members are required to be nameable, so they 1400 // must all have names. 1401 if (!FD->getDeclName()) { 1402 if (RD->isLambda()) { 1403 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda); 1404 S.Diag(RD->getLocation(), diag::note_lambda_decl); 1405 return true; 1406 } 1407 1408 if (FD->isAnonymousStructOrUnion()) { 1409 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1410 << DecompType << FD->getType()->isUnionType(); 1411 S.Diag(FD->getLocation(), diag::note_declared_at); 1412 return true; 1413 } 1414 1415 // FIXME: Are there any other ways we could have an anonymous member? 1416 } 1417 1418 // We have a real field to bind. 1419 if (I >= Bindings.size()) 1420 return DiagnoseBadNumberOfBindings(); 1421 auto *B = Bindings[I++]; 1422 SourceLocation Loc = B->getLocation(); 1423 1424 // The field must be accessible in the context of the structured binding. 1425 // We already checked that the base class is accessible. 1426 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1427 // const_cast here. 1428 S.CheckStructuredBindingMemberAccess( 1429 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1430 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1431 BasePair.getAccess(), FD->getAccess()))); 1432 1433 // Initialize the binding to Src.FD. 1434 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1435 if (E.isInvalid()) 1436 return true; 1437 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1438 VK_LValue, &BasePath); 1439 if (E.isInvalid()) 1440 return true; 1441 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1442 CXXScopeSpec(), FD, 1443 DeclAccessPair::make(FD, FD->getAccess()), 1444 DeclarationNameInfo(FD->getDeclName(), Loc)); 1445 if (E.isInvalid()) 1446 return true; 1447 1448 // If the type of the member is T, the referenced type is cv T, where cv is 1449 // the cv-qualification of the decomposition expression. 1450 // 1451 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1452 // 'const' to the type of the field. 1453 Qualifiers Q = DecompType.getQualifiers(); 1454 if (FD->isMutable()) 1455 Q.removeConst(); 1456 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1457 } 1458 1459 if (I != Bindings.size()) 1460 return DiagnoseBadNumberOfBindings(); 1461 1462 return false; 1463 } 1464 1465 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1466 QualType DecompType = DD->getType(); 1467 1468 // If the type of the decomposition is dependent, then so is the type of 1469 // each binding. 1470 if (DecompType->isDependentType()) { 1471 for (auto *B : DD->bindings()) 1472 B->setType(Context.DependentTy); 1473 return; 1474 } 1475 1476 DecompType = DecompType.getNonReferenceType(); 1477 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1478 1479 // C++1z [dcl.decomp]/2: 1480 // If E is an array type [...] 1481 // As an extension, we also support decomposition of built-in complex and 1482 // vector types. 1483 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1484 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1485 DD->setInvalidDecl(); 1486 return; 1487 } 1488 if (auto *VT = DecompType->getAs<VectorType>()) { 1489 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1490 DD->setInvalidDecl(); 1491 return; 1492 } 1493 if (auto *CT = DecompType->getAs<ComplexType>()) { 1494 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1495 DD->setInvalidDecl(); 1496 return; 1497 } 1498 1499 // C++1z [dcl.decomp]/3: 1500 // if the expression std::tuple_size<E>::value is a well-formed integral 1501 // constant expression, [...] 1502 llvm::APSInt TupleSize(32); 1503 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1504 case IsTupleLike::Error: 1505 DD->setInvalidDecl(); 1506 return; 1507 1508 case IsTupleLike::TupleLike: 1509 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1510 DD->setInvalidDecl(); 1511 return; 1512 1513 case IsTupleLike::NotTupleLike: 1514 break; 1515 } 1516 1517 // C++1z [dcl.dcl]/8: 1518 // [E shall be of array or non-union class type] 1519 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1520 if (!RD || RD->isUnion()) { 1521 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1522 << DD << !RD << DecompType; 1523 DD->setInvalidDecl(); 1524 return; 1525 } 1526 1527 // C++1z [dcl.decomp]/4: 1528 // all of E's non-static data members shall be [...] direct members of 1529 // E or of the same unambiguous public base class of E, ... 1530 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1531 DD->setInvalidDecl(); 1532 } 1533 1534 /// Merge the exception specifications of two variable declarations. 1535 /// 1536 /// This is called when there's a redeclaration of a VarDecl. The function 1537 /// checks if the redeclaration might have an exception specification and 1538 /// validates compatibility and merges the specs if necessary. 1539 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1540 // Shortcut if exceptions are disabled. 1541 if (!getLangOpts().CXXExceptions) 1542 return; 1543 1544 assert(Context.hasSameType(New->getType(), Old->getType()) && 1545 "Should only be called if types are otherwise the same."); 1546 1547 QualType NewType = New->getType(); 1548 QualType OldType = Old->getType(); 1549 1550 // We're only interested in pointers and references to functions, as well 1551 // as pointers to member functions. 1552 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1553 NewType = R->getPointeeType(); 1554 OldType = OldType->castAs<ReferenceType>()->getPointeeType(); 1555 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1556 NewType = P->getPointeeType(); 1557 OldType = OldType->castAs<PointerType>()->getPointeeType(); 1558 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1559 NewType = M->getPointeeType(); 1560 OldType = OldType->castAs<MemberPointerType>()->getPointeeType(); 1561 } 1562 1563 if (!NewType->isFunctionProtoType()) 1564 return; 1565 1566 // There's lots of special cases for functions. For function pointers, system 1567 // libraries are hopefully not as broken so that we don't need these 1568 // workarounds. 1569 if (CheckEquivalentExceptionSpec( 1570 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1571 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1572 New->setInvalidDecl(); 1573 } 1574 } 1575 1576 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1577 /// function declaration are well-formed according to C++ 1578 /// [dcl.fct.default]. 1579 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1580 unsigned NumParams = FD->getNumParams(); 1581 unsigned ParamIdx = 0; 1582 1583 // This checking doesn't make sense for explicit specializations; their 1584 // default arguments are determined by the declaration we're specializing, 1585 // not by FD. 1586 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1587 return; 1588 if (auto *FTD = FD->getDescribedFunctionTemplate()) 1589 if (FTD->isMemberSpecialization()) 1590 return; 1591 1592 // Find first parameter with a default argument 1593 for (; ParamIdx < NumParams; ++ParamIdx) { 1594 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1595 if (Param->hasDefaultArg()) 1596 break; 1597 } 1598 1599 // C++20 [dcl.fct.default]p4: 1600 // In a given function declaration, each parameter subsequent to a parameter 1601 // with a default argument shall have a default argument supplied in this or 1602 // a previous declaration, unless the parameter was expanded from a 1603 // parameter pack, or shall be a function parameter pack. 1604 for (; ParamIdx < NumParams; ++ParamIdx) { 1605 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1606 if (!Param->hasDefaultArg() && !Param->isParameterPack() && 1607 !(CurrentInstantiationScope && 1608 CurrentInstantiationScope->isLocalPackExpansion(Param))) { 1609 if (Param->isInvalidDecl()) 1610 /* We already complained about this parameter. */; 1611 else if (Param->getIdentifier()) 1612 Diag(Param->getLocation(), 1613 diag::err_param_default_argument_missing_name) 1614 << Param->getIdentifier(); 1615 else 1616 Diag(Param->getLocation(), 1617 diag::err_param_default_argument_missing); 1618 } 1619 } 1620 } 1621 1622 /// Check that the given type is a literal type. Issue a diagnostic if not, 1623 /// if Kind is Diagnose. 1624 /// \return \c true if a problem has been found (and optionally diagnosed). 1625 template <typename... Ts> 1626 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1627 SourceLocation Loc, QualType T, unsigned DiagID, 1628 Ts &&...DiagArgs) { 1629 if (T->isDependentType()) 1630 return false; 1631 1632 switch (Kind) { 1633 case Sema::CheckConstexprKind::Diagnose: 1634 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1635 std::forward<Ts>(DiagArgs)...); 1636 1637 case Sema::CheckConstexprKind::CheckValid: 1638 return !T->isLiteralType(SemaRef.Context); 1639 } 1640 1641 llvm_unreachable("unknown CheckConstexprKind"); 1642 } 1643 1644 /// Determine whether a destructor cannot be constexpr due to 1645 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, 1646 const CXXDestructorDecl *DD, 1647 Sema::CheckConstexprKind Kind) { 1648 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { 1649 const CXXRecordDecl *RD = 1650 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1651 if (!RD || RD->hasConstexprDestructor()) 1652 return true; 1653 1654 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1655 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) 1656 << static_cast<int>(DD->getConstexprKind()) << !FD 1657 << (FD ? FD->getDeclName() : DeclarationName()) << T; 1658 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) 1659 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; 1660 } 1661 return false; 1662 }; 1663 1664 const CXXRecordDecl *RD = DD->getParent(); 1665 for (const CXXBaseSpecifier &B : RD->bases()) 1666 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) 1667 return false; 1668 for (const FieldDecl *FD : RD->fields()) 1669 if (!Check(FD->getLocation(), FD->getType(), FD)) 1670 return false; 1671 return true; 1672 } 1673 1674 /// Check whether a function's parameter types are all literal types. If so, 1675 /// return true. If not, produce a suitable diagnostic and return false. 1676 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1677 const FunctionDecl *FD, 1678 Sema::CheckConstexprKind Kind) { 1679 unsigned ArgIndex = 0; 1680 const auto *FT = FD->getType()->castAs<FunctionProtoType>(); 1681 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1682 e = FT->param_type_end(); 1683 i != e; ++i, ++ArgIndex) { 1684 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1685 SourceLocation ParamLoc = PD->getLocation(); 1686 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1687 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1688 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1689 FD->isConsteval())) 1690 return false; 1691 } 1692 return true; 1693 } 1694 1695 /// Check whether a function's return type is a literal type. If so, return 1696 /// true. If not, produce a suitable diagnostic and return false. 1697 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, 1698 Sema::CheckConstexprKind Kind) { 1699 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), 1700 diag::err_constexpr_non_literal_return, 1701 FD->isConsteval())) 1702 return false; 1703 return true; 1704 } 1705 1706 /// Get diagnostic %select index for tag kind for 1707 /// record diagnostic message. 1708 /// WARNING: Indexes apply to particular diagnostics only! 1709 /// 1710 /// \returns diagnostic %select index. 1711 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1712 switch (Tag) { 1713 case TTK_Struct: return 0; 1714 case TTK_Interface: return 1; 1715 case TTK_Class: return 2; 1716 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1717 } 1718 } 1719 1720 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1721 Stmt *Body, 1722 Sema::CheckConstexprKind Kind); 1723 1724 // Check whether a function declaration satisfies the requirements of a 1725 // constexpr function definition or a constexpr constructor definition. If so, 1726 // return true. If not, produce appropriate diagnostics (unless asked not to by 1727 // Kind) and return false. 1728 // 1729 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1730 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1731 CheckConstexprKind Kind) { 1732 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1733 if (MD && MD->isInstance()) { 1734 // C++11 [dcl.constexpr]p4: 1735 // The definition of a constexpr constructor shall satisfy the following 1736 // constraints: 1737 // - the class shall not have any virtual base classes; 1738 // 1739 // FIXME: This only applies to constructors and destructors, not arbitrary 1740 // member functions. 1741 const CXXRecordDecl *RD = MD->getParent(); 1742 if (RD->getNumVBases()) { 1743 if (Kind == CheckConstexprKind::CheckValid) 1744 return false; 1745 1746 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1747 << isa<CXXConstructorDecl>(NewFD) 1748 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1749 for (const auto &I : RD->vbases()) 1750 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1751 << I.getSourceRange(); 1752 return false; 1753 } 1754 } 1755 1756 if (!isa<CXXConstructorDecl>(NewFD)) { 1757 // C++11 [dcl.constexpr]p3: 1758 // The definition of a constexpr function shall satisfy the following 1759 // constraints: 1760 // - it shall not be virtual; (removed in C++20) 1761 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1762 if (Method && Method->isVirtual()) { 1763 if (getLangOpts().CPlusPlus20) { 1764 if (Kind == CheckConstexprKind::Diagnose) 1765 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1766 } else { 1767 if (Kind == CheckConstexprKind::CheckValid) 1768 return false; 1769 1770 Method = Method->getCanonicalDecl(); 1771 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1772 1773 // If it's not obvious why this function is virtual, find an overridden 1774 // function which uses the 'virtual' keyword. 1775 const CXXMethodDecl *WrittenVirtual = Method; 1776 while (!WrittenVirtual->isVirtualAsWritten()) 1777 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1778 if (WrittenVirtual != Method) 1779 Diag(WrittenVirtual->getLocation(), 1780 diag::note_overridden_virtual_function); 1781 return false; 1782 } 1783 } 1784 1785 // - its return type shall be a literal type; 1786 if (!CheckConstexprReturnType(*this, NewFD, Kind)) 1787 return false; 1788 } 1789 1790 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { 1791 // A destructor can be constexpr only if the defaulted destructor could be; 1792 // we don't need to check the members and bases if we already know they all 1793 // have constexpr destructors. 1794 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { 1795 if (Kind == CheckConstexprKind::CheckValid) 1796 return false; 1797 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) 1798 return false; 1799 } 1800 } 1801 1802 // - each of its parameter types shall be a literal type; 1803 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1804 return false; 1805 1806 Stmt *Body = NewFD->getBody(); 1807 assert(Body && 1808 "CheckConstexprFunctionDefinition called on function with no body"); 1809 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1810 } 1811 1812 /// Check the given declaration statement is legal within a constexpr function 1813 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1814 /// 1815 /// \return true if the body is OK (maybe only as an extension), false if we 1816 /// have diagnosed a problem. 1817 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1818 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1819 Sema::CheckConstexprKind Kind) { 1820 // C++11 [dcl.constexpr]p3 and p4: 1821 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1822 // contain only 1823 for (const auto *DclIt : DS->decls()) { 1824 switch (DclIt->getKind()) { 1825 case Decl::StaticAssert: 1826 case Decl::Using: 1827 case Decl::UsingShadow: 1828 case Decl::UsingDirective: 1829 case Decl::UnresolvedUsingTypename: 1830 case Decl::UnresolvedUsingValue: 1831 // - static_assert-declarations 1832 // - using-declarations, 1833 // - using-directives, 1834 continue; 1835 1836 case Decl::Typedef: 1837 case Decl::TypeAlias: { 1838 // - typedef declarations and alias-declarations that do not define 1839 // classes or enumerations, 1840 const auto *TN = cast<TypedefNameDecl>(DclIt); 1841 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1842 // Don't allow variably-modified types in constexpr functions. 1843 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1844 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1845 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1846 << TL.getSourceRange() << TL.getType() 1847 << isa<CXXConstructorDecl>(Dcl); 1848 } 1849 return false; 1850 } 1851 continue; 1852 } 1853 1854 case Decl::Enum: 1855 case Decl::CXXRecord: 1856 // C++1y allows types to be defined, not just declared. 1857 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1858 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1859 SemaRef.Diag(DS->getBeginLoc(), 1860 SemaRef.getLangOpts().CPlusPlus14 1861 ? diag::warn_cxx11_compat_constexpr_type_definition 1862 : diag::ext_constexpr_type_definition) 1863 << isa<CXXConstructorDecl>(Dcl); 1864 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1865 return false; 1866 } 1867 } 1868 continue; 1869 1870 case Decl::EnumConstant: 1871 case Decl::IndirectField: 1872 case Decl::ParmVar: 1873 // These can only appear with other declarations which are banned in 1874 // C++11 and permitted in C++1y, so ignore them. 1875 continue; 1876 1877 case Decl::Var: 1878 case Decl::Decomposition: { 1879 // C++1y [dcl.constexpr]p3 allows anything except: 1880 // a definition of a variable of non-literal type or of static or 1881 // thread storage duration or [before C++2a] for which no 1882 // initialization is performed. 1883 const auto *VD = cast<VarDecl>(DclIt); 1884 if (VD->isThisDeclarationADefinition()) { 1885 if (VD->isStaticLocal()) { 1886 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1887 SemaRef.Diag(VD->getLocation(), 1888 diag::err_constexpr_local_var_static) 1889 << isa<CXXConstructorDecl>(Dcl) 1890 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1891 } 1892 return false; 1893 } 1894 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1895 diag::err_constexpr_local_var_non_literal_type, 1896 isa<CXXConstructorDecl>(Dcl))) 1897 return false; 1898 if (!VD->getType()->isDependentType() && 1899 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1900 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1901 SemaRef.Diag( 1902 VD->getLocation(), 1903 SemaRef.getLangOpts().CPlusPlus20 1904 ? diag::warn_cxx17_compat_constexpr_local_var_no_init 1905 : diag::ext_constexpr_local_var_no_init) 1906 << isa<CXXConstructorDecl>(Dcl); 1907 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1908 return false; 1909 } 1910 continue; 1911 } 1912 } 1913 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1914 SemaRef.Diag(VD->getLocation(), 1915 SemaRef.getLangOpts().CPlusPlus14 1916 ? diag::warn_cxx11_compat_constexpr_local_var 1917 : diag::ext_constexpr_local_var) 1918 << isa<CXXConstructorDecl>(Dcl); 1919 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1920 return false; 1921 } 1922 continue; 1923 } 1924 1925 case Decl::NamespaceAlias: 1926 case Decl::Function: 1927 // These are disallowed in C++11 and permitted in C++1y. Allow them 1928 // everywhere as an extension. 1929 if (!Cxx1yLoc.isValid()) 1930 Cxx1yLoc = DS->getBeginLoc(); 1931 continue; 1932 1933 default: 1934 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1935 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1936 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1937 } 1938 return false; 1939 } 1940 } 1941 1942 return true; 1943 } 1944 1945 /// Check that the given field is initialized within a constexpr constructor. 1946 /// 1947 /// \param Dcl The constexpr constructor being checked. 1948 /// \param Field The field being checked. This may be a member of an anonymous 1949 /// struct or union nested within the class being checked. 1950 /// \param Inits All declarations, including anonymous struct/union members and 1951 /// indirect members, for which any initialization was provided. 1952 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1953 /// multiple notes for different members to the same error. 1954 /// \param Kind Whether we're diagnosing a constructor as written or determining 1955 /// whether the formal requirements are satisfied. 1956 /// \return \c false if we're checking for validity and the constructor does 1957 /// not satisfy the requirements on a constexpr constructor. 1958 static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1959 const FunctionDecl *Dcl, 1960 FieldDecl *Field, 1961 llvm::SmallSet<Decl*, 16> &Inits, 1962 bool &Diagnosed, 1963 Sema::CheckConstexprKind Kind) { 1964 // In C++20 onwards, there's nothing to check for validity. 1965 if (Kind == Sema::CheckConstexprKind::CheckValid && 1966 SemaRef.getLangOpts().CPlusPlus20) 1967 return true; 1968 1969 if (Field->isInvalidDecl()) 1970 return true; 1971 1972 if (Field->isUnnamedBitfield()) 1973 return true; 1974 1975 // Anonymous unions with no variant members and empty anonymous structs do not 1976 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1977 // indirect fields don't need initializing. 1978 if (Field->isAnonymousStructOrUnion() && 1979 (Field->getType()->isUnionType() 1980 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1981 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1982 return true; 1983 1984 if (!Inits.count(Field)) { 1985 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1986 if (!Diagnosed) { 1987 SemaRef.Diag(Dcl->getLocation(), 1988 SemaRef.getLangOpts().CPlusPlus20 1989 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init 1990 : diag::ext_constexpr_ctor_missing_init); 1991 Diagnosed = true; 1992 } 1993 SemaRef.Diag(Field->getLocation(), 1994 diag::note_constexpr_ctor_missing_init); 1995 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1996 return false; 1997 } 1998 } else if (Field->isAnonymousStructOrUnion()) { 1999 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 2000 for (auto *I : RD->fields()) 2001 // If an anonymous union contains an anonymous struct of which any member 2002 // is initialized, all members must be initialized. 2003 if (!RD->isUnion() || Inits.count(I)) 2004 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2005 Kind)) 2006 return false; 2007 } 2008 return true; 2009 } 2010 2011 /// Check the provided statement is allowed in a constexpr function 2012 /// definition. 2013 static bool 2014 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 2015 SmallVectorImpl<SourceLocation> &ReturnStmts, 2016 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 2017 Sema::CheckConstexprKind Kind) { 2018 // - its function-body shall be [...] a compound-statement that contains only 2019 switch (S->getStmtClass()) { 2020 case Stmt::NullStmtClass: 2021 // - null statements, 2022 return true; 2023 2024 case Stmt::DeclStmtClass: 2025 // - static_assert-declarations 2026 // - using-declarations, 2027 // - using-directives, 2028 // - typedef declarations and alias-declarations that do not define 2029 // classes or enumerations, 2030 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 2031 return false; 2032 return true; 2033 2034 case Stmt::ReturnStmtClass: 2035 // - and exactly one return statement; 2036 if (isa<CXXConstructorDecl>(Dcl)) { 2037 // C++1y allows return statements in constexpr constructors. 2038 if (!Cxx1yLoc.isValid()) 2039 Cxx1yLoc = S->getBeginLoc(); 2040 return true; 2041 } 2042 2043 ReturnStmts.push_back(S->getBeginLoc()); 2044 return true; 2045 2046 case Stmt::CompoundStmtClass: { 2047 // C++1y allows compound-statements. 2048 if (!Cxx1yLoc.isValid()) 2049 Cxx1yLoc = S->getBeginLoc(); 2050 2051 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2052 for (auto *BodyIt : CompStmt->body()) { 2053 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2054 Cxx1yLoc, Cxx2aLoc, Kind)) 2055 return false; 2056 } 2057 return true; 2058 } 2059 2060 case Stmt::AttributedStmtClass: 2061 if (!Cxx1yLoc.isValid()) 2062 Cxx1yLoc = S->getBeginLoc(); 2063 return true; 2064 2065 case Stmt::IfStmtClass: { 2066 // C++1y allows if-statements. 2067 if (!Cxx1yLoc.isValid()) 2068 Cxx1yLoc = S->getBeginLoc(); 2069 2070 IfStmt *If = cast<IfStmt>(S); 2071 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2072 Cxx1yLoc, Cxx2aLoc, Kind)) 2073 return false; 2074 if (If->getElse() && 2075 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2076 Cxx1yLoc, Cxx2aLoc, Kind)) 2077 return false; 2078 return true; 2079 } 2080 2081 case Stmt::WhileStmtClass: 2082 case Stmt::DoStmtClass: 2083 case Stmt::ForStmtClass: 2084 case Stmt::CXXForRangeStmtClass: 2085 case Stmt::ContinueStmtClass: 2086 // C++1y allows all of these. We don't allow them as extensions in C++11, 2087 // because they don't make sense without variable mutation. 2088 if (!SemaRef.getLangOpts().CPlusPlus14) 2089 break; 2090 if (!Cxx1yLoc.isValid()) 2091 Cxx1yLoc = S->getBeginLoc(); 2092 for (Stmt *SubStmt : S->children()) 2093 if (SubStmt && 2094 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2095 Cxx1yLoc, Cxx2aLoc, Kind)) 2096 return false; 2097 return true; 2098 2099 case Stmt::SwitchStmtClass: 2100 case Stmt::CaseStmtClass: 2101 case Stmt::DefaultStmtClass: 2102 case Stmt::BreakStmtClass: 2103 // C++1y allows switch-statements, and since they don't need variable 2104 // mutation, we can reasonably allow them in C++11 as an extension. 2105 if (!Cxx1yLoc.isValid()) 2106 Cxx1yLoc = S->getBeginLoc(); 2107 for (Stmt *SubStmt : S->children()) 2108 if (SubStmt && 2109 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2110 Cxx1yLoc, Cxx2aLoc, Kind)) 2111 return false; 2112 return true; 2113 2114 case Stmt::GCCAsmStmtClass: 2115 case Stmt::MSAsmStmtClass: 2116 // C++2a allows inline assembly statements. 2117 case Stmt::CXXTryStmtClass: 2118 if (Cxx2aLoc.isInvalid()) 2119 Cxx2aLoc = S->getBeginLoc(); 2120 for (Stmt *SubStmt : S->children()) { 2121 if (SubStmt && 2122 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2123 Cxx1yLoc, Cxx2aLoc, Kind)) 2124 return false; 2125 } 2126 return true; 2127 2128 case Stmt::CXXCatchStmtClass: 2129 // Do not bother checking the language mode (already covered by the 2130 // try block check). 2131 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2132 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2133 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2134 return false; 2135 return true; 2136 2137 default: 2138 if (!isa<Expr>(S)) 2139 break; 2140 2141 // C++1y allows expression-statements. 2142 if (!Cxx1yLoc.isValid()) 2143 Cxx1yLoc = S->getBeginLoc(); 2144 return true; 2145 } 2146 2147 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2148 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2149 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2150 } 2151 return false; 2152 } 2153 2154 /// Check the body for the given constexpr function declaration only contains 2155 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2156 /// 2157 /// \return true if the body is OK, false if we have found or diagnosed a 2158 /// problem. 2159 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2160 Stmt *Body, 2161 Sema::CheckConstexprKind Kind) { 2162 SmallVector<SourceLocation, 4> ReturnStmts; 2163 2164 if (isa<CXXTryStmt>(Body)) { 2165 // C++11 [dcl.constexpr]p3: 2166 // The definition of a constexpr function shall satisfy the following 2167 // constraints: [...] 2168 // - its function-body shall be = delete, = default, or a 2169 // compound-statement 2170 // 2171 // C++11 [dcl.constexpr]p4: 2172 // In the definition of a constexpr constructor, [...] 2173 // - its function-body shall not be a function-try-block; 2174 // 2175 // This restriction is lifted in C++2a, as long as inner statements also 2176 // apply the general constexpr rules. 2177 switch (Kind) { 2178 case Sema::CheckConstexprKind::CheckValid: 2179 if (!SemaRef.getLangOpts().CPlusPlus20) 2180 return false; 2181 break; 2182 2183 case Sema::CheckConstexprKind::Diagnose: 2184 SemaRef.Diag(Body->getBeginLoc(), 2185 !SemaRef.getLangOpts().CPlusPlus20 2186 ? diag::ext_constexpr_function_try_block_cxx20 2187 : diag::warn_cxx17_compat_constexpr_function_try_block) 2188 << isa<CXXConstructorDecl>(Dcl); 2189 break; 2190 } 2191 } 2192 2193 // - its function-body shall be [...] a compound-statement that contains only 2194 // [... list of cases ...] 2195 // 2196 // Note that walking the children here is enough to properly check for 2197 // CompoundStmt and CXXTryStmt body. 2198 SourceLocation Cxx1yLoc, Cxx2aLoc; 2199 for (Stmt *SubStmt : Body->children()) { 2200 if (SubStmt && 2201 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2202 Cxx1yLoc, Cxx2aLoc, Kind)) 2203 return false; 2204 } 2205 2206 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2207 // If this is only valid as an extension, report that we don't satisfy the 2208 // constraints of the current language. 2209 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) || 2210 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2211 return false; 2212 } else if (Cxx2aLoc.isValid()) { 2213 SemaRef.Diag(Cxx2aLoc, 2214 SemaRef.getLangOpts().CPlusPlus20 2215 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2216 : diag::ext_constexpr_body_invalid_stmt_cxx20) 2217 << isa<CXXConstructorDecl>(Dcl); 2218 } else if (Cxx1yLoc.isValid()) { 2219 SemaRef.Diag(Cxx1yLoc, 2220 SemaRef.getLangOpts().CPlusPlus14 2221 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2222 : diag::ext_constexpr_body_invalid_stmt) 2223 << isa<CXXConstructorDecl>(Dcl); 2224 } 2225 2226 if (const CXXConstructorDecl *Constructor 2227 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2228 const CXXRecordDecl *RD = Constructor->getParent(); 2229 // DR1359: 2230 // - every non-variant non-static data member and base class sub-object 2231 // shall be initialized; 2232 // DR1460: 2233 // - if the class is a union having variant members, exactly one of them 2234 // shall be initialized; 2235 if (RD->isUnion()) { 2236 if (Constructor->getNumCtorInitializers() == 0 && 2237 RD->hasVariantMembers()) { 2238 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2239 SemaRef.Diag( 2240 Dcl->getLocation(), 2241 SemaRef.getLangOpts().CPlusPlus20 2242 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2243 : diag::ext_constexpr_union_ctor_no_init); 2244 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2245 return false; 2246 } 2247 } 2248 } else if (!Constructor->isDependentContext() && 2249 !Constructor->isDelegatingConstructor()) { 2250 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2251 2252 // Skip detailed checking if we have enough initializers, and we would 2253 // allow at most one initializer per member. 2254 bool AnyAnonStructUnionMembers = false; 2255 unsigned Fields = 0; 2256 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2257 E = RD->field_end(); I != E; ++I, ++Fields) { 2258 if (I->isAnonymousStructOrUnion()) { 2259 AnyAnonStructUnionMembers = true; 2260 break; 2261 } 2262 } 2263 // DR1460: 2264 // - if the class is a union-like class, but is not a union, for each of 2265 // its anonymous union members having variant members, exactly one of 2266 // them shall be initialized; 2267 if (AnyAnonStructUnionMembers || 2268 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2269 // Check initialization of non-static data members. Base classes are 2270 // always initialized so do not need to be checked. Dependent bases 2271 // might not have initializers in the member initializer list. 2272 llvm::SmallSet<Decl*, 16> Inits; 2273 for (const auto *I: Constructor->inits()) { 2274 if (FieldDecl *FD = I->getMember()) 2275 Inits.insert(FD); 2276 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2277 Inits.insert(ID->chain_begin(), ID->chain_end()); 2278 } 2279 2280 bool Diagnosed = false; 2281 for (auto *I : RD->fields()) 2282 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2283 Kind)) 2284 return false; 2285 } 2286 } 2287 } else { 2288 if (ReturnStmts.empty()) { 2289 // C++1y doesn't require constexpr functions to contain a 'return' 2290 // statement. We still do, unless the return type might be void, because 2291 // otherwise if there's no return statement, the function cannot 2292 // be used in a core constant expression. 2293 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2294 (Dcl->getReturnType()->isVoidType() || 2295 Dcl->getReturnType()->isDependentType()); 2296 switch (Kind) { 2297 case Sema::CheckConstexprKind::Diagnose: 2298 SemaRef.Diag(Dcl->getLocation(), 2299 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2300 : diag::err_constexpr_body_no_return) 2301 << Dcl->isConsteval(); 2302 if (!OK) 2303 return false; 2304 break; 2305 2306 case Sema::CheckConstexprKind::CheckValid: 2307 // The formal requirements don't include this rule in C++14, even 2308 // though the "must be able to produce a constant expression" rules 2309 // still imply it in some cases. 2310 if (!SemaRef.getLangOpts().CPlusPlus14) 2311 return false; 2312 break; 2313 } 2314 } else if (ReturnStmts.size() > 1) { 2315 switch (Kind) { 2316 case Sema::CheckConstexprKind::Diagnose: 2317 SemaRef.Diag( 2318 ReturnStmts.back(), 2319 SemaRef.getLangOpts().CPlusPlus14 2320 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2321 : diag::ext_constexpr_body_multiple_return); 2322 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2323 SemaRef.Diag(ReturnStmts[I], 2324 diag::note_constexpr_body_previous_return); 2325 break; 2326 2327 case Sema::CheckConstexprKind::CheckValid: 2328 if (!SemaRef.getLangOpts().CPlusPlus14) 2329 return false; 2330 break; 2331 } 2332 } 2333 } 2334 2335 // C++11 [dcl.constexpr]p5: 2336 // if no function argument values exist such that the function invocation 2337 // substitution would produce a constant expression, the program is 2338 // ill-formed; no diagnostic required. 2339 // C++11 [dcl.constexpr]p3: 2340 // - every constructor call and implicit conversion used in initializing the 2341 // return value shall be one of those allowed in a constant expression. 2342 // C++11 [dcl.constexpr]p4: 2343 // - every constructor involved in initializing non-static data members and 2344 // base class sub-objects shall be a constexpr constructor. 2345 // 2346 // Note that this rule is distinct from the "requirements for a constexpr 2347 // function", so is not checked in CheckValid mode. 2348 SmallVector<PartialDiagnosticAt, 8> Diags; 2349 if (Kind == Sema::CheckConstexprKind::Diagnose && 2350 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2351 SemaRef.Diag(Dcl->getLocation(), 2352 diag::ext_constexpr_function_never_constant_expr) 2353 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2354 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2355 SemaRef.Diag(Diags[I].first, Diags[I].second); 2356 // Don't return false here: we allow this for compatibility in 2357 // system headers. 2358 } 2359 2360 return true; 2361 } 2362 2363 /// Get the class that is directly named by the current context. This is the 2364 /// class for which an unqualified-id in this scope could name a constructor 2365 /// or destructor. 2366 /// 2367 /// If the scope specifier denotes a class, this will be that class. 2368 /// If the scope specifier is empty, this will be the class whose 2369 /// member-specification we are currently within. Otherwise, there 2370 /// is no such class. 2371 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2372 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2373 2374 if (SS && SS->isInvalid()) 2375 return nullptr; 2376 2377 if (SS && SS->isNotEmpty()) { 2378 DeclContext *DC = computeDeclContext(*SS, true); 2379 return dyn_cast_or_null<CXXRecordDecl>(DC); 2380 } 2381 2382 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2383 } 2384 2385 /// isCurrentClassName - Determine whether the identifier II is the 2386 /// name of the class type currently being defined. In the case of 2387 /// nested classes, this will only return true if II is the name of 2388 /// the innermost class. 2389 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2390 const CXXScopeSpec *SS) { 2391 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2392 return CurDecl && &II == CurDecl->getIdentifier(); 2393 } 2394 2395 /// Determine whether the identifier II is a typo for the name of 2396 /// the class type currently being defined. If so, update it to the identifier 2397 /// that should have been used. 2398 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2399 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2400 2401 if (!getLangOpts().SpellChecking) 2402 return false; 2403 2404 CXXRecordDecl *CurDecl; 2405 if (SS && SS->isSet() && !SS->isInvalid()) { 2406 DeclContext *DC = computeDeclContext(*SS, true); 2407 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2408 } else 2409 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2410 2411 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2412 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2413 < II->getLength()) { 2414 II = CurDecl->getIdentifier(); 2415 return true; 2416 } 2417 2418 return false; 2419 } 2420 2421 /// Determine whether the given class is a base class of the given 2422 /// class, including looking at dependent bases. 2423 static bool findCircularInheritance(const CXXRecordDecl *Class, 2424 const CXXRecordDecl *Current) { 2425 SmallVector<const CXXRecordDecl*, 8> Queue; 2426 2427 Class = Class->getCanonicalDecl(); 2428 while (true) { 2429 for (const auto &I : Current->bases()) { 2430 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2431 if (!Base) 2432 continue; 2433 2434 Base = Base->getDefinition(); 2435 if (!Base) 2436 continue; 2437 2438 if (Base->getCanonicalDecl() == Class) 2439 return true; 2440 2441 Queue.push_back(Base); 2442 } 2443 2444 if (Queue.empty()) 2445 return false; 2446 2447 Current = Queue.pop_back_val(); 2448 } 2449 2450 return false; 2451 } 2452 2453 /// Check the validity of a C++ base class specifier. 2454 /// 2455 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2456 /// and returns NULL otherwise. 2457 CXXBaseSpecifier * 2458 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2459 SourceRange SpecifierRange, 2460 bool Virtual, AccessSpecifier Access, 2461 TypeSourceInfo *TInfo, 2462 SourceLocation EllipsisLoc) { 2463 QualType BaseType = TInfo->getType(); 2464 if (BaseType->containsErrors()) { 2465 // Already emitted a diagnostic when parsing the error type. 2466 return nullptr; 2467 } 2468 // C++ [class.union]p1: 2469 // A union shall not have base classes. 2470 if (Class->isUnion()) { 2471 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2472 << SpecifierRange; 2473 return nullptr; 2474 } 2475 2476 if (EllipsisLoc.isValid() && 2477 !TInfo->getType()->containsUnexpandedParameterPack()) { 2478 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2479 << TInfo->getTypeLoc().getSourceRange(); 2480 EllipsisLoc = SourceLocation(); 2481 } 2482 2483 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2484 2485 if (BaseType->isDependentType()) { 2486 // Make sure that we don't have circular inheritance among our dependent 2487 // bases. For non-dependent bases, the check for completeness below handles 2488 // this. 2489 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2490 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2491 ((BaseDecl = BaseDecl->getDefinition()) && 2492 findCircularInheritance(Class, BaseDecl))) { 2493 Diag(BaseLoc, diag::err_circular_inheritance) 2494 << BaseType << Context.getTypeDeclType(Class); 2495 2496 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2497 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2498 << BaseType; 2499 2500 return nullptr; 2501 } 2502 } 2503 2504 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2505 Class->getTagKind() == TTK_Class, 2506 Access, TInfo, EllipsisLoc); 2507 } 2508 2509 // Base specifiers must be record types. 2510 if (!BaseType->isRecordType()) { 2511 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2512 return nullptr; 2513 } 2514 2515 // C++ [class.union]p1: 2516 // A union shall not be used as a base class. 2517 if (BaseType->isUnionType()) { 2518 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2519 return nullptr; 2520 } 2521 2522 // For the MS ABI, propagate DLL attributes to base class templates. 2523 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2524 if (Attr *ClassAttr = getDLLAttr(Class)) { 2525 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2526 BaseType->getAsCXXRecordDecl())) { 2527 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2528 BaseLoc); 2529 } 2530 } 2531 } 2532 2533 // C++ [class.derived]p2: 2534 // The class-name in a base-specifier shall not be an incompletely 2535 // defined class. 2536 if (RequireCompleteType(BaseLoc, BaseType, 2537 diag::err_incomplete_base_class, SpecifierRange)) { 2538 Class->setInvalidDecl(); 2539 return nullptr; 2540 } 2541 2542 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2543 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2544 assert(BaseDecl && "Record type has no declaration"); 2545 BaseDecl = BaseDecl->getDefinition(); 2546 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2547 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2548 assert(CXXBaseDecl && "Base type is not a C++ type"); 2549 2550 // Microsoft docs say: 2551 // "If a base-class has a code_seg attribute, derived classes must have the 2552 // same attribute." 2553 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2554 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2555 if ((DerivedCSA || BaseCSA) && 2556 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2557 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2558 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2559 << CXXBaseDecl; 2560 return nullptr; 2561 } 2562 2563 // A class which contains a flexible array member is not suitable for use as a 2564 // base class: 2565 // - If the layout determines that a base comes before another base, 2566 // the flexible array member would index into the subsequent base. 2567 // - If the layout determines that base comes before the derived class, 2568 // the flexible array member would index into the derived class. 2569 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2570 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2571 << CXXBaseDecl->getDeclName(); 2572 return nullptr; 2573 } 2574 2575 // C++ [class]p3: 2576 // If a class is marked final and it appears as a base-type-specifier in 2577 // base-clause, the program is ill-formed. 2578 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2579 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2580 << CXXBaseDecl->getDeclName() 2581 << FA->isSpelledAsSealed(); 2582 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2583 << CXXBaseDecl->getDeclName() << FA->getRange(); 2584 return nullptr; 2585 } 2586 2587 if (BaseDecl->isInvalidDecl()) 2588 Class->setInvalidDecl(); 2589 2590 // Create the base specifier. 2591 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2592 Class->getTagKind() == TTK_Class, 2593 Access, TInfo, EllipsisLoc); 2594 } 2595 2596 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2597 /// one entry in the base class list of a class specifier, for 2598 /// example: 2599 /// class foo : public bar, virtual private baz { 2600 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2601 BaseResult 2602 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2603 ParsedAttributes &Attributes, 2604 bool Virtual, AccessSpecifier Access, 2605 ParsedType basetype, SourceLocation BaseLoc, 2606 SourceLocation EllipsisLoc) { 2607 if (!classdecl) 2608 return true; 2609 2610 AdjustDeclIfTemplate(classdecl); 2611 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2612 if (!Class) 2613 return true; 2614 2615 // We haven't yet attached the base specifiers. 2616 Class->setIsParsingBaseSpecifiers(); 2617 2618 // We do not support any C++11 attributes on base-specifiers yet. 2619 // Diagnose any attributes we see. 2620 for (const ParsedAttr &AL : Attributes) { 2621 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2622 continue; 2623 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2624 ? (unsigned)diag::warn_unknown_attribute_ignored 2625 : (unsigned)diag::err_base_specifier_attribute) 2626 << AL << AL.getRange(); 2627 } 2628 2629 TypeSourceInfo *TInfo = nullptr; 2630 GetTypeFromParser(basetype, &TInfo); 2631 2632 if (EllipsisLoc.isInvalid() && 2633 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2634 UPPC_BaseType)) 2635 return true; 2636 2637 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2638 Virtual, Access, TInfo, 2639 EllipsisLoc)) 2640 return BaseSpec; 2641 else 2642 Class->setInvalidDecl(); 2643 2644 return true; 2645 } 2646 2647 /// Use small set to collect indirect bases. As this is only used 2648 /// locally, there's no need to abstract the small size parameter. 2649 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2650 2651 /// Recursively add the bases of Type. Don't add Type itself. 2652 static void 2653 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2654 const QualType &Type) 2655 { 2656 // Even though the incoming type is a base, it might not be 2657 // a class -- it could be a template parm, for instance. 2658 if (auto Rec = Type->getAs<RecordType>()) { 2659 auto Decl = Rec->getAsCXXRecordDecl(); 2660 2661 // Iterate over its bases. 2662 for (const auto &BaseSpec : Decl->bases()) { 2663 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2664 .getUnqualifiedType(); 2665 if (Set.insert(Base).second) 2666 // If we've not already seen it, recurse. 2667 NoteIndirectBases(Context, Set, Base); 2668 } 2669 } 2670 } 2671 2672 /// Performs the actual work of attaching the given base class 2673 /// specifiers to a C++ class. 2674 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2675 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2676 if (Bases.empty()) 2677 return false; 2678 2679 // Used to keep track of which base types we have already seen, so 2680 // that we can properly diagnose redundant direct base types. Note 2681 // that the key is always the unqualified canonical type of the base 2682 // class. 2683 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2684 2685 // Used to track indirect bases so we can see if a direct base is 2686 // ambiguous. 2687 IndirectBaseSet IndirectBaseTypes; 2688 2689 // Copy non-redundant base specifiers into permanent storage. 2690 unsigned NumGoodBases = 0; 2691 bool Invalid = false; 2692 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2693 QualType NewBaseType 2694 = Context.getCanonicalType(Bases[idx]->getType()); 2695 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2696 2697 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2698 if (KnownBase) { 2699 // C++ [class.mi]p3: 2700 // A class shall not be specified as a direct base class of a 2701 // derived class more than once. 2702 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2703 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2704 2705 // Delete the duplicate base class specifier; we're going to 2706 // overwrite its pointer later. 2707 Context.Deallocate(Bases[idx]); 2708 2709 Invalid = true; 2710 } else { 2711 // Okay, add this new base class. 2712 KnownBase = Bases[idx]; 2713 Bases[NumGoodBases++] = Bases[idx]; 2714 2715 // Note this base's direct & indirect bases, if there could be ambiguity. 2716 if (Bases.size() > 1) 2717 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2718 2719 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2720 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2721 if (Class->isInterface() && 2722 (!RD->isInterfaceLike() || 2723 KnownBase->getAccessSpecifier() != AS_public)) { 2724 // The Microsoft extension __interface does not permit bases that 2725 // are not themselves public interfaces. 2726 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2727 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2728 << RD->getSourceRange(); 2729 Invalid = true; 2730 } 2731 if (RD->hasAttr<WeakAttr>()) 2732 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2733 } 2734 } 2735 } 2736 2737 // Attach the remaining base class specifiers to the derived class. 2738 Class->setBases(Bases.data(), NumGoodBases); 2739 2740 // Check that the only base classes that are duplicate are virtual. 2741 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2742 // Check whether this direct base is inaccessible due to ambiguity. 2743 QualType BaseType = Bases[idx]->getType(); 2744 2745 // Skip all dependent types in templates being used as base specifiers. 2746 // Checks below assume that the base specifier is a CXXRecord. 2747 if (BaseType->isDependentType()) 2748 continue; 2749 2750 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2751 .getUnqualifiedType(); 2752 2753 if (IndirectBaseTypes.count(CanonicalBase)) { 2754 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2755 /*DetectVirtual=*/true); 2756 bool found 2757 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2758 assert(found); 2759 (void)found; 2760 2761 if (Paths.isAmbiguous(CanonicalBase)) 2762 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2763 << BaseType << getAmbiguousPathsDisplayString(Paths) 2764 << Bases[idx]->getSourceRange(); 2765 else 2766 assert(Bases[idx]->isVirtual()); 2767 } 2768 2769 // Delete the base class specifier, since its data has been copied 2770 // into the CXXRecordDecl. 2771 Context.Deallocate(Bases[idx]); 2772 } 2773 2774 return Invalid; 2775 } 2776 2777 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2778 /// class, after checking whether there are any duplicate base 2779 /// classes. 2780 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2781 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2782 if (!ClassDecl || Bases.empty()) 2783 return; 2784 2785 AdjustDeclIfTemplate(ClassDecl); 2786 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2787 } 2788 2789 /// Determine whether the type \p Derived is a C++ class that is 2790 /// derived from the type \p Base. 2791 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2792 if (!getLangOpts().CPlusPlus) 2793 return false; 2794 2795 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2796 if (!DerivedRD) 2797 return false; 2798 2799 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2800 if (!BaseRD) 2801 return false; 2802 2803 // If either the base or the derived type is invalid, don't try to 2804 // check whether one is derived from the other. 2805 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2806 return false; 2807 2808 // FIXME: In a modules build, do we need the entire path to be visible for us 2809 // to be able to use the inheritance relationship? 2810 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2811 return false; 2812 2813 return DerivedRD->isDerivedFrom(BaseRD); 2814 } 2815 2816 /// Determine whether the type \p Derived is a C++ class that is 2817 /// derived from the type \p Base. 2818 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2819 CXXBasePaths &Paths) { 2820 if (!getLangOpts().CPlusPlus) 2821 return false; 2822 2823 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2824 if (!DerivedRD) 2825 return false; 2826 2827 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2828 if (!BaseRD) 2829 return false; 2830 2831 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2832 return false; 2833 2834 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2835 } 2836 2837 static void BuildBasePathArray(const CXXBasePath &Path, 2838 CXXCastPath &BasePathArray) { 2839 // We first go backward and check if we have a virtual base. 2840 // FIXME: It would be better if CXXBasePath had the base specifier for 2841 // the nearest virtual base. 2842 unsigned Start = 0; 2843 for (unsigned I = Path.size(); I != 0; --I) { 2844 if (Path[I - 1].Base->isVirtual()) { 2845 Start = I - 1; 2846 break; 2847 } 2848 } 2849 2850 // Now add all bases. 2851 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2852 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2853 } 2854 2855 2856 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2857 CXXCastPath &BasePathArray) { 2858 assert(BasePathArray.empty() && "Base path array must be empty!"); 2859 assert(Paths.isRecordingPaths() && "Must record paths!"); 2860 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2861 } 2862 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2863 /// conversion (where Derived and Base are class types) is 2864 /// well-formed, meaning that the conversion is unambiguous (and 2865 /// that all of the base classes are accessible). Returns true 2866 /// and emits a diagnostic if the code is ill-formed, returns false 2867 /// otherwise. Loc is the location where this routine should point to 2868 /// if there is an error, and Range is the source range to highlight 2869 /// if there is an error. 2870 /// 2871 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the 2872 /// diagnostic for the respective type of error will be suppressed, but the 2873 /// check for ill-formed code will still be performed. 2874 bool 2875 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2876 unsigned InaccessibleBaseID, 2877 unsigned AmbiguousBaseConvID, 2878 SourceLocation Loc, SourceRange Range, 2879 DeclarationName Name, 2880 CXXCastPath *BasePath, 2881 bool IgnoreAccess) { 2882 // First, determine whether the path from Derived to Base is 2883 // ambiguous. This is slightly more expensive than checking whether 2884 // the Derived to Base conversion exists, because here we need to 2885 // explore multiple paths to determine if there is an ambiguity. 2886 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2887 /*DetectVirtual=*/false); 2888 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2889 if (!DerivationOkay) 2890 return true; 2891 2892 const CXXBasePath *Path = nullptr; 2893 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2894 Path = &Paths.front(); 2895 2896 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2897 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2898 // user to access such bases. 2899 if (!Path && getLangOpts().MSVCCompat) { 2900 for (const CXXBasePath &PossiblePath : Paths) { 2901 if (PossiblePath.size() == 1) { 2902 Path = &PossiblePath; 2903 if (AmbiguousBaseConvID) 2904 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2905 << Base << Derived << Range; 2906 break; 2907 } 2908 } 2909 } 2910 2911 if (Path) { 2912 if (!IgnoreAccess) { 2913 // Check that the base class can be accessed. 2914 switch ( 2915 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2916 case AR_inaccessible: 2917 return true; 2918 case AR_accessible: 2919 case AR_dependent: 2920 case AR_delayed: 2921 break; 2922 } 2923 } 2924 2925 // Build a base path if necessary. 2926 if (BasePath) 2927 ::BuildBasePathArray(*Path, *BasePath); 2928 return false; 2929 } 2930 2931 if (AmbiguousBaseConvID) { 2932 // We know that the derived-to-base conversion is ambiguous, and 2933 // we're going to produce a diagnostic. Perform the derived-to-base 2934 // search just one more time to compute all of the possible paths so 2935 // that we can print them out. This is more expensive than any of 2936 // the previous derived-to-base checks we've done, but at this point 2937 // performance isn't as much of an issue. 2938 Paths.clear(); 2939 Paths.setRecordingPaths(true); 2940 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2941 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2942 (void)StillOkay; 2943 2944 // Build up a textual representation of the ambiguous paths, e.g., 2945 // D -> B -> A, that will be used to illustrate the ambiguous 2946 // conversions in the diagnostic. We only print one of the paths 2947 // to each base class subobject. 2948 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2949 2950 Diag(Loc, AmbiguousBaseConvID) 2951 << Derived << Base << PathDisplayStr << Range << Name; 2952 } 2953 return true; 2954 } 2955 2956 bool 2957 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2958 SourceLocation Loc, SourceRange Range, 2959 CXXCastPath *BasePath, 2960 bool IgnoreAccess) { 2961 return CheckDerivedToBaseConversion( 2962 Derived, Base, diag::err_upcast_to_inaccessible_base, 2963 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2964 BasePath, IgnoreAccess); 2965 } 2966 2967 2968 /// Builds a string representing ambiguous paths from a 2969 /// specific derived class to different subobjects of the same base 2970 /// class. 2971 /// 2972 /// This function builds a string that can be used in error messages 2973 /// to show the different paths that one can take through the 2974 /// inheritance hierarchy to go from the derived class to different 2975 /// subobjects of a base class. The result looks something like this: 2976 /// @code 2977 /// struct D -> struct B -> struct A 2978 /// struct D -> struct C -> struct A 2979 /// @endcode 2980 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2981 std::string PathDisplayStr; 2982 std::set<unsigned> DisplayedPaths; 2983 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2984 Path != Paths.end(); ++Path) { 2985 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2986 // We haven't displayed a path to this particular base 2987 // class subobject yet. 2988 PathDisplayStr += "\n "; 2989 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2990 for (CXXBasePath::const_iterator Element = Path->begin(); 2991 Element != Path->end(); ++Element) 2992 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2993 } 2994 } 2995 2996 return PathDisplayStr; 2997 } 2998 2999 //===----------------------------------------------------------------------===// 3000 // C++ class member Handling 3001 //===----------------------------------------------------------------------===// 3002 3003 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 3004 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 3005 SourceLocation ColonLoc, 3006 const ParsedAttributesView &Attrs) { 3007 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 3008 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 3009 ASLoc, ColonLoc); 3010 CurContext->addHiddenDecl(ASDecl); 3011 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 3012 } 3013 3014 /// CheckOverrideControl - Check C++11 override control semantics. 3015 void Sema::CheckOverrideControl(NamedDecl *D) { 3016 if (D->isInvalidDecl()) 3017 return; 3018 3019 // We only care about "override" and "final" declarations. 3020 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 3021 return; 3022 3023 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3024 3025 // We can't check dependent instance methods. 3026 if (MD && MD->isInstance() && 3027 (MD->getParent()->hasAnyDependentBases() || 3028 MD->getType()->isDependentType())) 3029 return; 3030 3031 if (MD && !MD->isVirtual()) { 3032 // If we have a non-virtual method, check if if hides a virtual method. 3033 // (In that case, it's most likely the method has the wrong type.) 3034 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 3035 FindHiddenVirtualMethods(MD, OverloadedMethods); 3036 3037 if (!OverloadedMethods.empty()) { 3038 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3039 Diag(OA->getLocation(), 3040 diag::override_keyword_hides_virtual_member_function) 3041 << "override" << (OverloadedMethods.size() > 1); 3042 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3043 Diag(FA->getLocation(), 3044 diag::override_keyword_hides_virtual_member_function) 3045 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3046 << (OverloadedMethods.size() > 1); 3047 } 3048 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3049 MD->setInvalidDecl(); 3050 return; 3051 } 3052 // Fall through into the general case diagnostic. 3053 // FIXME: We might want to attempt typo correction here. 3054 } 3055 3056 if (!MD || !MD->isVirtual()) { 3057 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3058 Diag(OA->getLocation(), 3059 diag::override_keyword_only_allowed_on_virtual_member_functions) 3060 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3061 D->dropAttr<OverrideAttr>(); 3062 } 3063 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3064 Diag(FA->getLocation(), 3065 diag::override_keyword_only_allowed_on_virtual_member_functions) 3066 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3067 << FixItHint::CreateRemoval(FA->getLocation()); 3068 D->dropAttr<FinalAttr>(); 3069 } 3070 return; 3071 } 3072 3073 // C++11 [class.virtual]p5: 3074 // If a function is marked with the virt-specifier override and 3075 // does not override a member function of a base class, the program is 3076 // ill-formed. 3077 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3078 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3079 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3080 << MD->getDeclName(); 3081 } 3082 3083 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { 3084 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3085 return; 3086 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3087 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3088 return; 3089 3090 SourceLocation Loc = MD->getLocation(); 3091 SourceLocation SpellingLoc = Loc; 3092 if (getSourceManager().isMacroArgExpansion(Loc)) 3093 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3094 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3095 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3096 return; 3097 3098 if (MD->size_overridden_methods() > 0) { 3099 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { 3100 unsigned DiagID = 3101 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation()) 3102 ? DiagInconsistent 3103 : DiagSuggest; 3104 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3105 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3106 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3107 }; 3108 if (isa<CXXDestructorDecl>(MD)) 3109 EmitDiag( 3110 diag::warn_inconsistent_destructor_marked_not_override_overriding, 3111 diag::warn_suggest_destructor_marked_not_override_overriding); 3112 else 3113 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding, 3114 diag::warn_suggest_function_marked_not_override_overriding); 3115 } 3116 } 3117 3118 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3119 /// function overrides a virtual member function marked 'final', according to 3120 /// C++11 [class.virtual]p4. 3121 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3122 const CXXMethodDecl *Old) { 3123 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3124 if (!FA) 3125 return false; 3126 3127 Diag(New->getLocation(), diag::err_final_function_overridden) 3128 << New->getDeclName() 3129 << FA->isSpelledAsSealed(); 3130 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3131 return true; 3132 } 3133 3134 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3135 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3136 // FIXME: Destruction of ObjC lifetime types has side-effects. 3137 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3138 return !RD->isCompleteDefinition() || 3139 !RD->hasTrivialDefaultConstructor() || 3140 !RD->hasTrivialDestructor(); 3141 return false; 3142 } 3143 3144 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3145 ParsedAttributesView::const_iterator Itr = 3146 llvm::find_if(list, [](const ParsedAttr &AL) { 3147 return AL.isDeclspecPropertyAttribute(); 3148 }); 3149 if (Itr != list.end()) 3150 return &*Itr; 3151 return nullptr; 3152 } 3153 3154 // Check if there is a field shadowing. 3155 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3156 DeclarationName FieldName, 3157 const CXXRecordDecl *RD, 3158 bool DeclIsField) { 3159 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3160 return; 3161 3162 // To record a shadowed field in a base 3163 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3164 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3165 CXXBasePath &Path) { 3166 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3167 // Record an ambiguous path directly 3168 if (Bases.find(Base) != Bases.end()) 3169 return true; 3170 for (const auto Field : Base->lookup(FieldName)) { 3171 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3172 Field->getAccess() != AS_private) { 3173 assert(Field->getAccess() != AS_none); 3174 assert(Bases.find(Base) == Bases.end()); 3175 Bases[Base] = Field; 3176 return true; 3177 } 3178 } 3179 return false; 3180 }; 3181 3182 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3183 /*DetectVirtual=*/true); 3184 if (!RD->lookupInBases(FieldShadowed, Paths)) 3185 return; 3186 3187 for (const auto &P : Paths) { 3188 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3189 auto It = Bases.find(Base); 3190 // Skip duplicated bases 3191 if (It == Bases.end()) 3192 continue; 3193 auto BaseField = It->second; 3194 assert(BaseField->getAccess() != AS_private); 3195 if (AS_none != 3196 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3197 Diag(Loc, diag::warn_shadow_field) 3198 << FieldName << RD << Base << DeclIsField; 3199 Diag(BaseField->getLocation(), diag::note_shadow_field); 3200 Bases.erase(It); 3201 } 3202 } 3203 } 3204 3205 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3206 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3207 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3208 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3209 /// present (but parsing it has been deferred). 3210 NamedDecl * 3211 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3212 MultiTemplateParamsArg TemplateParameterLists, 3213 Expr *BW, const VirtSpecifiers &VS, 3214 InClassInitStyle InitStyle) { 3215 const DeclSpec &DS = D.getDeclSpec(); 3216 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3217 DeclarationName Name = NameInfo.getName(); 3218 SourceLocation Loc = NameInfo.getLoc(); 3219 3220 // For anonymous bitfields, the location should point to the type. 3221 if (Loc.isInvalid()) 3222 Loc = D.getBeginLoc(); 3223 3224 Expr *BitWidth = static_cast<Expr*>(BW); 3225 3226 assert(isa<CXXRecordDecl>(CurContext)); 3227 assert(!DS.isFriendSpecified()); 3228 3229 bool isFunc = D.isDeclarationOfFunction(); 3230 const ParsedAttr *MSPropertyAttr = 3231 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3232 3233 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3234 // The Microsoft extension __interface only permits public member functions 3235 // and prohibits constructors, destructors, operators, non-public member 3236 // functions, static methods and data members. 3237 unsigned InvalidDecl; 3238 bool ShowDeclName = true; 3239 if (!isFunc && 3240 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3241 InvalidDecl = 0; 3242 else if (!isFunc) 3243 InvalidDecl = 1; 3244 else if (AS != AS_public) 3245 InvalidDecl = 2; 3246 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3247 InvalidDecl = 3; 3248 else switch (Name.getNameKind()) { 3249 case DeclarationName::CXXConstructorName: 3250 InvalidDecl = 4; 3251 ShowDeclName = false; 3252 break; 3253 3254 case DeclarationName::CXXDestructorName: 3255 InvalidDecl = 5; 3256 ShowDeclName = false; 3257 break; 3258 3259 case DeclarationName::CXXOperatorName: 3260 case DeclarationName::CXXConversionFunctionName: 3261 InvalidDecl = 6; 3262 break; 3263 3264 default: 3265 InvalidDecl = 0; 3266 break; 3267 } 3268 3269 if (InvalidDecl) { 3270 if (ShowDeclName) 3271 Diag(Loc, diag::err_invalid_member_in_interface) 3272 << (InvalidDecl-1) << Name; 3273 else 3274 Diag(Loc, diag::err_invalid_member_in_interface) 3275 << (InvalidDecl-1) << ""; 3276 return nullptr; 3277 } 3278 } 3279 3280 // C++ 9.2p6: A member shall not be declared to have automatic storage 3281 // duration (auto, register) or with the extern storage-class-specifier. 3282 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3283 // data members and cannot be applied to names declared const or static, 3284 // and cannot be applied to reference members. 3285 switch (DS.getStorageClassSpec()) { 3286 case DeclSpec::SCS_unspecified: 3287 case DeclSpec::SCS_typedef: 3288 case DeclSpec::SCS_static: 3289 break; 3290 case DeclSpec::SCS_mutable: 3291 if (isFunc) { 3292 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3293 3294 // FIXME: It would be nicer if the keyword was ignored only for this 3295 // declarator. Otherwise we could get follow-up errors. 3296 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3297 } 3298 break; 3299 default: 3300 Diag(DS.getStorageClassSpecLoc(), 3301 diag::err_storageclass_invalid_for_member); 3302 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3303 break; 3304 } 3305 3306 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3307 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3308 !isFunc); 3309 3310 if (DS.hasConstexprSpecifier() && isInstField) { 3311 SemaDiagnosticBuilder B = 3312 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3313 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3314 if (InitStyle == ICIS_NoInit) { 3315 B << 0 << 0; 3316 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3317 B << FixItHint::CreateRemoval(ConstexprLoc); 3318 else { 3319 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3320 D.getMutableDeclSpec().ClearConstexprSpec(); 3321 const char *PrevSpec; 3322 unsigned DiagID; 3323 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3324 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3325 (void)Failed; 3326 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3327 } 3328 } else { 3329 B << 1; 3330 const char *PrevSpec; 3331 unsigned DiagID; 3332 if (D.getMutableDeclSpec().SetStorageClassSpec( 3333 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3334 Context.getPrintingPolicy())) { 3335 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3336 "This is the only DeclSpec that should fail to be applied"); 3337 B << 1; 3338 } else { 3339 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3340 isInstField = false; 3341 } 3342 } 3343 } 3344 3345 NamedDecl *Member; 3346 if (isInstField) { 3347 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3348 3349 // Data members must have identifiers for names. 3350 if (!Name.isIdentifier()) { 3351 Diag(Loc, diag::err_bad_variable_name) 3352 << Name; 3353 return nullptr; 3354 } 3355 3356 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3357 3358 // Member field could not be with "template" keyword. 3359 // So TemplateParameterLists should be empty in this case. 3360 if (TemplateParameterLists.size()) { 3361 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3362 if (TemplateParams->size()) { 3363 // There is no such thing as a member field template. 3364 Diag(D.getIdentifierLoc(), diag::err_template_member) 3365 << II 3366 << SourceRange(TemplateParams->getTemplateLoc(), 3367 TemplateParams->getRAngleLoc()); 3368 } else { 3369 // There is an extraneous 'template<>' for this member. 3370 Diag(TemplateParams->getTemplateLoc(), 3371 diag::err_template_member_noparams) 3372 << II 3373 << SourceRange(TemplateParams->getTemplateLoc(), 3374 TemplateParams->getRAngleLoc()); 3375 } 3376 return nullptr; 3377 } 3378 3379 if (SS.isSet() && !SS.isInvalid()) { 3380 // The user provided a superfluous scope specifier inside a class 3381 // definition: 3382 // 3383 // class X { 3384 // int X::member; 3385 // }; 3386 if (DeclContext *DC = computeDeclContext(SS, false)) 3387 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3388 D.getName().getKind() == 3389 UnqualifiedIdKind::IK_TemplateId); 3390 else 3391 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3392 << Name << SS.getRange(); 3393 3394 SS.clear(); 3395 } 3396 3397 if (MSPropertyAttr) { 3398 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3399 BitWidth, InitStyle, AS, *MSPropertyAttr); 3400 if (!Member) 3401 return nullptr; 3402 isInstField = false; 3403 } else { 3404 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3405 BitWidth, InitStyle, AS); 3406 if (!Member) 3407 return nullptr; 3408 } 3409 3410 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3411 } else { 3412 Member = HandleDeclarator(S, D, TemplateParameterLists); 3413 if (!Member) 3414 return nullptr; 3415 3416 // Non-instance-fields can't have a bitfield. 3417 if (BitWidth) { 3418 if (Member->isInvalidDecl()) { 3419 // don't emit another diagnostic. 3420 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3421 // C++ 9.6p3: A bit-field shall not be a static member. 3422 // "static member 'A' cannot be a bit-field" 3423 Diag(Loc, diag::err_static_not_bitfield) 3424 << Name << BitWidth->getSourceRange(); 3425 } else if (isa<TypedefDecl>(Member)) { 3426 // "typedef member 'x' cannot be a bit-field" 3427 Diag(Loc, diag::err_typedef_not_bitfield) 3428 << Name << BitWidth->getSourceRange(); 3429 } else { 3430 // A function typedef ("typedef int f(); f a;"). 3431 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3432 Diag(Loc, diag::err_not_integral_type_bitfield) 3433 << Name << cast<ValueDecl>(Member)->getType() 3434 << BitWidth->getSourceRange(); 3435 } 3436 3437 BitWidth = nullptr; 3438 Member->setInvalidDecl(); 3439 } 3440 3441 NamedDecl *NonTemplateMember = Member; 3442 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3443 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3444 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3445 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3446 3447 Member->setAccess(AS); 3448 3449 // If we have declared a member function template or static data member 3450 // template, set the access of the templated declaration as well. 3451 if (NonTemplateMember != Member) 3452 NonTemplateMember->setAccess(AS); 3453 3454 // C++ [temp.deduct.guide]p3: 3455 // A deduction guide [...] for a member class template [shall be 3456 // declared] with the same access [as the template]. 3457 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3458 auto *TD = DG->getDeducedTemplate(); 3459 // Access specifiers are only meaningful if both the template and the 3460 // deduction guide are from the same scope. 3461 if (AS != TD->getAccess() && 3462 TD->getDeclContext()->getRedeclContext()->Equals( 3463 DG->getDeclContext()->getRedeclContext())) { 3464 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3465 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3466 << TD->getAccess(); 3467 const AccessSpecDecl *LastAccessSpec = nullptr; 3468 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3469 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3470 LastAccessSpec = AccessSpec; 3471 } 3472 assert(LastAccessSpec && "differing access with no access specifier"); 3473 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3474 << AS; 3475 } 3476 } 3477 } 3478 3479 if (VS.isOverrideSpecified()) 3480 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3481 AttributeCommonInfo::AS_Keyword)); 3482 if (VS.isFinalSpecified()) 3483 Member->addAttr(FinalAttr::Create( 3484 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3485 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3486 3487 if (VS.getLastLocation().isValid()) { 3488 // Update the end location of a method that has a virt-specifiers. 3489 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3490 MD->setRangeEnd(VS.getLastLocation()); 3491 } 3492 3493 CheckOverrideControl(Member); 3494 3495 assert((Name || isInstField) && "No identifier for non-field ?"); 3496 3497 if (isInstField) { 3498 FieldDecl *FD = cast<FieldDecl>(Member); 3499 FieldCollector->Add(FD); 3500 3501 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3502 // Remember all explicit private FieldDecls that have a name, no side 3503 // effects and are not part of a dependent type declaration. 3504 if (!FD->isImplicit() && FD->getDeclName() && 3505 FD->getAccess() == AS_private && 3506 !FD->hasAttr<UnusedAttr>() && 3507 !FD->getParent()->isDependentContext() && 3508 !InitializationHasSideEffects(*FD)) 3509 UnusedPrivateFields.insert(FD); 3510 } 3511 } 3512 3513 return Member; 3514 } 3515 3516 namespace { 3517 class UninitializedFieldVisitor 3518 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3519 Sema &S; 3520 // List of Decls to generate a warning on. Also remove Decls that become 3521 // initialized. 3522 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3523 // List of base classes of the record. Classes are removed after their 3524 // initializers. 3525 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3526 // Vector of decls to be removed from the Decl set prior to visiting the 3527 // nodes. These Decls may have been initialized in the prior initializer. 3528 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3529 // If non-null, add a note to the warning pointing back to the constructor. 3530 const CXXConstructorDecl *Constructor; 3531 // Variables to hold state when processing an initializer list. When 3532 // InitList is true, special case initialization of FieldDecls matching 3533 // InitListFieldDecl. 3534 bool InitList; 3535 FieldDecl *InitListFieldDecl; 3536 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3537 3538 public: 3539 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3540 UninitializedFieldVisitor(Sema &S, 3541 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3542 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3543 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3544 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3545 3546 // Returns true if the use of ME is not an uninitialized use. 3547 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3548 bool CheckReferenceOnly) { 3549 llvm::SmallVector<FieldDecl*, 4> Fields; 3550 bool ReferenceField = false; 3551 while (ME) { 3552 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3553 if (!FD) 3554 return false; 3555 Fields.push_back(FD); 3556 if (FD->getType()->isReferenceType()) 3557 ReferenceField = true; 3558 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3559 } 3560 3561 // Binding a reference to an uninitialized field is not an 3562 // uninitialized use. 3563 if (CheckReferenceOnly && !ReferenceField) 3564 return true; 3565 3566 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3567 // Discard the first field since it is the field decl that is being 3568 // initialized. 3569 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3570 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3571 } 3572 3573 for (auto UsedIter = UsedFieldIndex.begin(), 3574 UsedEnd = UsedFieldIndex.end(), 3575 OrigIter = InitFieldIndex.begin(), 3576 OrigEnd = InitFieldIndex.end(); 3577 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3578 if (*UsedIter < *OrigIter) 3579 return true; 3580 if (*UsedIter > *OrigIter) 3581 break; 3582 } 3583 3584 return false; 3585 } 3586 3587 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3588 bool AddressOf) { 3589 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3590 return; 3591 3592 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3593 // or union. 3594 MemberExpr *FieldME = ME; 3595 3596 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3597 3598 Expr *Base = ME; 3599 while (MemberExpr *SubME = 3600 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3601 3602 if (isa<VarDecl>(SubME->getMemberDecl())) 3603 return; 3604 3605 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3606 if (!FD->isAnonymousStructOrUnion()) 3607 FieldME = SubME; 3608 3609 if (!FieldME->getType().isPODType(S.Context)) 3610 AllPODFields = false; 3611 3612 Base = SubME->getBase(); 3613 } 3614 3615 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) { 3616 Visit(Base); 3617 return; 3618 } 3619 3620 if (AddressOf && AllPODFields) 3621 return; 3622 3623 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3624 3625 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3626 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3627 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3628 } 3629 3630 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3631 QualType T = BaseCast->getType(); 3632 if (T->isPointerType() && 3633 BaseClasses.count(T->getPointeeType())) { 3634 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3635 << T->getPointeeType() << FoundVD; 3636 } 3637 } 3638 } 3639 3640 if (!Decls.count(FoundVD)) 3641 return; 3642 3643 const bool IsReference = FoundVD->getType()->isReferenceType(); 3644 3645 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3646 // Special checking for initializer lists. 3647 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3648 return; 3649 } 3650 } else { 3651 // Prevent double warnings on use of unbounded references. 3652 if (CheckReferenceOnly && !IsReference) 3653 return; 3654 } 3655 3656 unsigned diag = IsReference 3657 ? diag::warn_reference_field_is_uninit 3658 : diag::warn_field_is_uninit; 3659 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3660 if (Constructor) 3661 S.Diag(Constructor->getLocation(), 3662 diag::note_uninit_in_this_constructor) 3663 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3664 3665 } 3666 3667 void HandleValue(Expr *E, bool AddressOf) { 3668 E = E->IgnoreParens(); 3669 3670 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3671 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3672 AddressOf /*AddressOf*/); 3673 return; 3674 } 3675 3676 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3677 Visit(CO->getCond()); 3678 HandleValue(CO->getTrueExpr(), AddressOf); 3679 HandleValue(CO->getFalseExpr(), AddressOf); 3680 return; 3681 } 3682 3683 if (BinaryConditionalOperator *BCO = 3684 dyn_cast<BinaryConditionalOperator>(E)) { 3685 Visit(BCO->getCond()); 3686 HandleValue(BCO->getFalseExpr(), AddressOf); 3687 return; 3688 } 3689 3690 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3691 HandleValue(OVE->getSourceExpr(), AddressOf); 3692 return; 3693 } 3694 3695 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3696 switch (BO->getOpcode()) { 3697 default: 3698 break; 3699 case(BO_PtrMemD): 3700 case(BO_PtrMemI): 3701 HandleValue(BO->getLHS(), AddressOf); 3702 Visit(BO->getRHS()); 3703 return; 3704 case(BO_Comma): 3705 Visit(BO->getLHS()); 3706 HandleValue(BO->getRHS(), AddressOf); 3707 return; 3708 } 3709 } 3710 3711 Visit(E); 3712 } 3713 3714 void CheckInitListExpr(InitListExpr *ILE) { 3715 InitFieldIndex.push_back(0); 3716 for (auto Child : ILE->children()) { 3717 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3718 CheckInitListExpr(SubList); 3719 } else { 3720 Visit(Child); 3721 } 3722 ++InitFieldIndex.back(); 3723 } 3724 InitFieldIndex.pop_back(); 3725 } 3726 3727 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3728 FieldDecl *Field, const Type *BaseClass) { 3729 // Remove Decls that may have been initialized in the previous 3730 // initializer. 3731 for (ValueDecl* VD : DeclsToRemove) 3732 Decls.erase(VD); 3733 DeclsToRemove.clear(); 3734 3735 Constructor = FieldConstructor; 3736 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3737 3738 if (ILE && Field) { 3739 InitList = true; 3740 InitListFieldDecl = Field; 3741 InitFieldIndex.clear(); 3742 CheckInitListExpr(ILE); 3743 } else { 3744 InitList = false; 3745 Visit(E); 3746 } 3747 3748 if (Field) 3749 Decls.erase(Field); 3750 if (BaseClass) 3751 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3752 } 3753 3754 void VisitMemberExpr(MemberExpr *ME) { 3755 // All uses of unbounded reference fields will warn. 3756 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3757 } 3758 3759 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3760 if (E->getCastKind() == CK_LValueToRValue) { 3761 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3762 return; 3763 } 3764 3765 Inherited::VisitImplicitCastExpr(E); 3766 } 3767 3768 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3769 if (E->getConstructor()->isCopyConstructor()) { 3770 Expr *ArgExpr = E->getArg(0); 3771 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3772 if (ILE->getNumInits() == 1) 3773 ArgExpr = ILE->getInit(0); 3774 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3775 if (ICE->getCastKind() == CK_NoOp) 3776 ArgExpr = ICE->getSubExpr(); 3777 HandleValue(ArgExpr, false /*AddressOf*/); 3778 return; 3779 } 3780 Inherited::VisitCXXConstructExpr(E); 3781 } 3782 3783 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3784 Expr *Callee = E->getCallee(); 3785 if (isa<MemberExpr>(Callee)) { 3786 HandleValue(Callee, false /*AddressOf*/); 3787 for (auto Arg : E->arguments()) 3788 Visit(Arg); 3789 return; 3790 } 3791 3792 Inherited::VisitCXXMemberCallExpr(E); 3793 } 3794 3795 void VisitCallExpr(CallExpr *E) { 3796 // Treat std::move as a use. 3797 if (E->isCallToStdMove()) { 3798 HandleValue(E->getArg(0), /*AddressOf=*/false); 3799 return; 3800 } 3801 3802 Inherited::VisitCallExpr(E); 3803 } 3804 3805 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3806 Expr *Callee = E->getCallee(); 3807 3808 if (isa<UnresolvedLookupExpr>(Callee)) 3809 return Inherited::VisitCXXOperatorCallExpr(E); 3810 3811 Visit(Callee); 3812 for (auto Arg : E->arguments()) 3813 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3814 } 3815 3816 void VisitBinaryOperator(BinaryOperator *E) { 3817 // If a field assignment is detected, remove the field from the 3818 // uninitiailized field set. 3819 if (E->getOpcode() == BO_Assign) 3820 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3821 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3822 if (!FD->getType()->isReferenceType()) 3823 DeclsToRemove.push_back(FD); 3824 3825 if (E->isCompoundAssignmentOp()) { 3826 HandleValue(E->getLHS(), false /*AddressOf*/); 3827 Visit(E->getRHS()); 3828 return; 3829 } 3830 3831 Inherited::VisitBinaryOperator(E); 3832 } 3833 3834 void VisitUnaryOperator(UnaryOperator *E) { 3835 if (E->isIncrementDecrementOp()) { 3836 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3837 return; 3838 } 3839 if (E->getOpcode() == UO_AddrOf) { 3840 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3841 HandleValue(ME->getBase(), true /*AddressOf*/); 3842 return; 3843 } 3844 } 3845 3846 Inherited::VisitUnaryOperator(E); 3847 } 3848 }; 3849 3850 // Diagnose value-uses of fields to initialize themselves, e.g. 3851 // foo(foo) 3852 // where foo is not also a parameter to the constructor. 3853 // Also diagnose across field uninitialized use such as 3854 // x(y), y(x) 3855 // TODO: implement -Wuninitialized and fold this into that framework. 3856 static void DiagnoseUninitializedFields( 3857 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3858 3859 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3860 Constructor->getLocation())) { 3861 return; 3862 } 3863 3864 if (Constructor->isInvalidDecl()) 3865 return; 3866 3867 const CXXRecordDecl *RD = Constructor->getParent(); 3868 3869 if (RD->isDependentContext()) 3870 return; 3871 3872 // Holds fields that are uninitialized. 3873 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3874 3875 // At the beginning, all fields are uninitialized. 3876 for (auto *I : RD->decls()) { 3877 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3878 UninitializedFields.insert(FD); 3879 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3880 UninitializedFields.insert(IFD->getAnonField()); 3881 } 3882 } 3883 3884 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3885 for (auto I : RD->bases()) 3886 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3887 3888 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3889 return; 3890 3891 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3892 UninitializedFields, 3893 UninitializedBaseClasses); 3894 3895 for (const auto *FieldInit : Constructor->inits()) { 3896 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3897 break; 3898 3899 Expr *InitExpr = FieldInit->getInit(); 3900 if (!InitExpr) 3901 continue; 3902 3903 if (CXXDefaultInitExpr *Default = 3904 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3905 InitExpr = Default->getExpr(); 3906 if (!InitExpr) 3907 continue; 3908 // In class initializers will point to the constructor. 3909 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3910 FieldInit->getAnyMember(), 3911 FieldInit->getBaseClass()); 3912 } else { 3913 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3914 FieldInit->getAnyMember(), 3915 FieldInit->getBaseClass()); 3916 } 3917 } 3918 } 3919 } // namespace 3920 3921 /// Enter a new C++ default initializer scope. After calling this, the 3922 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3923 /// parsing or instantiating the initializer failed. 3924 void Sema::ActOnStartCXXInClassMemberInitializer() { 3925 // Create a synthetic function scope to represent the call to the constructor 3926 // that notionally surrounds a use of this initializer. 3927 PushFunctionScope(); 3928 } 3929 3930 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 3931 if (!D.isFunctionDeclarator()) 3932 return; 3933 auto &FTI = D.getFunctionTypeInfo(); 3934 if (!FTI.Params) 3935 return; 3936 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 3937 FTI.NumParams)) { 3938 auto *ParamDecl = cast<NamedDecl>(Param.Param); 3939 if (ParamDecl->getDeclName()) 3940 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 3941 } 3942 } 3943 3944 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 3945 return ActOnRequiresClause(ConstraintExpr); 3946 } 3947 3948 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) { 3949 if (ConstraintExpr.isInvalid()) 3950 return ExprError(); 3951 3952 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr); 3953 if (ConstraintExpr.isInvalid()) 3954 return ExprError(); 3955 3956 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(), 3957 UPPC_RequiresClause)) 3958 return ExprError(); 3959 3960 return ConstraintExpr; 3961 } 3962 3963 /// This is invoked after parsing an in-class initializer for a 3964 /// non-static C++ class member, and after instantiating an in-class initializer 3965 /// in a class template. Such actions are deferred until the class is complete. 3966 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3967 SourceLocation InitLoc, 3968 Expr *InitExpr) { 3969 // Pop the notional constructor scope we created earlier. 3970 PopFunctionScopeInfo(nullptr, D); 3971 3972 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3973 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3974 "must set init style when field is created"); 3975 3976 if (!InitExpr) { 3977 D->setInvalidDecl(); 3978 if (FD) 3979 FD->removeInClassInitializer(); 3980 return; 3981 } 3982 3983 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3984 FD->setInvalidDecl(); 3985 FD->removeInClassInitializer(); 3986 return; 3987 } 3988 3989 ExprResult Init = InitExpr; 3990 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3991 InitializedEntity Entity = 3992 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3993 InitializationKind Kind = 3994 FD->getInClassInitStyle() == ICIS_ListInit 3995 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 3996 InitExpr->getBeginLoc(), 3997 InitExpr->getEndLoc()) 3998 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 3999 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 4000 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 4001 if (Init.isInvalid()) { 4002 FD->setInvalidDecl(); 4003 return; 4004 } 4005 } 4006 4007 // C++11 [class.base.init]p7: 4008 // The initialization of each base and member constitutes a 4009 // full-expression. 4010 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 4011 if (Init.isInvalid()) { 4012 FD->setInvalidDecl(); 4013 return; 4014 } 4015 4016 InitExpr = Init.get(); 4017 4018 FD->setInClassInitializer(InitExpr); 4019 } 4020 4021 /// Find the direct and/or virtual base specifiers that 4022 /// correspond to the given base type, for use in base initialization 4023 /// within a constructor. 4024 static bool FindBaseInitializer(Sema &SemaRef, 4025 CXXRecordDecl *ClassDecl, 4026 QualType BaseType, 4027 const CXXBaseSpecifier *&DirectBaseSpec, 4028 const CXXBaseSpecifier *&VirtualBaseSpec) { 4029 // First, check for a direct base class. 4030 DirectBaseSpec = nullptr; 4031 for (const auto &Base : ClassDecl->bases()) { 4032 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 4033 // We found a direct base of this type. That's what we're 4034 // initializing. 4035 DirectBaseSpec = &Base; 4036 break; 4037 } 4038 } 4039 4040 // Check for a virtual base class. 4041 // FIXME: We might be able to short-circuit this if we know in advance that 4042 // there are no virtual bases. 4043 VirtualBaseSpec = nullptr; 4044 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 4045 // We haven't found a base yet; search the class hierarchy for a 4046 // virtual base class. 4047 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 4048 /*DetectVirtual=*/false); 4049 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 4050 SemaRef.Context.getTypeDeclType(ClassDecl), 4051 BaseType, Paths)) { 4052 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 4053 Path != Paths.end(); ++Path) { 4054 if (Path->back().Base->isVirtual()) { 4055 VirtualBaseSpec = Path->back().Base; 4056 break; 4057 } 4058 } 4059 } 4060 } 4061 4062 return DirectBaseSpec || VirtualBaseSpec; 4063 } 4064 4065 /// Handle a C++ member initializer using braced-init-list syntax. 4066 MemInitResult 4067 Sema::ActOnMemInitializer(Decl *ConstructorD, 4068 Scope *S, 4069 CXXScopeSpec &SS, 4070 IdentifierInfo *MemberOrBase, 4071 ParsedType TemplateTypeTy, 4072 const DeclSpec &DS, 4073 SourceLocation IdLoc, 4074 Expr *InitList, 4075 SourceLocation EllipsisLoc) { 4076 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4077 DS, IdLoc, InitList, 4078 EllipsisLoc); 4079 } 4080 4081 /// Handle a C++ member initializer using parentheses syntax. 4082 MemInitResult 4083 Sema::ActOnMemInitializer(Decl *ConstructorD, 4084 Scope *S, 4085 CXXScopeSpec &SS, 4086 IdentifierInfo *MemberOrBase, 4087 ParsedType TemplateTypeTy, 4088 const DeclSpec &DS, 4089 SourceLocation IdLoc, 4090 SourceLocation LParenLoc, 4091 ArrayRef<Expr *> Args, 4092 SourceLocation RParenLoc, 4093 SourceLocation EllipsisLoc) { 4094 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4095 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4096 DS, IdLoc, List, EllipsisLoc); 4097 } 4098 4099 namespace { 4100 4101 // Callback to only accept typo corrections that can be a valid C++ member 4102 // intializer: either a non-static field member or a base class. 4103 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4104 public: 4105 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4106 : ClassDecl(ClassDecl) {} 4107 4108 bool ValidateCandidate(const TypoCorrection &candidate) override { 4109 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4110 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4111 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4112 return isa<TypeDecl>(ND); 4113 } 4114 return false; 4115 } 4116 4117 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4118 return std::make_unique<MemInitializerValidatorCCC>(*this); 4119 } 4120 4121 private: 4122 CXXRecordDecl *ClassDecl; 4123 }; 4124 4125 } 4126 4127 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4128 CXXScopeSpec &SS, 4129 ParsedType TemplateTypeTy, 4130 IdentifierInfo *MemberOrBase) { 4131 if (SS.getScopeRep() || TemplateTypeTy) 4132 return nullptr; 4133 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 4134 if (Result.empty()) 4135 return nullptr; 4136 ValueDecl *Member; 4137 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 4138 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) 4139 return Member; 4140 return nullptr; 4141 } 4142 4143 /// Handle a C++ member initializer. 4144 MemInitResult 4145 Sema::BuildMemInitializer(Decl *ConstructorD, 4146 Scope *S, 4147 CXXScopeSpec &SS, 4148 IdentifierInfo *MemberOrBase, 4149 ParsedType TemplateTypeTy, 4150 const DeclSpec &DS, 4151 SourceLocation IdLoc, 4152 Expr *Init, 4153 SourceLocation EllipsisLoc) { 4154 ExprResult Res = CorrectDelayedTyposInExpr(Init); 4155 if (!Res.isUsable()) 4156 return true; 4157 Init = Res.get(); 4158 4159 if (!ConstructorD) 4160 return true; 4161 4162 AdjustDeclIfTemplate(ConstructorD); 4163 4164 CXXConstructorDecl *Constructor 4165 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4166 if (!Constructor) { 4167 // The user wrote a constructor initializer on a function that is 4168 // not a C++ constructor. Ignore the error for now, because we may 4169 // have more member initializers coming; we'll diagnose it just 4170 // once in ActOnMemInitializers. 4171 return true; 4172 } 4173 4174 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4175 4176 // C++ [class.base.init]p2: 4177 // Names in a mem-initializer-id are looked up in the scope of the 4178 // constructor's class and, if not found in that scope, are looked 4179 // up in the scope containing the constructor's definition. 4180 // [Note: if the constructor's class contains a member with the 4181 // same name as a direct or virtual base class of the class, a 4182 // mem-initializer-id naming the member or base class and composed 4183 // of a single identifier refers to the class member. A 4184 // mem-initializer-id for the hidden base class may be specified 4185 // using a qualified name. ] 4186 4187 // Look for a member, first. 4188 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4189 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4190 if (EllipsisLoc.isValid()) 4191 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4192 << MemberOrBase 4193 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4194 4195 return BuildMemberInitializer(Member, Init, IdLoc); 4196 } 4197 // It didn't name a member, so see if it names a class. 4198 QualType BaseType; 4199 TypeSourceInfo *TInfo = nullptr; 4200 4201 if (TemplateTypeTy) { 4202 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4203 if (BaseType.isNull()) 4204 return true; 4205 } else if (DS.getTypeSpecType() == TST_decltype) { 4206 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4207 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4208 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4209 return true; 4210 } else { 4211 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4212 LookupParsedName(R, S, &SS); 4213 4214 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4215 if (!TyD) { 4216 if (R.isAmbiguous()) return true; 4217 4218 // We don't want access-control diagnostics here. 4219 R.suppressDiagnostics(); 4220 4221 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4222 bool NotUnknownSpecialization = false; 4223 DeclContext *DC = computeDeclContext(SS, false); 4224 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4225 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4226 4227 if (!NotUnknownSpecialization) { 4228 // When the scope specifier can refer to a member of an unknown 4229 // specialization, we take it as a type name. 4230 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4231 SS.getWithLocInContext(Context), 4232 *MemberOrBase, IdLoc); 4233 if (BaseType.isNull()) 4234 return true; 4235 4236 TInfo = Context.CreateTypeSourceInfo(BaseType); 4237 DependentNameTypeLoc TL = 4238 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4239 if (!TL.isNull()) { 4240 TL.setNameLoc(IdLoc); 4241 TL.setElaboratedKeywordLoc(SourceLocation()); 4242 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4243 } 4244 4245 R.clear(); 4246 R.setLookupName(MemberOrBase); 4247 } 4248 } 4249 4250 // If no results were found, try to correct typos. 4251 TypoCorrection Corr; 4252 MemInitializerValidatorCCC CCC(ClassDecl); 4253 if (R.empty() && BaseType.isNull() && 4254 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4255 CCC, CTK_ErrorRecovery, ClassDecl))) { 4256 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4257 // We have found a non-static data member with a similar 4258 // name to what was typed; complain and initialize that 4259 // member. 4260 diagnoseTypo(Corr, 4261 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4262 << MemberOrBase << true); 4263 return BuildMemberInitializer(Member, Init, IdLoc); 4264 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4265 const CXXBaseSpecifier *DirectBaseSpec; 4266 const CXXBaseSpecifier *VirtualBaseSpec; 4267 if (FindBaseInitializer(*this, ClassDecl, 4268 Context.getTypeDeclType(Type), 4269 DirectBaseSpec, VirtualBaseSpec)) { 4270 // We have found a direct or virtual base class with a 4271 // similar name to what was typed; complain and initialize 4272 // that base class. 4273 diagnoseTypo(Corr, 4274 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4275 << MemberOrBase << false, 4276 PDiag() /*Suppress note, we provide our own.*/); 4277 4278 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4279 : VirtualBaseSpec; 4280 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4281 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4282 4283 TyD = Type; 4284 } 4285 } 4286 } 4287 4288 if (!TyD && BaseType.isNull()) { 4289 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4290 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4291 return true; 4292 } 4293 } 4294 4295 if (BaseType.isNull()) { 4296 BaseType = Context.getTypeDeclType(TyD); 4297 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4298 if (SS.isSet()) { 4299 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4300 BaseType); 4301 TInfo = Context.CreateTypeSourceInfo(BaseType); 4302 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4303 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4304 TL.setElaboratedKeywordLoc(SourceLocation()); 4305 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4306 } 4307 } 4308 } 4309 4310 if (!TInfo) 4311 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4312 4313 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4314 } 4315 4316 MemInitResult 4317 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4318 SourceLocation IdLoc) { 4319 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4320 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4321 assert((DirectMember || IndirectMember) && 4322 "Member must be a FieldDecl or IndirectFieldDecl"); 4323 4324 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4325 return true; 4326 4327 if (Member->isInvalidDecl()) 4328 return true; 4329 4330 MultiExprArg Args; 4331 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4332 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4333 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4334 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4335 } else { 4336 // Template instantiation doesn't reconstruct ParenListExprs for us. 4337 Args = Init; 4338 } 4339 4340 SourceRange InitRange = Init->getSourceRange(); 4341 4342 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4343 // Can't check initialization for a member of dependent type or when 4344 // any of the arguments are type-dependent expressions. 4345 DiscardCleanupsInEvaluationContext(); 4346 } else { 4347 bool InitList = false; 4348 if (isa<InitListExpr>(Init)) { 4349 InitList = true; 4350 Args = Init; 4351 } 4352 4353 // Initialize the member. 4354 InitializedEntity MemberEntity = 4355 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4356 : InitializedEntity::InitializeMember(IndirectMember, 4357 nullptr); 4358 InitializationKind Kind = 4359 InitList ? InitializationKind::CreateDirectList( 4360 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4361 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4362 InitRange.getEnd()); 4363 4364 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4365 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4366 nullptr); 4367 if (MemberInit.isInvalid()) 4368 return true; 4369 4370 // C++11 [class.base.init]p7: 4371 // The initialization of each base and member constitutes a 4372 // full-expression. 4373 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4374 /*DiscardedValue*/ false); 4375 if (MemberInit.isInvalid()) 4376 return true; 4377 4378 Init = MemberInit.get(); 4379 } 4380 4381 if (DirectMember) { 4382 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4383 InitRange.getBegin(), Init, 4384 InitRange.getEnd()); 4385 } else { 4386 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4387 InitRange.getBegin(), Init, 4388 InitRange.getEnd()); 4389 } 4390 } 4391 4392 MemInitResult 4393 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4394 CXXRecordDecl *ClassDecl) { 4395 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4396 if (!LangOpts.CPlusPlus11) 4397 return Diag(NameLoc, diag::err_delegating_ctor) 4398 << TInfo->getTypeLoc().getLocalSourceRange(); 4399 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4400 4401 bool InitList = true; 4402 MultiExprArg Args = Init; 4403 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4404 InitList = false; 4405 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4406 } 4407 4408 SourceRange InitRange = Init->getSourceRange(); 4409 // Initialize the object. 4410 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4411 QualType(ClassDecl->getTypeForDecl(), 0)); 4412 InitializationKind Kind = 4413 InitList ? InitializationKind::CreateDirectList( 4414 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4415 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4416 InitRange.getEnd()); 4417 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4418 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4419 Args, nullptr); 4420 if (DelegationInit.isInvalid()) 4421 return true; 4422 4423 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4424 "Delegating constructor with no target?"); 4425 4426 // C++11 [class.base.init]p7: 4427 // The initialization of each base and member constitutes a 4428 // full-expression. 4429 DelegationInit = ActOnFinishFullExpr( 4430 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4431 if (DelegationInit.isInvalid()) 4432 return true; 4433 4434 // If we are in a dependent context, template instantiation will 4435 // perform this type-checking again. Just save the arguments that we 4436 // received in a ParenListExpr. 4437 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4438 // of the information that we have about the base 4439 // initializer. However, deconstructing the ASTs is a dicey process, 4440 // and this approach is far more likely to get the corner cases right. 4441 if (CurContext->isDependentContext()) 4442 DelegationInit = Init; 4443 4444 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4445 DelegationInit.getAs<Expr>(), 4446 InitRange.getEnd()); 4447 } 4448 4449 MemInitResult 4450 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4451 Expr *Init, CXXRecordDecl *ClassDecl, 4452 SourceLocation EllipsisLoc) { 4453 SourceLocation BaseLoc 4454 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4455 4456 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4457 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4458 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4459 4460 // C++ [class.base.init]p2: 4461 // [...] Unless the mem-initializer-id names a nonstatic data 4462 // member of the constructor's class or a direct or virtual base 4463 // of that class, the mem-initializer is ill-formed. A 4464 // mem-initializer-list can initialize a base class using any 4465 // name that denotes that base class type. 4466 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4467 4468 SourceRange InitRange = Init->getSourceRange(); 4469 if (EllipsisLoc.isValid()) { 4470 // This is a pack expansion. 4471 if (!BaseType->containsUnexpandedParameterPack()) { 4472 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4473 << SourceRange(BaseLoc, InitRange.getEnd()); 4474 4475 EllipsisLoc = SourceLocation(); 4476 } 4477 } else { 4478 // Check for any unexpanded parameter packs. 4479 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4480 return true; 4481 4482 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4483 return true; 4484 } 4485 4486 // Check for direct and virtual base classes. 4487 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4488 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4489 if (!Dependent) { 4490 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4491 BaseType)) 4492 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4493 4494 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4495 VirtualBaseSpec); 4496 4497 // C++ [base.class.init]p2: 4498 // Unless the mem-initializer-id names a nonstatic data member of the 4499 // constructor's class or a direct or virtual base of that class, the 4500 // mem-initializer is ill-formed. 4501 if (!DirectBaseSpec && !VirtualBaseSpec) { 4502 // If the class has any dependent bases, then it's possible that 4503 // one of those types will resolve to the same type as 4504 // BaseType. Therefore, just treat this as a dependent base 4505 // class initialization. FIXME: Should we try to check the 4506 // initialization anyway? It seems odd. 4507 if (ClassDecl->hasAnyDependentBases()) 4508 Dependent = true; 4509 else 4510 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4511 << BaseType << Context.getTypeDeclType(ClassDecl) 4512 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4513 } 4514 } 4515 4516 if (Dependent) { 4517 DiscardCleanupsInEvaluationContext(); 4518 4519 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4520 /*IsVirtual=*/false, 4521 InitRange.getBegin(), Init, 4522 InitRange.getEnd(), EllipsisLoc); 4523 } 4524 4525 // C++ [base.class.init]p2: 4526 // If a mem-initializer-id is ambiguous because it designates both 4527 // a direct non-virtual base class and an inherited virtual base 4528 // class, the mem-initializer is ill-formed. 4529 if (DirectBaseSpec && VirtualBaseSpec) 4530 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4531 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4532 4533 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4534 if (!BaseSpec) 4535 BaseSpec = VirtualBaseSpec; 4536 4537 // Initialize the base. 4538 bool InitList = true; 4539 MultiExprArg Args = Init; 4540 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4541 InitList = false; 4542 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4543 } 4544 4545 InitializedEntity BaseEntity = 4546 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4547 InitializationKind Kind = 4548 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4549 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4550 InitRange.getEnd()); 4551 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4552 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4553 if (BaseInit.isInvalid()) 4554 return true; 4555 4556 // C++11 [class.base.init]p7: 4557 // The initialization of each base and member constitutes a 4558 // full-expression. 4559 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4560 /*DiscardedValue*/ false); 4561 if (BaseInit.isInvalid()) 4562 return true; 4563 4564 // If we are in a dependent context, template instantiation will 4565 // perform this type-checking again. Just save the arguments that we 4566 // received in a ParenListExpr. 4567 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4568 // of the information that we have about the base 4569 // initializer. However, deconstructing the ASTs is a dicey process, 4570 // and this approach is far more likely to get the corner cases right. 4571 if (CurContext->isDependentContext()) 4572 BaseInit = Init; 4573 4574 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4575 BaseSpec->isVirtual(), 4576 InitRange.getBegin(), 4577 BaseInit.getAs<Expr>(), 4578 InitRange.getEnd(), EllipsisLoc); 4579 } 4580 4581 // Create a static_cast\<T&&>(expr). 4582 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4583 if (T.isNull()) T = E->getType(); 4584 QualType TargetType = SemaRef.BuildReferenceType( 4585 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4586 SourceLocation ExprLoc = E->getBeginLoc(); 4587 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4588 TargetType, ExprLoc); 4589 4590 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4591 SourceRange(ExprLoc, ExprLoc), 4592 E->getSourceRange()).get(); 4593 } 4594 4595 /// ImplicitInitializerKind - How an implicit base or member initializer should 4596 /// initialize its base or member. 4597 enum ImplicitInitializerKind { 4598 IIK_Default, 4599 IIK_Copy, 4600 IIK_Move, 4601 IIK_Inherit 4602 }; 4603 4604 static bool 4605 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4606 ImplicitInitializerKind ImplicitInitKind, 4607 CXXBaseSpecifier *BaseSpec, 4608 bool IsInheritedVirtualBase, 4609 CXXCtorInitializer *&CXXBaseInit) { 4610 InitializedEntity InitEntity 4611 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4612 IsInheritedVirtualBase); 4613 4614 ExprResult BaseInit; 4615 4616 switch (ImplicitInitKind) { 4617 case IIK_Inherit: 4618 case IIK_Default: { 4619 InitializationKind InitKind 4620 = InitializationKind::CreateDefault(Constructor->getLocation()); 4621 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4622 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4623 break; 4624 } 4625 4626 case IIK_Move: 4627 case IIK_Copy: { 4628 bool Moving = ImplicitInitKind == IIK_Move; 4629 ParmVarDecl *Param = Constructor->getParamDecl(0); 4630 QualType ParamType = Param->getType().getNonReferenceType(); 4631 4632 Expr *CopyCtorArg = 4633 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4634 SourceLocation(), Param, false, 4635 Constructor->getLocation(), ParamType, 4636 VK_LValue, nullptr); 4637 4638 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4639 4640 // Cast to the base class to avoid ambiguities. 4641 QualType ArgTy = 4642 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4643 ParamType.getQualifiers()); 4644 4645 if (Moving) { 4646 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4647 } 4648 4649 CXXCastPath BasePath; 4650 BasePath.push_back(BaseSpec); 4651 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4652 CK_UncheckedDerivedToBase, 4653 Moving ? VK_XValue : VK_LValue, 4654 &BasePath).get(); 4655 4656 InitializationKind InitKind 4657 = InitializationKind::CreateDirect(Constructor->getLocation(), 4658 SourceLocation(), SourceLocation()); 4659 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4660 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4661 break; 4662 } 4663 } 4664 4665 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4666 if (BaseInit.isInvalid()) 4667 return true; 4668 4669 CXXBaseInit = 4670 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4671 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4672 SourceLocation()), 4673 BaseSpec->isVirtual(), 4674 SourceLocation(), 4675 BaseInit.getAs<Expr>(), 4676 SourceLocation(), 4677 SourceLocation()); 4678 4679 return false; 4680 } 4681 4682 static bool RefersToRValueRef(Expr *MemRef) { 4683 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4684 return Referenced->getType()->isRValueReferenceType(); 4685 } 4686 4687 static bool 4688 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4689 ImplicitInitializerKind ImplicitInitKind, 4690 FieldDecl *Field, IndirectFieldDecl *Indirect, 4691 CXXCtorInitializer *&CXXMemberInit) { 4692 if (Field->isInvalidDecl()) 4693 return true; 4694 4695 SourceLocation Loc = Constructor->getLocation(); 4696 4697 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4698 bool Moving = ImplicitInitKind == IIK_Move; 4699 ParmVarDecl *Param = Constructor->getParamDecl(0); 4700 QualType ParamType = Param->getType().getNonReferenceType(); 4701 4702 // Suppress copying zero-width bitfields. 4703 if (Field->isZeroLengthBitField(SemaRef.Context)) 4704 return false; 4705 4706 Expr *MemberExprBase = 4707 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4708 SourceLocation(), Param, false, 4709 Loc, ParamType, VK_LValue, nullptr); 4710 4711 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4712 4713 if (Moving) { 4714 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4715 } 4716 4717 // Build a reference to this field within the parameter. 4718 CXXScopeSpec SS; 4719 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4720 Sema::LookupMemberName); 4721 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4722 : cast<ValueDecl>(Field), AS_public); 4723 MemberLookup.resolveKind(); 4724 ExprResult CtorArg 4725 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4726 ParamType, Loc, 4727 /*IsArrow=*/false, 4728 SS, 4729 /*TemplateKWLoc=*/SourceLocation(), 4730 /*FirstQualifierInScope=*/nullptr, 4731 MemberLookup, 4732 /*TemplateArgs=*/nullptr, 4733 /*S*/nullptr); 4734 if (CtorArg.isInvalid()) 4735 return true; 4736 4737 // C++11 [class.copy]p15: 4738 // - if a member m has rvalue reference type T&&, it is direct-initialized 4739 // with static_cast<T&&>(x.m); 4740 if (RefersToRValueRef(CtorArg.get())) { 4741 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4742 } 4743 4744 InitializedEntity Entity = 4745 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4746 /*Implicit*/ true) 4747 : InitializedEntity::InitializeMember(Field, nullptr, 4748 /*Implicit*/ true); 4749 4750 // Direct-initialize to use the copy constructor. 4751 InitializationKind InitKind = 4752 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4753 4754 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4755 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4756 ExprResult MemberInit = 4757 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4758 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4759 if (MemberInit.isInvalid()) 4760 return true; 4761 4762 if (Indirect) 4763 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4764 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4765 else 4766 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4767 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4768 return false; 4769 } 4770 4771 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4772 "Unhandled implicit init kind!"); 4773 4774 QualType FieldBaseElementType = 4775 SemaRef.Context.getBaseElementType(Field->getType()); 4776 4777 if (FieldBaseElementType->isRecordType()) { 4778 InitializedEntity InitEntity = 4779 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4780 /*Implicit*/ true) 4781 : InitializedEntity::InitializeMember(Field, nullptr, 4782 /*Implicit*/ true); 4783 InitializationKind InitKind = 4784 InitializationKind::CreateDefault(Loc); 4785 4786 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4787 ExprResult MemberInit = 4788 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4789 4790 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4791 if (MemberInit.isInvalid()) 4792 return true; 4793 4794 if (Indirect) 4795 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4796 Indirect, Loc, 4797 Loc, 4798 MemberInit.get(), 4799 Loc); 4800 else 4801 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4802 Field, Loc, Loc, 4803 MemberInit.get(), 4804 Loc); 4805 return false; 4806 } 4807 4808 if (!Field->getParent()->isUnion()) { 4809 if (FieldBaseElementType->isReferenceType()) { 4810 SemaRef.Diag(Constructor->getLocation(), 4811 diag::err_uninitialized_member_in_ctor) 4812 << (int)Constructor->isImplicit() 4813 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4814 << 0 << Field->getDeclName(); 4815 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4816 return true; 4817 } 4818 4819 if (FieldBaseElementType.isConstQualified()) { 4820 SemaRef.Diag(Constructor->getLocation(), 4821 diag::err_uninitialized_member_in_ctor) 4822 << (int)Constructor->isImplicit() 4823 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4824 << 1 << Field->getDeclName(); 4825 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4826 return true; 4827 } 4828 } 4829 4830 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4831 // ARC and Weak: 4832 // Default-initialize Objective-C pointers to NULL. 4833 CXXMemberInit 4834 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4835 Loc, Loc, 4836 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4837 Loc); 4838 return false; 4839 } 4840 4841 // Nothing to initialize. 4842 CXXMemberInit = nullptr; 4843 return false; 4844 } 4845 4846 namespace { 4847 struct BaseAndFieldInfo { 4848 Sema &S; 4849 CXXConstructorDecl *Ctor; 4850 bool AnyErrorsInInits; 4851 ImplicitInitializerKind IIK; 4852 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4853 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4854 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4855 4856 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4857 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4858 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4859 if (Ctor->getInheritedConstructor()) 4860 IIK = IIK_Inherit; 4861 else if (Generated && Ctor->isCopyConstructor()) 4862 IIK = IIK_Copy; 4863 else if (Generated && Ctor->isMoveConstructor()) 4864 IIK = IIK_Move; 4865 else 4866 IIK = IIK_Default; 4867 } 4868 4869 bool isImplicitCopyOrMove() const { 4870 switch (IIK) { 4871 case IIK_Copy: 4872 case IIK_Move: 4873 return true; 4874 4875 case IIK_Default: 4876 case IIK_Inherit: 4877 return false; 4878 } 4879 4880 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4881 } 4882 4883 bool addFieldInitializer(CXXCtorInitializer *Init) { 4884 AllToInit.push_back(Init); 4885 4886 // Check whether this initializer makes the field "used". 4887 if (Init->getInit()->HasSideEffects(S.Context)) 4888 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4889 4890 return false; 4891 } 4892 4893 bool isInactiveUnionMember(FieldDecl *Field) { 4894 RecordDecl *Record = Field->getParent(); 4895 if (!Record->isUnion()) 4896 return false; 4897 4898 if (FieldDecl *Active = 4899 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4900 return Active != Field->getCanonicalDecl(); 4901 4902 // In an implicit copy or move constructor, ignore any in-class initializer. 4903 if (isImplicitCopyOrMove()) 4904 return true; 4905 4906 // If there's no explicit initialization, the field is active only if it 4907 // has an in-class initializer... 4908 if (Field->hasInClassInitializer()) 4909 return false; 4910 // ... or it's an anonymous struct or union whose class has an in-class 4911 // initializer. 4912 if (!Field->isAnonymousStructOrUnion()) 4913 return true; 4914 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4915 return !FieldRD->hasInClassInitializer(); 4916 } 4917 4918 /// Determine whether the given field is, or is within, a union member 4919 /// that is inactive (because there was an initializer given for a different 4920 /// member of the union, or because the union was not initialized at all). 4921 bool isWithinInactiveUnionMember(FieldDecl *Field, 4922 IndirectFieldDecl *Indirect) { 4923 if (!Indirect) 4924 return isInactiveUnionMember(Field); 4925 4926 for (auto *C : Indirect->chain()) { 4927 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4928 if (Field && isInactiveUnionMember(Field)) 4929 return true; 4930 } 4931 return false; 4932 } 4933 }; 4934 } 4935 4936 /// Determine whether the given type is an incomplete or zero-lenfgth 4937 /// array type. 4938 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4939 if (T->isIncompleteArrayType()) 4940 return true; 4941 4942 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4943 if (!ArrayT->getSize()) 4944 return true; 4945 4946 T = ArrayT->getElementType(); 4947 } 4948 4949 return false; 4950 } 4951 4952 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4953 FieldDecl *Field, 4954 IndirectFieldDecl *Indirect = nullptr) { 4955 if (Field->isInvalidDecl()) 4956 return false; 4957 4958 // Overwhelmingly common case: we have a direct initializer for this field. 4959 if (CXXCtorInitializer *Init = 4960 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4961 return Info.addFieldInitializer(Init); 4962 4963 // C++11 [class.base.init]p8: 4964 // if the entity is a non-static data member that has a 4965 // brace-or-equal-initializer and either 4966 // -- the constructor's class is a union and no other variant member of that 4967 // union is designated by a mem-initializer-id or 4968 // -- the constructor's class is not a union, and, if the entity is a member 4969 // of an anonymous union, no other member of that union is designated by 4970 // a mem-initializer-id, 4971 // the entity is initialized as specified in [dcl.init]. 4972 // 4973 // We also apply the same rules to handle anonymous structs within anonymous 4974 // unions. 4975 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4976 return false; 4977 4978 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4979 ExprResult DIE = 4980 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4981 if (DIE.isInvalid()) 4982 return true; 4983 4984 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4985 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4986 4987 CXXCtorInitializer *Init; 4988 if (Indirect) 4989 Init = new (SemaRef.Context) 4990 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4991 SourceLocation(), DIE.get(), SourceLocation()); 4992 else 4993 Init = new (SemaRef.Context) 4994 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4995 SourceLocation(), DIE.get(), SourceLocation()); 4996 return Info.addFieldInitializer(Init); 4997 } 4998 4999 // Don't initialize incomplete or zero-length arrays. 5000 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 5001 return false; 5002 5003 // Don't try to build an implicit initializer if there were semantic 5004 // errors in any of the initializers (and therefore we might be 5005 // missing some that the user actually wrote). 5006 if (Info.AnyErrorsInInits) 5007 return false; 5008 5009 CXXCtorInitializer *Init = nullptr; 5010 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 5011 Indirect, Init)) 5012 return true; 5013 5014 if (!Init) 5015 return false; 5016 5017 return Info.addFieldInitializer(Init); 5018 } 5019 5020 bool 5021 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 5022 CXXCtorInitializer *Initializer) { 5023 assert(Initializer->isDelegatingInitializer()); 5024 Constructor->setNumCtorInitializers(1); 5025 CXXCtorInitializer **initializer = 5026 new (Context) CXXCtorInitializer*[1]; 5027 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 5028 Constructor->setCtorInitializers(initializer); 5029 5030 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 5031 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 5032 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 5033 } 5034 5035 DelegatingCtorDecls.push_back(Constructor); 5036 5037 DiagnoseUninitializedFields(*this, Constructor); 5038 5039 return false; 5040 } 5041 5042 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 5043 ArrayRef<CXXCtorInitializer *> Initializers) { 5044 if (Constructor->isDependentContext()) { 5045 // Just store the initializers as written, they will be checked during 5046 // instantiation. 5047 if (!Initializers.empty()) { 5048 Constructor->setNumCtorInitializers(Initializers.size()); 5049 CXXCtorInitializer **baseOrMemberInitializers = 5050 new (Context) CXXCtorInitializer*[Initializers.size()]; 5051 memcpy(baseOrMemberInitializers, Initializers.data(), 5052 Initializers.size() * sizeof(CXXCtorInitializer*)); 5053 Constructor->setCtorInitializers(baseOrMemberInitializers); 5054 } 5055 5056 // Let template instantiation know whether we had errors. 5057 if (AnyErrors) 5058 Constructor->setInvalidDecl(); 5059 5060 return false; 5061 } 5062 5063 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 5064 5065 // We need to build the initializer AST according to order of construction 5066 // and not what user specified in the Initializers list. 5067 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 5068 if (!ClassDecl) 5069 return true; 5070 5071 bool HadError = false; 5072 5073 for (unsigned i = 0; i < Initializers.size(); i++) { 5074 CXXCtorInitializer *Member = Initializers[i]; 5075 5076 if (Member->isBaseInitializer()) 5077 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5078 else { 5079 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5080 5081 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5082 for (auto *C : F->chain()) { 5083 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5084 if (FD && FD->getParent()->isUnion()) 5085 Info.ActiveUnionMember.insert(std::make_pair( 5086 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5087 } 5088 } else if (FieldDecl *FD = Member->getMember()) { 5089 if (FD->getParent()->isUnion()) 5090 Info.ActiveUnionMember.insert(std::make_pair( 5091 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5092 } 5093 } 5094 } 5095 5096 // Keep track of the direct virtual bases. 5097 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5098 for (auto &I : ClassDecl->bases()) { 5099 if (I.isVirtual()) 5100 DirectVBases.insert(&I); 5101 } 5102 5103 // Push virtual bases before others. 5104 for (auto &VBase : ClassDecl->vbases()) { 5105 if (CXXCtorInitializer *Value 5106 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5107 // [class.base.init]p7, per DR257: 5108 // A mem-initializer where the mem-initializer-id names a virtual base 5109 // class is ignored during execution of a constructor of any class that 5110 // is not the most derived class. 5111 if (ClassDecl->isAbstract()) { 5112 // FIXME: Provide a fixit to remove the base specifier. This requires 5113 // tracking the location of the associated comma for a base specifier. 5114 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5115 << VBase.getType() << ClassDecl; 5116 DiagnoseAbstractType(ClassDecl); 5117 } 5118 5119 Info.AllToInit.push_back(Value); 5120 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5121 // [class.base.init]p8, per DR257: 5122 // If a given [...] base class is not named by a mem-initializer-id 5123 // [...] and the entity is not a virtual base class of an abstract 5124 // class, then [...] the entity is default-initialized. 5125 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5126 CXXCtorInitializer *CXXBaseInit; 5127 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5128 &VBase, IsInheritedVirtualBase, 5129 CXXBaseInit)) { 5130 HadError = true; 5131 continue; 5132 } 5133 5134 Info.AllToInit.push_back(CXXBaseInit); 5135 } 5136 } 5137 5138 // Non-virtual bases. 5139 for (auto &Base : ClassDecl->bases()) { 5140 // Virtuals are in the virtual base list and already constructed. 5141 if (Base.isVirtual()) 5142 continue; 5143 5144 if (CXXCtorInitializer *Value 5145 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5146 Info.AllToInit.push_back(Value); 5147 } else if (!AnyErrors) { 5148 CXXCtorInitializer *CXXBaseInit; 5149 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5150 &Base, /*IsInheritedVirtualBase=*/false, 5151 CXXBaseInit)) { 5152 HadError = true; 5153 continue; 5154 } 5155 5156 Info.AllToInit.push_back(CXXBaseInit); 5157 } 5158 } 5159 5160 // Fields. 5161 for (auto *Mem : ClassDecl->decls()) { 5162 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5163 // C++ [class.bit]p2: 5164 // A declaration for a bit-field that omits the identifier declares an 5165 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5166 // initialized. 5167 if (F->isUnnamedBitfield()) 5168 continue; 5169 5170 // If we're not generating the implicit copy/move constructor, then we'll 5171 // handle anonymous struct/union fields based on their individual 5172 // indirect fields. 5173 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5174 continue; 5175 5176 if (CollectFieldInitializer(*this, Info, F)) 5177 HadError = true; 5178 continue; 5179 } 5180 5181 // Beyond this point, we only consider default initialization. 5182 if (Info.isImplicitCopyOrMove()) 5183 continue; 5184 5185 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5186 if (F->getType()->isIncompleteArrayType()) { 5187 assert(ClassDecl->hasFlexibleArrayMember() && 5188 "Incomplete array type is not valid"); 5189 continue; 5190 } 5191 5192 // Initialize each field of an anonymous struct individually. 5193 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5194 HadError = true; 5195 5196 continue; 5197 } 5198 } 5199 5200 unsigned NumInitializers = Info.AllToInit.size(); 5201 if (NumInitializers > 0) { 5202 Constructor->setNumCtorInitializers(NumInitializers); 5203 CXXCtorInitializer **baseOrMemberInitializers = 5204 new (Context) CXXCtorInitializer*[NumInitializers]; 5205 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5206 NumInitializers * sizeof(CXXCtorInitializer*)); 5207 Constructor->setCtorInitializers(baseOrMemberInitializers); 5208 5209 // Constructors implicitly reference the base and member 5210 // destructors. 5211 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5212 Constructor->getParent()); 5213 } 5214 5215 return HadError; 5216 } 5217 5218 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5219 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5220 const RecordDecl *RD = RT->getDecl(); 5221 if (RD->isAnonymousStructOrUnion()) { 5222 for (auto *Field : RD->fields()) 5223 PopulateKeysForFields(Field, IdealInits); 5224 return; 5225 } 5226 } 5227 IdealInits.push_back(Field->getCanonicalDecl()); 5228 } 5229 5230 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5231 return Context.getCanonicalType(BaseType).getTypePtr(); 5232 } 5233 5234 static const void *GetKeyForMember(ASTContext &Context, 5235 CXXCtorInitializer *Member) { 5236 if (!Member->isAnyMemberInitializer()) 5237 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5238 5239 return Member->getAnyMember()->getCanonicalDecl(); 5240 } 5241 5242 static void DiagnoseBaseOrMemInitializerOrder( 5243 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5244 ArrayRef<CXXCtorInitializer *> Inits) { 5245 if (Constructor->getDeclContext()->isDependentContext()) 5246 return; 5247 5248 // Don't check initializers order unless the warning is enabled at the 5249 // location of at least one initializer. 5250 bool ShouldCheckOrder = false; 5251 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5252 CXXCtorInitializer *Init = Inits[InitIndex]; 5253 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5254 Init->getSourceLocation())) { 5255 ShouldCheckOrder = true; 5256 break; 5257 } 5258 } 5259 if (!ShouldCheckOrder) 5260 return; 5261 5262 // Build the list of bases and members in the order that they'll 5263 // actually be initialized. The explicit initializers should be in 5264 // this same order but may be missing things. 5265 SmallVector<const void*, 32> IdealInitKeys; 5266 5267 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5268 5269 // 1. Virtual bases. 5270 for (const auto &VBase : ClassDecl->vbases()) 5271 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5272 5273 // 2. Non-virtual bases. 5274 for (const auto &Base : ClassDecl->bases()) { 5275 if (Base.isVirtual()) 5276 continue; 5277 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5278 } 5279 5280 // 3. Direct fields. 5281 for (auto *Field : ClassDecl->fields()) { 5282 if (Field->isUnnamedBitfield()) 5283 continue; 5284 5285 PopulateKeysForFields(Field, IdealInitKeys); 5286 } 5287 5288 unsigned NumIdealInits = IdealInitKeys.size(); 5289 unsigned IdealIndex = 0; 5290 5291 CXXCtorInitializer *PrevInit = nullptr; 5292 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5293 CXXCtorInitializer *Init = Inits[InitIndex]; 5294 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 5295 5296 // Scan forward to try to find this initializer in the idealized 5297 // initializers list. 5298 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5299 if (InitKey == IdealInitKeys[IdealIndex]) 5300 break; 5301 5302 // If we didn't find this initializer, it must be because we 5303 // scanned past it on a previous iteration. That can only 5304 // happen if we're out of order; emit a warning. 5305 if (IdealIndex == NumIdealInits && PrevInit) { 5306 Sema::SemaDiagnosticBuilder D = 5307 SemaRef.Diag(PrevInit->getSourceLocation(), 5308 diag::warn_initializer_out_of_order); 5309 5310 if (PrevInit->isAnyMemberInitializer()) 5311 D << 0 << PrevInit->getAnyMember()->getDeclName(); 5312 else 5313 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 5314 5315 if (Init->isAnyMemberInitializer()) 5316 D << 0 << Init->getAnyMember()->getDeclName(); 5317 else 5318 D << 1 << Init->getTypeSourceInfo()->getType(); 5319 5320 // Move back to the initializer's location in the ideal list. 5321 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5322 if (InitKey == IdealInitKeys[IdealIndex]) 5323 break; 5324 5325 assert(IdealIndex < NumIdealInits && 5326 "initializer not found in initializer list"); 5327 } 5328 5329 PrevInit = Init; 5330 } 5331 } 5332 5333 namespace { 5334 bool CheckRedundantInit(Sema &S, 5335 CXXCtorInitializer *Init, 5336 CXXCtorInitializer *&PrevInit) { 5337 if (!PrevInit) { 5338 PrevInit = Init; 5339 return false; 5340 } 5341 5342 if (FieldDecl *Field = Init->getAnyMember()) 5343 S.Diag(Init->getSourceLocation(), 5344 diag::err_multiple_mem_initialization) 5345 << Field->getDeclName() 5346 << Init->getSourceRange(); 5347 else { 5348 const Type *BaseClass = Init->getBaseClass(); 5349 assert(BaseClass && "neither field nor base"); 5350 S.Diag(Init->getSourceLocation(), 5351 diag::err_multiple_base_initialization) 5352 << QualType(BaseClass, 0) 5353 << Init->getSourceRange(); 5354 } 5355 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5356 << 0 << PrevInit->getSourceRange(); 5357 5358 return true; 5359 } 5360 5361 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5362 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5363 5364 bool CheckRedundantUnionInit(Sema &S, 5365 CXXCtorInitializer *Init, 5366 RedundantUnionMap &Unions) { 5367 FieldDecl *Field = Init->getAnyMember(); 5368 RecordDecl *Parent = Field->getParent(); 5369 NamedDecl *Child = Field; 5370 5371 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5372 if (Parent->isUnion()) { 5373 UnionEntry &En = Unions[Parent]; 5374 if (En.first && En.first != Child) { 5375 S.Diag(Init->getSourceLocation(), 5376 diag::err_multiple_mem_union_initialization) 5377 << Field->getDeclName() 5378 << Init->getSourceRange(); 5379 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5380 << 0 << En.second->getSourceRange(); 5381 return true; 5382 } 5383 if (!En.first) { 5384 En.first = Child; 5385 En.second = Init; 5386 } 5387 if (!Parent->isAnonymousStructOrUnion()) 5388 return false; 5389 } 5390 5391 Child = Parent; 5392 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5393 } 5394 5395 return false; 5396 } 5397 } 5398 5399 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5400 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5401 SourceLocation ColonLoc, 5402 ArrayRef<CXXCtorInitializer*> MemInits, 5403 bool AnyErrors) { 5404 if (!ConstructorDecl) 5405 return; 5406 5407 AdjustDeclIfTemplate(ConstructorDecl); 5408 5409 CXXConstructorDecl *Constructor 5410 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5411 5412 if (!Constructor) { 5413 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5414 return; 5415 } 5416 5417 // Mapping for the duplicate initializers check. 5418 // For member initializers, this is keyed with a FieldDecl*. 5419 // For base initializers, this is keyed with a Type*. 5420 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5421 5422 // Mapping for the inconsistent anonymous-union initializers check. 5423 RedundantUnionMap MemberUnions; 5424 5425 bool HadError = false; 5426 for (unsigned i = 0; i < MemInits.size(); i++) { 5427 CXXCtorInitializer *Init = MemInits[i]; 5428 5429 // Set the source order index. 5430 Init->setSourceOrder(i); 5431 5432 if (Init->isAnyMemberInitializer()) { 5433 const void *Key = GetKeyForMember(Context, Init); 5434 if (CheckRedundantInit(*this, Init, Members[Key]) || 5435 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5436 HadError = true; 5437 } else if (Init->isBaseInitializer()) { 5438 const void *Key = GetKeyForMember(Context, Init); 5439 if (CheckRedundantInit(*this, Init, Members[Key])) 5440 HadError = true; 5441 } else { 5442 assert(Init->isDelegatingInitializer()); 5443 // This must be the only initializer 5444 if (MemInits.size() != 1) { 5445 Diag(Init->getSourceLocation(), 5446 diag::err_delegating_initializer_alone) 5447 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5448 // We will treat this as being the only initializer. 5449 } 5450 SetDelegatingInitializer(Constructor, MemInits[i]); 5451 // Return immediately as the initializer is set. 5452 return; 5453 } 5454 } 5455 5456 if (HadError) 5457 return; 5458 5459 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5460 5461 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5462 5463 DiagnoseUninitializedFields(*this, Constructor); 5464 } 5465 5466 void 5467 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5468 CXXRecordDecl *ClassDecl) { 5469 // Ignore dependent contexts. Also ignore unions, since their members never 5470 // have destructors implicitly called. 5471 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5472 return; 5473 5474 // FIXME: all the access-control diagnostics are positioned on the 5475 // field/base declaration. That's probably good; that said, the 5476 // user might reasonably want to know why the destructor is being 5477 // emitted, and we currently don't say. 5478 5479 // Non-static data members. 5480 for (auto *Field : ClassDecl->fields()) { 5481 if (Field->isInvalidDecl()) 5482 continue; 5483 5484 // Don't destroy incomplete or zero-length arrays. 5485 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5486 continue; 5487 5488 QualType FieldType = Context.getBaseElementType(Field->getType()); 5489 5490 const RecordType* RT = FieldType->getAs<RecordType>(); 5491 if (!RT) 5492 continue; 5493 5494 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5495 if (FieldClassDecl->isInvalidDecl()) 5496 continue; 5497 if (FieldClassDecl->hasIrrelevantDestructor()) 5498 continue; 5499 // The destructor for an implicit anonymous union member is never invoked. 5500 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5501 continue; 5502 5503 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5504 assert(Dtor && "No dtor found for FieldClassDecl!"); 5505 CheckDestructorAccess(Field->getLocation(), Dtor, 5506 PDiag(diag::err_access_dtor_field) 5507 << Field->getDeclName() 5508 << FieldType); 5509 5510 MarkFunctionReferenced(Location, Dtor); 5511 DiagnoseUseOfDecl(Dtor, Location); 5512 } 5513 5514 // We only potentially invoke the destructors of potentially constructed 5515 // subobjects. 5516 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5517 5518 // If the destructor exists and has already been marked used in the MS ABI, 5519 // then virtual base destructors have already been checked and marked used. 5520 // Skip checking them again to avoid duplicate diagnostics. 5521 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5522 CXXDestructorDecl *Dtor = ClassDecl->getDestructor(); 5523 if (Dtor && Dtor->isUsed()) 5524 VisitVirtualBases = false; 5525 } 5526 5527 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5528 5529 // Bases. 5530 for (const auto &Base : ClassDecl->bases()) { 5531 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5532 if (!RT) 5533 continue; 5534 5535 // Remember direct virtual bases. 5536 if (Base.isVirtual()) { 5537 if (!VisitVirtualBases) 5538 continue; 5539 DirectVirtualBases.insert(RT); 5540 } 5541 5542 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5543 // If our base class is invalid, we probably can't get its dtor anyway. 5544 if (BaseClassDecl->isInvalidDecl()) 5545 continue; 5546 if (BaseClassDecl->hasIrrelevantDestructor()) 5547 continue; 5548 5549 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5550 assert(Dtor && "No dtor found for BaseClassDecl!"); 5551 5552 // FIXME: caret should be on the start of the class name 5553 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5554 PDiag(diag::err_access_dtor_base) 5555 << Base.getType() << Base.getSourceRange(), 5556 Context.getTypeDeclType(ClassDecl)); 5557 5558 MarkFunctionReferenced(Location, Dtor); 5559 DiagnoseUseOfDecl(Dtor, Location); 5560 } 5561 5562 if (VisitVirtualBases) 5563 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl, 5564 &DirectVirtualBases); 5565 } 5566 5567 void Sema::MarkVirtualBaseDestructorsReferenced( 5568 SourceLocation Location, CXXRecordDecl *ClassDecl, 5569 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) { 5570 // Virtual bases. 5571 for (const auto &VBase : ClassDecl->vbases()) { 5572 // Bases are always records in a well-formed non-dependent class. 5573 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5574 5575 // Ignore already visited direct virtual bases. 5576 if (DirectVirtualBases && DirectVirtualBases->count(RT)) 5577 continue; 5578 5579 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5580 // If our base class is invalid, we probably can't get its dtor anyway. 5581 if (BaseClassDecl->isInvalidDecl()) 5582 continue; 5583 if (BaseClassDecl->hasIrrelevantDestructor()) 5584 continue; 5585 5586 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5587 assert(Dtor && "No dtor found for BaseClassDecl!"); 5588 if (CheckDestructorAccess( 5589 ClassDecl->getLocation(), Dtor, 5590 PDiag(diag::err_access_dtor_vbase) 5591 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5592 Context.getTypeDeclType(ClassDecl)) == 5593 AR_accessible) { 5594 CheckDerivedToBaseConversion( 5595 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5596 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5597 SourceRange(), DeclarationName(), nullptr); 5598 } 5599 5600 MarkFunctionReferenced(Location, Dtor); 5601 DiagnoseUseOfDecl(Dtor, Location); 5602 } 5603 } 5604 5605 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5606 if (!CDtorDecl) 5607 return; 5608 5609 if (CXXConstructorDecl *Constructor 5610 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5611 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5612 DiagnoseUninitializedFields(*this, Constructor); 5613 } 5614 } 5615 5616 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5617 if (!getLangOpts().CPlusPlus) 5618 return false; 5619 5620 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5621 if (!RD) 5622 return false; 5623 5624 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5625 // class template specialization here, but doing so breaks a lot of code. 5626 5627 // We can't answer whether something is abstract until it has a 5628 // definition. If it's currently being defined, we'll walk back 5629 // over all the declarations when we have a full definition. 5630 const CXXRecordDecl *Def = RD->getDefinition(); 5631 if (!Def || Def->isBeingDefined()) 5632 return false; 5633 5634 return RD->isAbstract(); 5635 } 5636 5637 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5638 TypeDiagnoser &Diagnoser) { 5639 if (!isAbstractType(Loc, T)) 5640 return false; 5641 5642 T = Context.getBaseElementType(T); 5643 Diagnoser.diagnose(*this, Loc, T); 5644 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5645 return true; 5646 } 5647 5648 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5649 // Check if we've already emitted the list of pure virtual functions 5650 // for this class. 5651 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5652 return; 5653 5654 // If the diagnostic is suppressed, don't emit the notes. We're only 5655 // going to emit them once, so try to attach them to a diagnostic we're 5656 // actually going to show. 5657 if (Diags.isLastDiagnosticIgnored()) 5658 return; 5659 5660 CXXFinalOverriderMap FinalOverriders; 5661 RD->getFinalOverriders(FinalOverriders); 5662 5663 // Keep a set of seen pure methods so we won't diagnose the same method 5664 // more than once. 5665 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5666 5667 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5668 MEnd = FinalOverriders.end(); 5669 M != MEnd; 5670 ++M) { 5671 for (OverridingMethods::iterator SO = M->second.begin(), 5672 SOEnd = M->second.end(); 5673 SO != SOEnd; ++SO) { 5674 // C++ [class.abstract]p4: 5675 // A class is abstract if it contains or inherits at least one 5676 // pure virtual function for which the final overrider is pure 5677 // virtual. 5678 5679 // 5680 if (SO->second.size() != 1) 5681 continue; 5682 5683 if (!SO->second.front().Method->isPure()) 5684 continue; 5685 5686 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5687 continue; 5688 5689 Diag(SO->second.front().Method->getLocation(), 5690 diag::note_pure_virtual_function) 5691 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5692 } 5693 } 5694 5695 if (!PureVirtualClassDiagSet) 5696 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5697 PureVirtualClassDiagSet->insert(RD); 5698 } 5699 5700 namespace { 5701 struct AbstractUsageInfo { 5702 Sema &S; 5703 CXXRecordDecl *Record; 5704 CanQualType AbstractType; 5705 bool Invalid; 5706 5707 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5708 : S(S), Record(Record), 5709 AbstractType(S.Context.getCanonicalType( 5710 S.Context.getTypeDeclType(Record))), 5711 Invalid(false) {} 5712 5713 void DiagnoseAbstractType() { 5714 if (Invalid) return; 5715 S.DiagnoseAbstractType(Record); 5716 Invalid = true; 5717 } 5718 5719 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5720 }; 5721 5722 struct CheckAbstractUsage { 5723 AbstractUsageInfo &Info; 5724 const NamedDecl *Ctx; 5725 5726 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5727 : Info(Info), Ctx(Ctx) {} 5728 5729 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5730 switch (TL.getTypeLocClass()) { 5731 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5732 #define TYPELOC(CLASS, PARENT) \ 5733 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5734 #include "clang/AST/TypeLocNodes.def" 5735 } 5736 } 5737 5738 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5739 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5740 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5741 if (!TL.getParam(I)) 5742 continue; 5743 5744 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5745 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5746 } 5747 } 5748 5749 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5750 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5751 } 5752 5753 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5754 // Visit the type parameters from a permissive context. 5755 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5756 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5757 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5758 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5759 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5760 // TODO: other template argument types? 5761 } 5762 } 5763 5764 // Visit pointee types from a permissive context. 5765 #define CheckPolymorphic(Type) \ 5766 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5767 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5768 } 5769 CheckPolymorphic(PointerTypeLoc) 5770 CheckPolymorphic(ReferenceTypeLoc) 5771 CheckPolymorphic(MemberPointerTypeLoc) 5772 CheckPolymorphic(BlockPointerTypeLoc) 5773 CheckPolymorphic(AtomicTypeLoc) 5774 5775 /// Handle all the types we haven't given a more specific 5776 /// implementation for above. 5777 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5778 // Every other kind of type that we haven't called out already 5779 // that has an inner type is either (1) sugar or (2) contains that 5780 // inner type in some way as a subobject. 5781 if (TypeLoc Next = TL.getNextTypeLoc()) 5782 return Visit(Next, Sel); 5783 5784 // If there's no inner type and we're in a permissive context, 5785 // don't diagnose. 5786 if (Sel == Sema::AbstractNone) return; 5787 5788 // Check whether the type matches the abstract type. 5789 QualType T = TL.getType(); 5790 if (T->isArrayType()) { 5791 Sel = Sema::AbstractArrayType; 5792 T = Info.S.Context.getBaseElementType(T); 5793 } 5794 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5795 if (CT != Info.AbstractType) return; 5796 5797 // It matched; do some magic. 5798 if (Sel == Sema::AbstractArrayType) { 5799 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5800 << T << TL.getSourceRange(); 5801 } else { 5802 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5803 << Sel << T << TL.getSourceRange(); 5804 } 5805 Info.DiagnoseAbstractType(); 5806 } 5807 }; 5808 5809 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5810 Sema::AbstractDiagSelID Sel) { 5811 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5812 } 5813 5814 } 5815 5816 /// Check for invalid uses of an abstract type in a method declaration. 5817 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5818 CXXMethodDecl *MD) { 5819 // No need to do the check on definitions, which require that 5820 // the return/param types be complete. 5821 if (MD->doesThisDeclarationHaveABody()) 5822 return; 5823 5824 // For safety's sake, just ignore it if we don't have type source 5825 // information. This should never happen for non-implicit methods, 5826 // but... 5827 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5828 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5829 } 5830 5831 /// Check for invalid uses of an abstract type within a class definition. 5832 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5833 CXXRecordDecl *RD) { 5834 for (auto *D : RD->decls()) { 5835 if (D->isImplicit()) continue; 5836 5837 // Methods and method templates. 5838 if (isa<CXXMethodDecl>(D)) { 5839 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5840 } else if (isa<FunctionTemplateDecl>(D)) { 5841 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5842 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5843 5844 // Fields and static variables. 5845 } else if (isa<FieldDecl>(D)) { 5846 FieldDecl *FD = cast<FieldDecl>(D); 5847 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5848 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5849 } else if (isa<VarDecl>(D)) { 5850 VarDecl *VD = cast<VarDecl>(D); 5851 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5852 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5853 5854 // Nested classes and class templates. 5855 } else if (isa<CXXRecordDecl>(D)) { 5856 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5857 } else if (isa<ClassTemplateDecl>(D)) { 5858 CheckAbstractClassUsage(Info, 5859 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5860 } 5861 } 5862 } 5863 5864 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5865 Attr *ClassAttr = getDLLAttr(Class); 5866 if (!ClassAttr) 5867 return; 5868 5869 assert(ClassAttr->getKind() == attr::DLLExport); 5870 5871 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5872 5873 if (TSK == TSK_ExplicitInstantiationDeclaration) 5874 // Don't go any further if this is just an explicit instantiation 5875 // declaration. 5876 return; 5877 5878 // Add a context note to explain how we got to any diagnostics produced below. 5879 struct MarkingClassDllexported { 5880 Sema &S; 5881 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class, 5882 SourceLocation AttrLoc) 5883 : S(S) { 5884 Sema::CodeSynthesisContext Ctx; 5885 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported; 5886 Ctx.PointOfInstantiation = AttrLoc; 5887 Ctx.Entity = Class; 5888 S.pushCodeSynthesisContext(Ctx); 5889 } 5890 ~MarkingClassDllexported() { 5891 S.popCodeSynthesisContext(); 5892 } 5893 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); 5894 5895 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5896 S.MarkVTableUsed(Class->getLocation(), Class, true); 5897 5898 for (Decl *Member : Class->decls()) { 5899 // Defined static variables that are members of an exported base 5900 // class must be marked export too. 5901 auto *VD = dyn_cast<VarDecl>(Member); 5902 if (VD && Member->getAttr<DLLExportAttr>() && 5903 VD->getStorageClass() == SC_Static && 5904 TSK == TSK_ImplicitInstantiation) 5905 S.MarkVariableReferenced(VD->getLocation(), VD); 5906 5907 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5908 if (!MD) 5909 continue; 5910 5911 if (Member->getAttr<DLLExportAttr>()) { 5912 if (MD->isUserProvided()) { 5913 // Instantiate non-default class member functions ... 5914 5915 // .. except for certain kinds of template specializations. 5916 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5917 continue; 5918 5919 S.MarkFunctionReferenced(Class->getLocation(), MD); 5920 5921 // The function will be passed to the consumer when its definition is 5922 // encountered. 5923 } else if (MD->isExplicitlyDefaulted()) { 5924 // Synthesize and instantiate explicitly defaulted methods. 5925 S.MarkFunctionReferenced(Class->getLocation(), MD); 5926 5927 if (TSK != TSK_ExplicitInstantiationDefinition) { 5928 // Except for explicit instantiation defs, we will not see the 5929 // definition again later, so pass it to the consumer now. 5930 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5931 } 5932 } else if (!MD->isTrivial() || 5933 MD->isCopyAssignmentOperator() || 5934 MD->isMoveAssignmentOperator()) { 5935 // Synthesize and instantiate non-trivial implicit methods, and the copy 5936 // and move assignment operators. The latter are exported even if they 5937 // are trivial, because the address of an operator can be taken and 5938 // should compare equal across libraries. 5939 S.MarkFunctionReferenced(Class->getLocation(), MD); 5940 5941 // There is no later point when we will see the definition of this 5942 // function, so pass it to the consumer now. 5943 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5944 } 5945 } 5946 } 5947 } 5948 5949 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5950 CXXRecordDecl *Class) { 5951 // Only the MS ABI has default constructor closures, so we don't need to do 5952 // this semantic checking anywhere else. 5953 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5954 return; 5955 5956 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5957 for (Decl *Member : Class->decls()) { 5958 // Look for exported default constructors. 5959 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5960 if (!CD || !CD->isDefaultConstructor()) 5961 continue; 5962 auto *Attr = CD->getAttr<DLLExportAttr>(); 5963 if (!Attr) 5964 continue; 5965 5966 // If the class is non-dependent, mark the default arguments as ODR-used so 5967 // that we can properly codegen the constructor closure. 5968 if (!Class->isDependentContext()) { 5969 for (ParmVarDecl *PD : CD->parameters()) { 5970 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5971 S.DiscardCleanupsInEvaluationContext(); 5972 } 5973 } 5974 5975 if (LastExportedDefaultCtor) { 5976 S.Diag(LastExportedDefaultCtor->getLocation(), 5977 diag::err_attribute_dll_ambiguous_default_ctor) 5978 << Class; 5979 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5980 << CD->getDeclName(); 5981 return; 5982 } 5983 LastExportedDefaultCtor = CD; 5984 } 5985 } 5986 5987 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, 5988 CXXRecordDecl *Class) { 5989 bool ErrorReported = false; 5990 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 5991 ClassTemplateDecl *TD) { 5992 if (ErrorReported) 5993 return; 5994 S.Diag(TD->getLocation(), 5995 diag::err_cuda_device_builtin_surftex_cls_template) 5996 << /*surface*/ 0 << TD; 5997 ErrorReported = true; 5998 }; 5999 6000 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6001 if (!TD) { 6002 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6003 if (!SD) { 6004 S.Diag(Class->getLocation(), 6005 diag::err_cuda_device_builtin_surftex_ref_decl) 6006 << /*surface*/ 0 << Class; 6007 S.Diag(Class->getLocation(), 6008 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6009 << Class; 6010 return; 6011 } 6012 TD = SD->getSpecializedTemplate(); 6013 } 6014 6015 TemplateParameterList *Params = TD->getTemplateParameters(); 6016 unsigned N = Params->size(); 6017 6018 if (N != 2) { 6019 reportIllegalClassTemplate(S, TD); 6020 S.Diag(TD->getLocation(), 6021 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6022 << TD << 2; 6023 } 6024 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6025 reportIllegalClassTemplate(S, TD); 6026 S.Diag(TD->getLocation(), 6027 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6028 << TD << /*1st*/ 0 << /*type*/ 0; 6029 } 6030 if (N > 1) { 6031 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6032 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6033 reportIllegalClassTemplate(S, TD); 6034 S.Diag(TD->getLocation(), 6035 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6036 << TD << /*2nd*/ 1 << /*integer*/ 1; 6037 } 6038 } 6039 } 6040 6041 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, 6042 CXXRecordDecl *Class) { 6043 bool ErrorReported = false; 6044 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6045 ClassTemplateDecl *TD) { 6046 if (ErrorReported) 6047 return; 6048 S.Diag(TD->getLocation(), 6049 diag::err_cuda_device_builtin_surftex_cls_template) 6050 << /*texture*/ 1 << TD; 6051 ErrorReported = true; 6052 }; 6053 6054 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6055 if (!TD) { 6056 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6057 if (!SD) { 6058 S.Diag(Class->getLocation(), 6059 diag::err_cuda_device_builtin_surftex_ref_decl) 6060 << /*texture*/ 1 << Class; 6061 S.Diag(Class->getLocation(), 6062 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6063 << Class; 6064 return; 6065 } 6066 TD = SD->getSpecializedTemplate(); 6067 } 6068 6069 TemplateParameterList *Params = TD->getTemplateParameters(); 6070 unsigned N = Params->size(); 6071 6072 if (N != 3) { 6073 reportIllegalClassTemplate(S, TD); 6074 S.Diag(TD->getLocation(), 6075 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6076 << TD << 3; 6077 } 6078 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6079 reportIllegalClassTemplate(S, TD); 6080 S.Diag(TD->getLocation(), 6081 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6082 << TD << /*1st*/ 0 << /*type*/ 0; 6083 } 6084 if (N > 1) { 6085 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6086 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6087 reportIllegalClassTemplate(S, TD); 6088 S.Diag(TD->getLocation(), 6089 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6090 << TD << /*2nd*/ 1 << /*integer*/ 1; 6091 } 6092 } 6093 if (N > 2) { 6094 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2)); 6095 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6096 reportIllegalClassTemplate(S, TD); 6097 S.Diag(TD->getLocation(), 6098 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6099 << TD << /*3rd*/ 2 << /*integer*/ 1; 6100 } 6101 } 6102 } 6103 6104 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 6105 // Mark any compiler-generated routines with the implicit code_seg attribute. 6106 for (auto *Method : Class->methods()) { 6107 if (Method->isUserProvided()) 6108 continue; 6109 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 6110 Method->addAttr(A); 6111 } 6112 } 6113 6114 /// Check class-level dllimport/dllexport attribute. 6115 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 6116 Attr *ClassAttr = getDLLAttr(Class); 6117 6118 // MSVC inherits DLL attributes to partial class template specializations. 6119 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) { 6120 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 6121 if (Attr *TemplateAttr = 6122 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 6123 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 6124 A->setInherited(true); 6125 ClassAttr = A; 6126 } 6127 } 6128 } 6129 6130 if (!ClassAttr) 6131 return; 6132 6133 if (!Class->isExternallyVisible()) { 6134 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 6135 << Class << ClassAttr; 6136 return; 6137 } 6138 6139 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6140 !ClassAttr->isInherited()) { 6141 // Diagnose dll attributes on members of class with dll attribute. 6142 for (Decl *Member : Class->decls()) { 6143 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 6144 continue; 6145 InheritableAttr *MemberAttr = getDLLAttr(Member); 6146 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 6147 continue; 6148 6149 Diag(MemberAttr->getLocation(), 6150 diag::err_attribute_dll_member_of_dll_class) 6151 << MemberAttr << ClassAttr; 6152 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 6153 Member->setInvalidDecl(); 6154 } 6155 } 6156 6157 if (Class->getDescribedClassTemplate()) 6158 // Don't inherit dll attribute until the template is instantiated. 6159 return; 6160 6161 // The class is either imported or exported. 6162 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 6163 6164 // Check if this was a dllimport attribute propagated from a derived class to 6165 // a base class template specialization. We don't apply these attributes to 6166 // static data members. 6167 const bool PropagatedImport = 6168 !ClassExported && 6169 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 6170 6171 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6172 6173 // Ignore explicit dllexport on explicit class template instantiation 6174 // declarations, except in MinGW mode. 6175 if (ClassExported && !ClassAttr->isInherited() && 6176 TSK == TSK_ExplicitInstantiationDeclaration && 6177 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 6178 Class->dropAttr<DLLExportAttr>(); 6179 return; 6180 } 6181 6182 // Force declaration of implicit members so they can inherit the attribute. 6183 ForceDeclarationOfImplicitMembers(Class); 6184 6185 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 6186 // seem to be true in practice? 6187 6188 for (Decl *Member : Class->decls()) { 6189 VarDecl *VD = dyn_cast<VarDecl>(Member); 6190 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 6191 6192 // Only methods and static fields inherit the attributes. 6193 if (!VD && !MD) 6194 continue; 6195 6196 if (MD) { 6197 // Don't process deleted methods. 6198 if (MD->isDeleted()) 6199 continue; 6200 6201 if (MD->isInlined()) { 6202 // MinGW does not import or export inline methods. But do it for 6203 // template instantiations. 6204 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6205 TSK != TSK_ExplicitInstantiationDeclaration && 6206 TSK != TSK_ExplicitInstantiationDefinition) 6207 continue; 6208 6209 // MSVC versions before 2015 don't export the move assignment operators 6210 // and move constructor, so don't attempt to import/export them if 6211 // we have a definition. 6212 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 6213 if ((MD->isMoveAssignmentOperator() || 6214 (Ctor && Ctor->isMoveConstructor())) && 6215 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 6216 continue; 6217 6218 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 6219 // operator is exported anyway. 6220 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6221 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 6222 continue; 6223 } 6224 } 6225 6226 // Don't apply dllimport attributes to static data members of class template 6227 // instantiations when the attribute is propagated from a derived class. 6228 if (VD && PropagatedImport) 6229 continue; 6230 6231 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6232 continue; 6233 6234 if (!getDLLAttr(Member)) { 6235 InheritableAttr *NewAttr = nullptr; 6236 6237 // Do not export/import inline function when -fno-dllexport-inlines is 6238 // passed. But add attribute for later local static var check. 6239 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6240 TSK != TSK_ExplicitInstantiationDeclaration && 6241 TSK != TSK_ExplicitInstantiationDefinition) { 6242 if (ClassExported) { 6243 NewAttr = ::new (getASTContext()) 6244 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6245 } else { 6246 NewAttr = ::new (getASTContext()) 6247 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6248 } 6249 } else { 6250 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6251 } 6252 6253 NewAttr->setInherited(true); 6254 Member->addAttr(NewAttr); 6255 6256 if (MD) { 6257 // Propagate DLLAttr to friend re-declarations of MD that have already 6258 // been constructed. 6259 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6260 FD = FD->getPreviousDecl()) { 6261 if (FD->getFriendObjectKind() == Decl::FOK_None) 6262 continue; 6263 assert(!getDLLAttr(FD) && 6264 "friend re-decl should not already have a DLLAttr"); 6265 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6266 NewAttr->setInherited(true); 6267 FD->addAttr(NewAttr); 6268 } 6269 } 6270 } 6271 } 6272 6273 if (ClassExported) 6274 DelayedDllExportClasses.push_back(Class); 6275 } 6276 6277 /// Perform propagation of DLL attributes from a derived class to a 6278 /// templated base class for MS compatibility. 6279 void Sema::propagateDLLAttrToBaseClassTemplate( 6280 CXXRecordDecl *Class, Attr *ClassAttr, 6281 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6282 if (getDLLAttr( 6283 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6284 // If the base class template has a DLL attribute, don't try to change it. 6285 return; 6286 } 6287 6288 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6289 if (!getDLLAttr(BaseTemplateSpec) && 6290 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6291 TSK == TSK_ImplicitInstantiation)) { 6292 // The template hasn't been instantiated yet (or it has, but only as an 6293 // explicit instantiation declaration or implicit instantiation, which means 6294 // we haven't codegenned any members yet), so propagate the attribute. 6295 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6296 NewAttr->setInherited(true); 6297 BaseTemplateSpec->addAttr(NewAttr); 6298 6299 // If this was an import, mark that we propagated it from a derived class to 6300 // a base class template specialization. 6301 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6302 ImportAttr->setPropagatedToBaseTemplate(); 6303 6304 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6305 // needs to be run again to work see the new attribute. Otherwise this will 6306 // get run whenever the template is instantiated. 6307 if (TSK != TSK_Undeclared) 6308 checkClassLevelDLLAttribute(BaseTemplateSpec); 6309 6310 return; 6311 } 6312 6313 if (getDLLAttr(BaseTemplateSpec)) { 6314 // The template has already been specialized or instantiated with an 6315 // attribute, explicitly or through propagation. We should not try to change 6316 // it. 6317 return; 6318 } 6319 6320 // The template was previously instantiated or explicitly specialized without 6321 // a dll attribute, It's too late for us to add an attribute, so warn that 6322 // this is unsupported. 6323 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6324 << BaseTemplateSpec->isExplicitSpecialization(); 6325 Diag(ClassAttr->getLocation(), diag::note_attribute); 6326 if (BaseTemplateSpec->isExplicitSpecialization()) { 6327 Diag(BaseTemplateSpec->getLocation(), 6328 diag::note_template_class_explicit_specialization_was_here) 6329 << BaseTemplateSpec; 6330 } else { 6331 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6332 diag::note_template_class_instantiation_was_here) 6333 << BaseTemplateSpec; 6334 } 6335 } 6336 6337 /// Determine the kind of defaulting that would be done for a given function. 6338 /// 6339 /// If the function is both a default constructor and a copy / move constructor 6340 /// (due to having a default argument for the first parameter), this picks 6341 /// CXXDefaultConstructor. 6342 /// 6343 /// FIXME: Check that case is properly handled by all callers. 6344 Sema::DefaultedFunctionKind 6345 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6346 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6347 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6348 if (Ctor->isDefaultConstructor()) 6349 return Sema::CXXDefaultConstructor; 6350 6351 if (Ctor->isCopyConstructor()) 6352 return Sema::CXXCopyConstructor; 6353 6354 if (Ctor->isMoveConstructor()) 6355 return Sema::CXXMoveConstructor; 6356 } 6357 6358 if (MD->isCopyAssignmentOperator()) 6359 return Sema::CXXCopyAssignment; 6360 6361 if (MD->isMoveAssignmentOperator()) 6362 return Sema::CXXMoveAssignment; 6363 6364 if (isa<CXXDestructorDecl>(FD)) 6365 return Sema::CXXDestructor; 6366 } 6367 6368 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6369 case OO_EqualEqual: 6370 return DefaultedComparisonKind::Equal; 6371 6372 case OO_ExclaimEqual: 6373 return DefaultedComparisonKind::NotEqual; 6374 6375 case OO_Spaceship: 6376 // No point allowing this if <=> doesn't exist in the current language mode. 6377 if (!getLangOpts().CPlusPlus20) 6378 break; 6379 return DefaultedComparisonKind::ThreeWay; 6380 6381 case OO_Less: 6382 case OO_LessEqual: 6383 case OO_Greater: 6384 case OO_GreaterEqual: 6385 // No point allowing this if <=> doesn't exist in the current language mode. 6386 if (!getLangOpts().CPlusPlus20) 6387 break; 6388 return DefaultedComparisonKind::Relational; 6389 6390 default: 6391 break; 6392 } 6393 6394 // Not defaultable. 6395 return DefaultedFunctionKind(); 6396 } 6397 6398 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, 6399 SourceLocation DefaultLoc) { 6400 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD); 6401 if (DFK.isComparison()) 6402 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison()); 6403 6404 switch (DFK.asSpecialMember()) { 6405 case Sema::CXXDefaultConstructor: 6406 S.DefineImplicitDefaultConstructor(DefaultLoc, 6407 cast<CXXConstructorDecl>(FD)); 6408 break; 6409 case Sema::CXXCopyConstructor: 6410 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6411 break; 6412 case Sema::CXXCopyAssignment: 6413 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6414 break; 6415 case Sema::CXXDestructor: 6416 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD)); 6417 break; 6418 case Sema::CXXMoveConstructor: 6419 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6420 break; 6421 case Sema::CXXMoveAssignment: 6422 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6423 break; 6424 case Sema::CXXInvalid: 6425 llvm_unreachable("Invalid special member."); 6426 } 6427 } 6428 6429 /// Determine whether a type is permitted to be passed or returned in 6430 /// registers, per C++ [class.temporary]p3. 6431 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6432 TargetInfo::CallingConvKind CCK) { 6433 if (D->isDependentType() || D->isInvalidDecl()) 6434 return false; 6435 6436 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6437 // The PS4 platform ABI follows the behavior of Clang 3.2. 6438 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6439 return !D->hasNonTrivialDestructorForCall() && 6440 !D->hasNonTrivialCopyConstructorForCall(); 6441 6442 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6443 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6444 bool DtorIsTrivialForCall = false; 6445 6446 // If a class has at least one non-deleted, trivial copy constructor, it 6447 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6448 // 6449 // Note: This permits classes with non-trivial copy or move ctors to be 6450 // passed in registers, so long as they *also* have a trivial copy ctor, 6451 // which is non-conforming. 6452 if (D->needsImplicitCopyConstructor()) { 6453 if (!D->defaultedCopyConstructorIsDeleted()) { 6454 if (D->hasTrivialCopyConstructor()) 6455 CopyCtorIsTrivial = true; 6456 if (D->hasTrivialCopyConstructorForCall()) 6457 CopyCtorIsTrivialForCall = true; 6458 } 6459 } else { 6460 for (const CXXConstructorDecl *CD : D->ctors()) { 6461 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6462 if (CD->isTrivial()) 6463 CopyCtorIsTrivial = true; 6464 if (CD->isTrivialForCall()) 6465 CopyCtorIsTrivialForCall = true; 6466 } 6467 } 6468 } 6469 6470 if (D->needsImplicitDestructor()) { 6471 if (!D->defaultedDestructorIsDeleted() && 6472 D->hasTrivialDestructorForCall()) 6473 DtorIsTrivialForCall = true; 6474 } else if (const auto *DD = D->getDestructor()) { 6475 if (!DD->isDeleted() && DD->isTrivialForCall()) 6476 DtorIsTrivialForCall = true; 6477 } 6478 6479 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6480 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6481 return true; 6482 6483 // If a class has a destructor, we'd really like to pass it indirectly 6484 // because it allows us to elide copies. Unfortunately, MSVC makes that 6485 // impossible for small types, which it will pass in a single register or 6486 // stack slot. Most objects with dtors are large-ish, so handle that early. 6487 // We can't call out all large objects as being indirect because there are 6488 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6489 // how we pass large POD types. 6490 6491 // Note: This permits small classes with nontrivial destructors to be 6492 // passed in registers, which is non-conforming. 6493 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6494 uint64_t TypeSize = isAArch64 ? 128 : 64; 6495 6496 if (CopyCtorIsTrivial && 6497 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6498 return true; 6499 return false; 6500 } 6501 6502 // Per C++ [class.temporary]p3, the relevant condition is: 6503 // each copy constructor, move constructor, and destructor of X is 6504 // either trivial or deleted, and X has at least one non-deleted copy 6505 // or move constructor 6506 bool HasNonDeletedCopyOrMove = false; 6507 6508 if (D->needsImplicitCopyConstructor() && 6509 !D->defaultedCopyConstructorIsDeleted()) { 6510 if (!D->hasTrivialCopyConstructorForCall()) 6511 return false; 6512 HasNonDeletedCopyOrMove = true; 6513 } 6514 6515 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6516 !D->defaultedMoveConstructorIsDeleted()) { 6517 if (!D->hasTrivialMoveConstructorForCall()) 6518 return false; 6519 HasNonDeletedCopyOrMove = true; 6520 } 6521 6522 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6523 !D->hasTrivialDestructorForCall()) 6524 return false; 6525 6526 for (const CXXMethodDecl *MD : D->methods()) { 6527 if (MD->isDeleted()) 6528 continue; 6529 6530 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6531 if (CD && CD->isCopyOrMoveConstructor()) 6532 HasNonDeletedCopyOrMove = true; 6533 else if (!isa<CXXDestructorDecl>(MD)) 6534 continue; 6535 6536 if (!MD->isTrivialForCall()) 6537 return false; 6538 } 6539 6540 return HasNonDeletedCopyOrMove; 6541 } 6542 6543 /// Report an error regarding overriding, along with any relevant 6544 /// overridden methods. 6545 /// 6546 /// \param DiagID the primary error to report. 6547 /// \param MD the overriding method. 6548 static bool 6549 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, 6550 llvm::function_ref<bool(const CXXMethodDecl *)> Report) { 6551 bool IssuedDiagnostic = false; 6552 for (const CXXMethodDecl *O : MD->overridden_methods()) { 6553 if (Report(O)) { 6554 if (!IssuedDiagnostic) { 6555 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6556 IssuedDiagnostic = true; 6557 } 6558 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 6559 } 6560 } 6561 return IssuedDiagnostic; 6562 } 6563 6564 /// Perform semantic checks on a class definition that has been 6565 /// completing, introducing implicitly-declared members, checking for 6566 /// abstract types, etc. 6567 /// 6568 /// \param S The scope in which the class was parsed. Null if we didn't just 6569 /// parse a class definition. 6570 /// \param Record The completed class. 6571 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6572 if (!Record) 6573 return; 6574 6575 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6576 AbstractUsageInfo Info(*this, Record); 6577 CheckAbstractClassUsage(Info, Record); 6578 } 6579 6580 // If this is not an aggregate type and has no user-declared constructor, 6581 // complain about any non-static data members of reference or const scalar 6582 // type, since they will never get initializers. 6583 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6584 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6585 !Record->isLambda()) { 6586 bool Complained = false; 6587 for (const auto *F : Record->fields()) { 6588 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6589 continue; 6590 6591 if (F->getType()->isReferenceType() || 6592 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6593 if (!Complained) { 6594 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6595 << Record->getTagKind() << Record; 6596 Complained = true; 6597 } 6598 6599 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6600 << F->getType()->isReferenceType() 6601 << F->getDeclName(); 6602 } 6603 } 6604 } 6605 6606 if (Record->getIdentifier()) { 6607 // C++ [class.mem]p13: 6608 // If T is the name of a class, then each of the following shall have a 6609 // name different from T: 6610 // - every member of every anonymous union that is a member of class T. 6611 // 6612 // C++ [class.mem]p14: 6613 // In addition, if class T has a user-declared constructor (12.1), every 6614 // non-static data member of class T shall have a name different from T. 6615 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6616 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6617 ++I) { 6618 NamedDecl *D = (*I)->getUnderlyingDecl(); 6619 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6620 Record->hasUserDeclaredConstructor()) || 6621 isa<IndirectFieldDecl>(D)) { 6622 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6623 << D->getDeclName(); 6624 break; 6625 } 6626 } 6627 } 6628 6629 // Warn if the class has virtual methods but non-virtual public destructor. 6630 if (Record->isPolymorphic() && !Record->isDependentType()) { 6631 CXXDestructorDecl *dtor = Record->getDestructor(); 6632 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6633 !Record->hasAttr<FinalAttr>()) 6634 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6635 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6636 } 6637 6638 if (Record->isAbstract()) { 6639 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6640 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6641 << FA->isSpelledAsSealed(); 6642 DiagnoseAbstractType(Record); 6643 } 6644 } 6645 6646 // Warn if the class has a final destructor but is not itself marked final. 6647 if (!Record->hasAttr<FinalAttr>()) { 6648 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6649 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6650 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6651 << FA->isSpelledAsSealed() 6652 << FixItHint::CreateInsertion( 6653 getLocForEndOfToken(Record->getLocation()), 6654 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6655 Diag(Record->getLocation(), 6656 diag::note_final_dtor_non_final_class_silence) 6657 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6658 } 6659 } 6660 } 6661 6662 // See if trivial_abi has to be dropped. 6663 if (Record->hasAttr<TrivialABIAttr>()) 6664 checkIllFormedTrivialABIStruct(*Record); 6665 6666 // Set HasTrivialSpecialMemberForCall if the record has attribute 6667 // "trivial_abi". 6668 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6669 6670 if (HasTrivialABI) 6671 Record->setHasTrivialSpecialMemberForCall(); 6672 6673 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6674 // We check these last because they can depend on the properties of the 6675 // primary comparison functions (==, <=>). 6676 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6677 6678 // Perform checks that can't be done until we know all the properties of a 6679 // member function (whether it's defaulted, deleted, virtual, overriding, 6680 // ...). 6681 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) { 6682 // A static function cannot override anything. 6683 if (MD->getStorageClass() == SC_Static) { 6684 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD, 6685 [](const CXXMethodDecl *) { return true; })) 6686 return; 6687 } 6688 6689 // A deleted function cannot override a non-deleted function and vice 6690 // versa. 6691 if (ReportOverrides(*this, 6692 MD->isDeleted() ? diag::err_deleted_override 6693 : diag::err_non_deleted_override, 6694 MD, [&](const CXXMethodDecl *V) { 6695 return MD->isDeleted() != V->isDeleted(); 6696 })) { 6697 if (MD->isDefaulted() && MD->isDeleted()) 6698 // Explain why this defaulted function was deleted. 6699 DiagnoseDeletedDefaultedFunction(MD); 6700 return; 6701 } 6702 6703 // A consteval function cannot override a non-consteval function and vice 6704 // versa. 6705 if (ReportOverrides(*this, 6706 MD->isConsteval() ? diag::err_consteval_override 6707 : diag::err_non_consteval_override, 6708 MD, [&](const CXXMethodDecl *V) { 6709 return MD->isConsteval() != V->isConsteval(); 6710 })) { 6711 if (MD->isDefaulted() && MD->isDeleted()) 6712 // Explain why this defaulted function was deleted. 6713 DiagnoseDeletedDefaultedFunction(MD); 6714 return; 6715 } 6716 }; 6717 6718 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool { 6719 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6720 return false; 6721 6722 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6723 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6724 DFK.asComparison() == DefaultedComparisonKind::Relational) { 6725 DefaultedSecondaryComparisons.push_back(FD); 6726 return true; 6727 } 6728 6729 CheckExplicitlyDefaultedFunction(S, FD); 6730 return false; 6731 }; 6732 6733 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6734 // Check whether the explicitly-defaulted members are valid. 6735 bool Incomplete = CheckForDefaultedFunction(M); 6736 6737 // Skip the rest of the checks for a member of a dependent class. 6738 if (Record->isDependentType()) 6739 return; 6740 6741 // For an explicitly defaulted or deleted special member, we defer 6742 // determining triviality until the class is complete. That time is now! 6743 CXXSpecialMember CSM = getSpecialMember(M); 6744 if (!M->isImplicit() && !M->isUserProvided()) { 6745 if (CSM != CXXInvalid) { 6746 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6747 // Inform the class that we've finished declaring this member. 6748 Record->finishedDefaultedOrDeletedMember(M); 6749 M->setTrivialForCall( 6750 HasTrivialABI || 6751 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6752 Record->setTrivialForCallFlags(M); 6753 } 6754 } 6755 6756 // Set triviality for the purpose of calls if this is a user-provided 6757 // copy/move constructor or destructor. 6758 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6759 CSM == CXXDestructor) && M->isUserProvided()) { 6760 M->setTrivialForCall(HasTrivialABI); 6761 Record->setTrivialForCallFlags(M); 6762 } 6763 6764 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6765 M->hasAttr<DLLExportAttr>()) { 6766 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6767 M->isTrivial() && 6768 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6769 CSM == CXXDestructor)) 6770 M->dropAttr<DLLExportAttr>(); 6771 6772 if (M->hasAttr<DLLExportAttr>()) { 6773 // Define after any fields with in-class initializers have been parsed. 6774 DelayedDllExportMemberFunctions.push_back(M); 6775 } 6776 } 6777 6778 // Define defaulted constexpr virtual functions that override a base class 6779 // function right away. 6780 // FIXME: We can defer doing this until the vtable is marked as used. 6781 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6782 DefineDefaultedFunction(*this, M, M->getLocation()); 6783 6784 if (!Incomplete) 6785 CheckCompletedMemberFunction(M); 6786 }; 6787 6788 // Check the destructor before any other member function. We need to 6789 // determine whether it's trivial in order to determine whether the claas 6790 // type is a literal type, which is a prerequisite for determining whether 6791 // other special member functions are valid and whether they're implicitly 6792 // 'constexpr'. 6793 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6794 CompleteMemberFunction(Dtor); 6795 6796 bool HasMethodWithOverrideControl = false, 6797 HasOverridingMethodWithoutOverrideControl = false; 6798 for (auto *D : Record->decls()) { 6799 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 6800 // FIXME: We could do this check for dependent types with non-dependent 6801 // bases. 6802 if (!Record->isDependentType()) { 6803 // See if a method overloads virtual methods in a base 6804 // class without overriding any. 6805 if (!M->isStatic()) 6806 DiagnoseHiddenVirtualMethods(M); 6807 if (M->hasAttr<OverrideAttr>()) 6808 HasMethodWithOverrideControl = true; 6809 else if (M->size_overridden_methods() > 0) 6810 HasOverridingMethodWithoutOverrideControl = true; 6811 } 6812 6813 if (!isa<CXXDestructorDecl>(M)) 6814 CompleteMemberFunction(M); 6815 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 6816 CheckForDefaultedFunction( 6817 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 6818 } 6819 } 6820 6821 if (HasOverridingMethodWithoutOverrideControl) { 6822 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl; 6823 for (auto *M : Record->methods()) 6824 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl); 6825 } 6826 6827 // Check the defaulted secondary comparisons after any other member functions. 6828 for (FunctionDecl *FD : DefaultedSecondaryComparisons) { 6829 CheckExplicitlyDefaultedFunction(S, FD); 6830 6831 // If this is a member function, we deferred checking it until now. 6832 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) 6833 CheckCompletedMemberFunction(MD); 6834 } 6835 6836 // ms_struct is a request to use the same ABI rules as MSVC. Check 6837 // whether this class uses any C++ features that are implemented 6838 // completely differently in MSVC, and if so, emit a diagnostic. 6839 // That diagnostic defaults to an error, but we allow projects to 6840 // map it down to a warning (or ignore it). It's a fairly common 6841 // practice among users of the ms_struct pragma to mass-annotate 6842 // headers, sweeping up a bunch of types that the project doesn't 6843 // really rely on MSVC-compatible layout for. We must therefore 6844 // support "ms_struct except for C++ stuff" as a secondary ABI. 6845 // Don't emit this diagnostic if the feature was enabled as a 6846 // language option (as opposed to via a pragma or attribute), as 6847 // the option -mms-bitfields otherwise essentially makes it impossible 6848 // to build C++ code, unless this diagnostic is turned off. 6849 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields && 6850 (Record->isPolymorphic() || Record->getNumBases())) { 6851 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6852 } 6853 6854 checkClassLevelDLLAttribute(Record); 6855 checkClassLevelCodeSegAttribute(Record); 6856 6857 bool ClangABICompat4 = 6858 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6859 TargetInfo::CallingConvKind CCK = 6860 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6861 bool CanPass = canPassInRegisters(*this, Record, CCK); 6862 6863 // Do not change ArgPassingRestrictions if it has already been set to 6864 // APK_CanNeverPassInRegs. 6865 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6866 Record->setArgPassingRestrictions(CanPass 6867 ? RecordDecl::APK_CanPassInRegs 6868 : RecordDecl::APK_CannotPassInRegs); 6869 6870 // If canPassInRegisters returns true despite the record having a non-trivial 6871 // destructor, the record is destructed in the callee. This happens only when 6872 // the record or one of its subobjects has a field annotated with trivial_abi 6873 // or a field qualified with ObjC __strong/__weak. 6874 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6875 Record->setParamDestroyedInCallee(true); 6876 else if (Record->hasNonTrivialDestructor()) 6877 Record->setParamDestroyedInCallee(CanPass); 6878 6879 if (getLangOpts().ForceEmitVTables) { 6880 // If we want to emit all the vtables, we need to mark it as used. This 6881 // is especially required for cases like vtable assumption loads. 6882 MarkVTableUsed(Record->getInnerLocStart(), Record); 6883 } 6884 6885 if (getLangOpts().CUDA) { 6886 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) 6887 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record); 6888 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>()) 6889 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record); 6890 } 6891 } 6892 6893 /// Look up the special member function that would be called by a special 6894 /// member function for a subobject of class type. 6895 /// 6896 /// \param Class The class type of the subobject. 6897 /// \param CSM The kind of special member function. 6898 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6899 /// \param ConstRHS True if this is a copy operation with a const object 6900 /// on its RHS, that is, if the argument to the outer special member 6901 /// function is 'const' and this is not a field marked 'mutable'. 6902 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6903 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6904 unsigned FieldQuals, bool ConstRHS) { 6905 unsigned LHSQuals = 0; 6906 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6907 LHSQuals = FieldQuals; 6908 6909 unsigned RHSQuals = FieldQuals; 6910 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6911 RHSQuals = 0; 6912 else if (ConstRHS) 6913 RHSQuals |= Qualifiers::Const; 6914 6915 return S.LookupSpecialMember(Class, CSM, 6916 RHSQuals & Qualifiers::Const, 6917 RHSQuals & Qualifiers::Volatile, 6918 false, 6919 LHSQuals & Qualifiers::Const, 6920 LHSQuals & Qualifiers::Volatile); 6921 } 6922 6923 class Sema::InheritedConstructorInfo { 6924 Sema &S; 6925 SourceLocation UseLoc; 6926 6927 /// A mapping from the base classes through which the constructor was 6928 /// inherited to the using shadow declaration in that base class (or a null 6929 /// pointer if the constructor was declared in that base class). 6930 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6931 InheritedFromBases; 6932 6933 public: 6934 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6935 ConstructorUsingShadowDecl *Shadow) 6936 : S(S), UseLoc(UseLoc) { 6937 bool DiagnosedMultipleConstructedBases = false; 6938 CXXRecordDecl *ConstructedBase = nullptr; 6939 UsingDecl *ConstructedBaseUsing = nullptr; 6940 6941 // Find the set of such base class subobjects and check that there's a 6942 // unique constructed subobject. 6943 for (auto *D : Shadow->redecls()) { 6944 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6945 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6946 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6947 6948 InheritedFromBases.insert( 6949 std::make_pair(DNominatedBase->getCanonicalDecl(), 6950 DShadow->getNominatedBaseClassShadowDecl())); 6951 if (DShadow->constructsVirtualBase()) 6952 InheritedFromBases.insert( 6953 std::make_pair(DConstructedBase->getCanonicalDecl(), 6954 DShadow->getConstructedBaseClassShadowDecl())); 6955 else 6956 assert(DNominatedBase == DConstructedBase); 6957 6958 // [class.inhctor.init]p2: 6959 // If the constructor was inherited from multiple base class subobjects 6960 // of type B, the program is ill-formed. 6961 if (!ConstructedBase) { 6962 ConstructedBase = DConstructedBase; 6963 ConstructedBaseUsing = D->getUsingDecl(); 6964 } else if (ConstructedBase != DConstructedBase && 6965 !Shadow->isInvalidDecl()) { 6966 if (!DiagnosedMultipleConstructedBases) { 6967 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6968 << Shadow->getTargetDecl(); 6969 S.Diag(ConstructedBaseUsing->getLocation(), 6970 diag::note_ambiguous_inherited_constructor_using) 6971 << ConstructedBase; 6972 DiagnosedMultipleConstructedBases = true; 6973 } 6974 S.Diag(D->getUsingDecl()->getLocation(), 6975 diag::note_ambiguous_inherited_constructor_using) 6976 << DConstructedBase; 6977 } 6978 } 6979 6980 if (DiagnosedMultipleConstructedBases) 6981 Shadow->setInvalidDecl(); 6982 } 6983 6984 /// Find the constructor to use for inherited construction of a base class, 6985 /// and whether that base class constructor inherits the constructor from a 6986 /// virtual base class (in which case it won't actually invoke it). 6987 std::pair<CXXConstructorDecl *, bool> 6988 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6989 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6990 if (It == InheritedFromBases.end()) 6991 return std::make_pair(nullptr, false); 6992 6993 // This is an intermediary class. 6994 if (It->second) 6995 return std::make_pair( 6996 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6997 It->second->constructsVirtualBase()); 6998 6999 // This is the base class from which the constructor was inherited. 7000 return std::make_pair(Ctor, false); 7001 } 7002 }; 7003 7004 /// Is the special member function which would be selected to perform the 7005 /// specified operation on the specified class type a constexpr constructor? 7006 static bool 7007 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 7008 Sema::CXXSpecialMember CSM, unsigned Quals, 7009 bool ConstRHS, 7010 CXXConstructorDecl *InheritedCtor = nullptr, 7011 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7012 // If we're inheriting a constructor, see if we need to call it for this base 7013 // class. 7014 if (InheritedCtor) { 7015 assert(CSM == Sema::CXXDefaultConstructor); 7016 auto BaseCtor = 7017 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 7018 if (BaseCtor) 7019 return BaseCtor->isConstexpr(); 7020 } 7021 7022 if (CSM == Sema::CXXDefaultConstructor) 7023 return ClassDecl->hasConstexprDefaultConstructor(); 7024 if (CSM == Sema::CXXDestructor) 7025 return ClassDecl->hasConstexprDestructor(); 7026 7027 Sema::SpecialMemberOverloadResult SMOR = 7028 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 7029 if (!SMOR.getMethod()) 7030 // A constructor we wouldn't select can't be "involved in initializing" 7031 // anything. 7032 return true; 7033 return SMOR.getMethod()->isConstexpr(); 7034 } 7035 7036 /// Determine whether the specified special member function would be constexpr 7037 /// if it were implicitly defined. 7038 static bool defaultedSpecialMemberIsConstexpr( 7039 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 7040 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 7041 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7042 if (!S.getLangOpts().CPlusPlus11) 7043 return false; 7044 7045 // C++11 [dcl.constexpr]p4: 7046 // In the definition of a constexpr constructor [...] 7047 bool Ctor = true; 7048 switch (CSM) { 7049 case Sema::CXXDefaultConstructor: 7050 if (Inherited) 7051 break; 7052 // Since default constructor lookup is essentially trivial (and cannot 7053 // involve, for instance, template instantiation), we compute whether a 7054 // defaulted default constructor is constexpr directly within CXXRecordDecl. 7055 // 7056 // This is important for performance; we need to know whether the default 7057 // constructor is constexpr to determine whether the type is a literal type. 7058 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 7059 7060 case Sema::CXXCopyConstructor: 7061 case Sema::CXXMoveConstructor: 7062 // For copy or move constructors, we need to perform overload resolution. 7063 break; 7064 7065 case Sema::CXXCopyAssignment: 7066 case Sema::CXXMoveAssignment: 7067 if (!S.getLangOpts().CPlusPlus14) 7068 return false; 7069 // In C++1y, we need to perform overload resolution. 7070 Ctor = false; 7071 break; 7072 7073 case Sema::CXXDestructor: 7074 return ClassDecl->defaultedDestructorIsConstexpr(); 7075 7076 case Sema::CXXInvalid: 7077 return false; 7078 } 7079 7080 // -- if the class is a non-empty union, or for each non-empty anonymous 7081 // union member of a non-union class, exactly one non-static data member 7082 // shall be initialized; [DR1359] 7083 // 7084 // If we squint, this is guaranteed, since exactly one non-static data member 7085 // will be initialized (if the constructor isn't deleted), we just don't know 7086 // which one. 7087 if (Ctor && ClassDecl->isUnion()) 7088 return CSM == Sema::CXXDefaultConstructor 7089 ? ClassDecl->hasInClassInitializer() || 7090 !ClassDecl->hasVariantMembers() 7091 : true; 7092 7093 // -- the class shall not have any virtual base classes; 7094 if (Ctor && ClassDecl->getNumVBases()) 7095 return false; 7096 7097 // C++1y [class.copy]p26: 7098 // -- [the class] is a literal type, and 7099 if (!Ctor && !ClassDecl->isLiteral()) 7100 return false; 7101 7102 // -- every constructor involved in initializing [...] base class 7103 // sub-objects shall be a constexpr constructor; 7104 // -- the assignment operator selected to copy/move each direct base 7105 // class is a constexpr function, and 7106 for (const auto &B : ClassDecl->bases()) { 7107 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 7108 if (!BaseType) continue; 7109 7110 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7111 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 7112 InheritedCtor, Inherited)) 7113 return false; 7114 } 7115 7116 // -- every constructor involved in initializing non-static data members 7117 // [...] shall be a constexpr constructor; 7118 // -- every non-static data member and base class sub-object shall be 7119 // initialized 7120 // -- for each non-static data member of X that is of class type (or array 7121 // thereof), the assignment operator selected to copy/move that member is 7122 // a constexpr function 7123 for (const auto *F : ClassDecl->fields()) { 7124 if (F->isInvalidDecl()) 7125 continue; 7126 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 7127 continue; 7128 QualType BaseType = S.Context.getBaseElementType(F->getType()); 7129 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 7130 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7131 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 7132 BaseType.getCVRQualifiers(), 7133 ConstArg && !F->isMutable())) 7134 return false; 7135 } else if (CSM == Sema::CXXDefaultConstructor) { 7136 return false; 7137 } 7138 } 7139 7140 // All OK, it's constexpr! 7141 return true; 7142 } 7143 7144 namespace { 7145 /// RAII object to register a defaulted function as having its exception 7146 /// specification computed. 7147 struct ComputingExceptionSpec { 7148 Sema &S; 7149 7150 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 7151 : S(S) { 7152 Sema::CodeSynthesisContext Ctx; 7153 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 7154 Ctx.PointOfInstantiation = Loc; 7155 Ctx.Entity = FD; 7156 S.pushCodeSynthesisContext(Ctx); 7157 } 7158 ~ComputingExceptionSpec() { 7159 S.popCodeSynthesisContext(); 7160 } 7161 }; 7162 } 7163 7164 static Sema::ImplicitExceptionSpecification 7165 ComputeDefaultedSpecialMemberExceptionSpec( 7166 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 7167 Sema::InheritedConstructorInfo *ICI); 7168 7169 static Sema::ImplicitExceptionSpecification 7170 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 7171 FunctionDecl *FD, 7172 Sema::DefaultedComparisonKind DCK); 7173 7174 static Sema::ImplicitExceptionSpecification 7175 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 7176 auto DFK = S.getDefaultedFunctionKind(FD); 7177 if (DFK.isSpecialMember()) 7178 return ComputeDefaultedSpecialMemberExceptionSpec( 7179 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 7180 if (DFK.isComparison()) 7181 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 7182 DFK.asComparison()); 7183 7184 auto *CD = cast<CXXConstructorDecl>(FD); 7185 assert(CD->getInheritedConstructor() && 7186 "only defaulted functions and inherited constructors have implicit " 7187 "exception specs"); 7188 Sema::InheritedConstructorInfo ICI( 7189 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 7190 return ComputeDefaultedSpecialMemberExceptionSpec( 7191 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 7192 } 7193 7194 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 7195 CXXMethodDecl *MD) { 7196 FunctionProtoType::ExtProtoInfo EPI; 7197 7198 // Build an exception specification pointing back at this member. 7199 EPI.ExceptionSpec.Type = EST_Unevaluated; 7200 EPI.ExceptionSpec.SourceDecl = MD; 7201 7202 // Set the calling convention to the default for C++ instance methods. 7203 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 7204 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 7205 /*IsCXXMethod=*/true)); 7206 return EPI; 7207 } 7208 7209 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 7210 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 7211 if (FPT->getExceptionSpecType() != EST_Unevaluated) 7212 return; 7213 7214 // Evaluate the exception specification. 7215 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 7216 auto ESI = IES.getExceptionSpec(); 7217 7218 // Update the type of the special member to use it. 7219 UpdateExceptionSpec(FD, ESI); 7220 } 7221 7222 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 7223 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted"); 7224 7225 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 7226 if (!DefKind) { 7227 assert(FD->getDeclContext()->isDependentContext()); 7228 return; 7229 } 7230 7231 if (DefKind.isSpecialMember() 7232 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 7233 DefKind.asSpecialMember()) 7234 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 7235 FD->setInvalidDecl(); 7236 } 7237 7238 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7239 CXXSpecialMember CSM) { 7240 CXXRecordDecl *RD = MD->getParent(); 7241 7242 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 7243 "not an explicitly-defaulted special member"); 7244 7245 // Defer all checking for special members of a dependent type. 7246 if (RD->isDependentType()) 7247 return false; 7248 7249 // Whether this was the first-declared instance of the constructor. 7250 // This affects whether we implicitly add an exception spec and constexpr. 7251 bool First = MD == MD->getCanonicalDecl(); 7252 7253 bool HadError = false; 7254 7255 // C++11 [dcl.fct.def.default]p1: 7256 // A function that is explicitly defaulted shall 7257 // -- be a special member function [...] (checked elsewhere), 7258 // -- have the same type (except for ref-qualifiers, and except that a 7259 // copy operation can take a non-const reference) as an implicit 7260 // declaration, and 7261 // -- not have default arguments. 7262 // C++2a changes the second bullet to instead delete the function if it's 7263 // defaulted on its first declaration, unless it's "an assignment operator, 7264 // and its return type differs or its parameter type is not a reference". 7265 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First; 7266 bool ShouldDeleteForTypeMismatch = false; 7267 unsigned ExpectedParams = 1; 7268 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 7269 ExpectedParams = 0; 7270 if (MD->getNumParams() != ExpectedParams) { 7271 // This checks for default arguments: a copy or move constructor with a 7272 // default argument is classified as a default constructor, and assignment 7273 // operations and destructors can't have default arguments. 7274 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 7275 << CSM << MD->getSourceRange(); 7276 HadError = true; 7277 } else if (MD->isVariadic()) { 7278 if (DeleteOnTypeMismatch) 7279 ShouldDeleteForTypeMismatch = true; 7280 else { 7281 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 7282 << CSM << MD->getSourceRange(); 7283 HadError = true; 7284 } 7285 } 7286 7287 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 7288 7289 bool CanHaveConstParam = false; 7290 if (CSM == CXXCopyConstructor) 7291 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 7292 else if (CSM == CXXCopyAssignment) 7293 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 7294 7295 QualType ReturnType = Context.VoidTy; 7296 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 7297 // Check for return type matching. 7298 ReturnType = Type->getReturnType(); 7299 7300 QualType DeclType = Context.getTypeDeclType(RD); 7301 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 7302 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 7303 7304 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 7305 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 7306 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 7307 HadError = true; 7308 } 7309 7310 // A defaulted special member cannot have cv-qualifiers. 7311 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 7312 if (DeleteOnTypeMismatch) 7313 ShouldDeleteForTypeMismatch = true; 7314 else { 7315 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 7316 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 7317 HadError = true; 7318 } 7319 } 7320 } 7321 7322 // Check for parameter type matching. 7323 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 7324 bool HasConstParam = false; 7325 if (ExpectedParams && ArgType->isReferenceType()) { 7326 // Argument must be reference to possibly-const T. 7327 QualType ReferentType = ArgType->getPointeeType(); 7328 HasConstParam = ReferentType.isConstQualified(); 7329 7330 if (ReferentType.isVolatileQualified()) { 7331 if (DeleteOnTypeMismatch) 7332 ShouldDeleteForTypeMismatch = true; 7333 else { 7334 Diag(MD->getLocation(), 7335 diag::err_defaulted_special_member_volatile_param) << CSM; 7336 HadError = true; 7337 } 7338 } 7339 7340 if (HasConstParam && !CanHaveConstParam) { 7341 if (DeleteOnTypeMismatch) 7342 ShouldDeleteForTypeMismatch = true; 7343 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7344 Diag(MD->getLocation(), 7345 diag::err_defaulted_special_member_copy_const_param) 7346 << (CSM == CXXCopyAssignment); 7347 // FIXME: Explain why this special member can't be const. 7348 HadError = true; 7349 } else { 7350 Diag(MD->getLocation(), 7351 diag::err_defaulted_special_member_move_const_param) 7352 << (CSM == CXXMoveAssignment); 7353 HadError = true; 7354 } 7355 } 7356 } else if (ExpectedParams) { 7357 // A copy assignment operator can take its argument by value, but a 7358 // defaulted one cannot. 7359 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 7360 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7361 HadError = true; 7362 } 7363 7364 // C++11 [dcl.fct.def.default]p2: 7365 // An explicitly-defaulted function may be declared constexpr only if it 7366 // would have been implicitly declared as constexpr, 7367 // Do not apply this rule to members of class templates, since core issue 1358 7368 // makes such functions always instantiate to constexpr functions. For 7369 // functions which cannot be constexpr (for non-constructors in C++11 and for 7370 // destructors in C++14 and C++17), this is checked elsewhere. 7371 // 7372 // FIXME: This should not apply if the member is deleted. 7373 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7374 HasConstParam); 7375 if ((getLangOpts().CPlusPlus20 || 7376 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7377 : isa<CXXConstructorDecl>(MD))) && 7378 MD->isConstexpr() && !Constexpr && 7379 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7380 Diag(MD->getBeginLoc(), MD->isConsteval() 7381 ? diag::err_incorrect_defaulted_consteval 7382 : diag::err_incorrect_defaulted_constexpr) 7383 << CSM; 7384 // FIXME: Explain why the special member can't be constexpr. 7385 HadError = true; 7386 } 7387 7388 if (First) { 7389 // C++2a [dcl.fct.def.default]p3: 7390 // If a function is explicitly defaulted on its first declaration, it is 7391 // implicitly considered to be constexpr if the implicit declaration 7392 // would be. 7393 MD->setConstexprKind(Constexpr ? (MD->isConsteval() 7394 ? ConstexprSpecKind::Consteval 7395 : ConstexprSpecKind::Constexpr) 7396 : ConstexprSpecKind::Unspecified); 7397 7398 if (!Type->hasExceptionSpec()) { 7399 // C++2a [except.spec]p3: 7400 // If a declaration of a function does not have a noexcept-specifier 7401 // [and] is defaulted on its first declaration, [...] the exception 7402 // specification is as specified below 7403 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7404 EPI.ExceptionSpec.Type = EST_Unevaluated; 7405 EPI.ExceptionSpec.SourceDecl = MD; 7406 MD->setType(Context.getFunctionType(ReturnType, 7407 llvm::makeArrayRef(&ArgType, 7408 ExpectedParams), 7409 EPI)); 7410 } 7411 } 7412 7413 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7414 if (First) { 7415 SetDeclDeleted(MD, MD->getLocation()); 7416 if (!inTemplateInstantiation() && !HadError) { 7417 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7418 if (ShouldDeleteForTypeMismatch) { 7419 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7420 } else { 7421 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7422 } 7423 } 7424 if (ShouldDeleteForTypeMismatch && !HadError) { 7425 Diag(MD->getLocation(), 7426 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7427 } 7428 } else { 7429 // C++11 [dcl.fct.def.default]p4: 7430 // [For a] user-provided explicitly-defaulted function [...] if such a 7431 // function is implicitly defined as deleted, the program is ill-formed. 7432 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7433 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 7434 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7435 HadError = true; 7436 } 7437 } 7438 7439 return HadError; 7440 } 7441 7442 namespace { 7443 /// Helper class for building and checking a defaulted comparison. 7444 /// 7445 /// Defaulted functions are built in two phases: 7446 /// 7447 /// * First, the set of operations that the function will perform are 7448 /// identified, and some of them are checked. If any of the checked 7449 /// operations is invalid in certain ways, the comparison function is 7450 /// defined as deleted and no body is built. 7451 /// * Then, if the function is not defined as deleted, the body is built. 7452 /// 7453 /// This is accomplished by performing two visitation steps over the eventual 7454 /// body of the function. 7455 template<typename Derived, typename ResultList, typename Result, 7456 typename Subobject> 7457 class DefaultedComparisonVisitor { 7458 public: 7459 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7460 7461 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7462 DefaultedComparisonKind DCK) 7463 : S(S), RD(RD), FD(FD), DCK(DCK) { 7464 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7465 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7466 // UnresolvedSet to avoid this copy. 7467 Fns.assign(Info->getUnqualifiedLookups().begin(), 7468 Info->getUnqualifiedLookups().end()); 7469 } 7470 } 7471 7472 ResultList visit() { 7473 // The type of an lvalue naming a parameter of this function. 7474 QualType ParamLvalType = 7475 FD->getParamDecl(0)->getType().getNonReferenceType(); 7476 7477 ResultList Results; 7478 7479 switch (DCK) { 7480 case DefaultedComparisonKind::None: 7481 llvm_unreachable("not a defaulted comparison"); 7482 7483 case DefaultedComparisonKind::Equal: 7484 case DefaultedComparisonKind::ThreeWay: 7485 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7486 return Results; 7487 7488 case DefaultedComparisonKind::NotEqual: 7489 case DefaultedComparisonKind::Relational: 7490 Results.add(getDerived().visitExpandedSubobject( 7491 ParamLvalType, getDerived().getCompleteObject())); 7492 return Results; 7493 } 7494 llvm_unreachable(""); 7495 } 7496 7497 protected: 7498 Derived &getDerived() { return static_cast<Derived&>(*this); } 7499 7500 /// Visit the expanded list of subobjects of the given type, as specified in 7501 /// C++2a [class.compare.default]. 7502 /// 7503 /// \return \c true if the ResultList object said we're done, \c false if not. 7504 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7505 Qualifiers Quals) { 7506 // C++2a [class.compare.default]p4: 7507 // The direct base class subobjects of C 7508 for (CXXBaseSpecifier &Base : Record->bases()) 7509 if (Results.add(getDerived().visitSubobject( 7510 S.Context.getQualifiedType(Base.getType(), Quals), 7511 getDerived().getBase(&Base)))) 7512 return true; 7513 7514 // followed by the non-static data members of C 7515 for (FieldDecl *Field : Record->fields()) { 7516 // Recursively expand anonymous structs. 7517 if (Field->isAnonymousStructOrUnion()) { 7518 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7519 Quals)) 7520 return true; 7521 continue; 7522 } 7523 7524 // Figure out the type of an lvalue denoting this field. 7525 Qualifiers FieldQuals = Quals; 7526 if (Field->isMutable()) 7527 FieldQuals.removeConst(); 7528 QualType FieldType = 7529 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7530 7531 if (Results.add(getDerived().visitSubobject( 7532 FieldType, getDerived().getField(Field)))) 7533 return true; 7534 } 7535 7536 // form a list of subobjects. 7537 return false; 7538 } 7539 7540 Result visitSubobject(QualType Type, Subobject Subobj) { 7541 // In that list, any subobject of array type is recursively expanded 7542 const ArrayType *AT = S.Context.getAsArrayType(Type); 7543 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7544 return getDerived().visitSubobjectArray(CAT->getElementType(), 7545 CAT->getSize(), Subobj); 7546 return getDerived().visitExpandedSubobject(Type, Subobj); 7547 } 7548 7549 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7550 Subobject Subobj) { 7551 return getDerived().visitSubobject(Type, Subobj); 7552 } 7553 7554 protected: 7555 Sema &S; 7556 CXXRecordDecl *RD; 7557 FunctionDecl *FD; 7558 DefaultedComparisonKind DCK; 7559 UnresolvedSet<16> Fns; 7560 }; 7561 7562 /// Information about a defaulted comparison, as determined by 7563 /// DefaultedComparisonAnalyzer. 7564 struct DefaultedComparisonInfo { 7565 bool Deleted = false; 7566 bool Constexpr = true; 7567 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7568 7569 static DefaultedComparisonInfo deleted() { 7570 DefaultedComparisonInfo Deleted; 7571 Deleted.Deleted = true; 7572 return Deleted; 7573 } 7574 7575 bool add(const DefaultedComparisonInfo &R) { 7576 Deleted |= R.Deleted; 7577 Constexpr &= R.Constexpr; 7578 Category = commonComparisonType(Category, R.Category); 7579 return Deleted; 7580 } 7581 }; 7582 7583 /// An element in the expanded list of subobjects of a defaulted comparison, as 7584 /// specified in C++2a [class.compare.default]p4. 7585 struct DefaultedComparisonSubobject { 7586 enum { CompleteObject, Member, Base } Kind; 7587 NamedDecl *Decl; 7588 SourceLocation Loc; 7589 }; 7590 7591 /// A visitor over the notional body of a defaulted comparison that determines 7592 /// whether that body would be deleted or constexpr. 7593 class DefaultedComparisonAnalyzer 7594 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7595 DefaultedComparisonInfo, 7596 DefaultedComparisonInfo, 7597 DefaultedComparisonSubobject> { 7598 public: 7599 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7600 7601 private: 7602 DiagnosticKind Diagnose; 7603 7604 public: 7605 using Base = DefaultedComparisonVisitor; 7606 using Result = DefaultedComparisonInfo; 7607 using Subobject = DefaultedComparisonSubobject; 7608 7609 friend Base; 7610 7611 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7612 DefaultedComparisonKind DCK, 7613 DiagnosticKind Diagnose = NoDiagnostics) 7614 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7615 7616 Result visit() { 7617 if ((DCK == DefaultedComparisonKind::Equal || 7618 DCK == DefaultedComparisonKind::ThreeWay) && 7619 RD->hasVariantMembers()) { 7620 // C++2a [class.compare.default]p2 [P2002R0]: 7621 // A defaulted comparison operator function for class C is defined as 7622 // deleted if [...] C has variant members. 7623 if (Diagnose == ExplainDeleted) { 7624 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7625 << FD << RD->isUnion() << RD; 7626 } 7627 return Result::deleted(); 7628 } 7629 7630 return Base::visit(); 7631 } 7632 7633 private: 7634 Subobject getCompleteObject() { 7635 return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()}; 7636 } 7637 7638 Subobject getBase(CXXBaseSpecifier *Base) { 7639 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7640 Base->getBaseTypeLoc()}; 7641 } 7642 7643 Subobject getField(FieldDecl *Field) { 7644 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7645 } 7646 7647 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7648 // C++2a [class.compare.default]p2 [P2002R0]: 7649 // A defaulted <=> or == operator function for class C is defined as 7650 // deleted if any non-static data member of C is of reference type 7651 if (Type->isReferenceType()) { 7652 if (Diagnose == ExplainDeleted) { 7653 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7654 << FD << RD; 7655 } 7656 return Result::deleted(); 7657 } 7658 7659 // [...] Let xi be an lvalue denoting the ith element [...] 7660 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7661 Expr *Args[] = {&Xi, &Xi}; 7662 7663 // All operators start by trying to apply that same operator recursively. 7664 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7665 assert(OO != OO_None && "not an overloaded operator!"); 7666 return visitBinaryOperator(OO, Args, Subobj); 7667 } 7668 7669 Result 7670 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7671 Subobject Subobj, 7672 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7673 // Note that there is no need to consider rewritten candidates here if 7674 // we've already found there is no viable 'operator<=>' candidate (and are 7675 // considering synthesizing a '<=>' from '==' and '<'). 7676 OverloadCandidateSet CandidateSet( 7677 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7678 OverloadCandidateSet::OperatorRewriteInfo( 7679 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7680 7681 /// C++2a [class.compare.default]p1 [P2002R0]: 7682 /// [...] the defaulted function itself is never a candidate for overload 7683 /// resolution [...] 7684 CandidateSet.exclude(FD); 7685 7686 if (Args[0]->getType()->isOverloadableType()) 7687 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7688 else if (OO == OO_EqualEqual || 7689 !Args[0]->getType()->isFunctionPointerType()) { 7690 // FIXME: We determine whether this is a valid expression by checking to 7691 // see if there's a viable builtin operator candidate for it. That isn't 7692 // really what the rules ask us to do, but should give the right results. 7693 // 7694 // Note that the builtin operator for relational comparisons on function 7695 // pointers is the only known case which cannot be used. 7696 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet); 7697 } 7698 7699 Result R; 7700 7701 OverloadCandidateSet::iterator Best; 7702 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7703 case OR_Success: { 7704 // C++2a [class.compare.secondary]p2 [P2002R0]: 7705 // The operator function [...] is defined as deleted if [...] the 7706 // candidate selected by overload resolution is not a rewritten 7707 // candidate. 7708 if ((DCK == DefaultedComparisonKind::NotEqual || 7709 DCK == DefaultedComparisonKind::Relational) && 7710 !Best->RewriteKind) { 7711 if (Diagnose == ExplainDeleted) { 7712 S.Diag(Best->Function->getLocation(), 7713 diag::note_defaulted_comparison_not_rewritten_callee) 7714 << FD; 7715 } 7716 return Result::deleted(); 7717 } 7718 7719 // Throughout C++2a [class.compare]: if overload resolution does not 7720 // result in a usable function, the candidate function is defined as 7721 // deleted. This requires that we selected an accessible function. 7722 // 7723 // Note that this only considers the access of the function when named 7724 // within the type of the subobject, and not the access path for any 7725 // derived-to-base conversion. 7726 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7727 if (ArgClass && Best->FoundDecl.getDecl() && 7728 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7729 QualType ObjectType = Subobj.Kind == Subobject::Member 7730 ? Args[0]->getType() 7731 : S.Context.getRecordType(RD); 7732 if (!S.isMemberAccessibleForDeletion( 7733 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7734 Diagnose == ExplainDeleted 7735 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7736 << FD << Subobj.Kind << Subobj.Decl 7737 : S.PDiag())) 7738 return Result::deleted(); 7739 } 7740 7741 // C++2a [class.compare.default]p3 [P2002R0]: 7742 // A defaulted comparison function is constexpr-compatible if [...] 7743 // no overlod resolution performed [...] results in a non-constexpr 7744 // function. 7745 if (FunctionDecl *BestFD = Best->Function) { 7746 assert(!BestFD->isDeleted() && "wrong overload resolution result"); 7747 // If it's not constexpr, explain why not. 7748 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 7749 if (Subobj.Kind != Subobject::CompleteObject) 7750 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7751 << Subobj.Kind << Subobj.Decl; 7752 S.Diag(BestFD->getLocation(), 7753 diag::note_defaulted_comparison_not_constexpr_here); 7754 // Bail out after explaining; we don't want any more notes. 7755 return Result::deleted(); 7756 } 7757 R.Constexpr &= BestFD->isConstexpr(); 7758 } 7759 7760 if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) { 7761 if (auto *BestFD = Best->Function) { 7762 // If any callee has an undeduced return type, deduce it now. 7763 // FIXME: It's not clear how a failure here should be handled. For 7764 // now, we produce an eager diagnostic, because that is forward 7765 // compatible with most (all?) other reasonable options. 7766 if (BestFD->getReturnType()->isUndeducedType() && 7767 S.DeduceReturnType(BestFD, FD->getLocation(), 7768 /*Diagnose=*/false)) { 7769 // Don't produce a duplicate error when asked to explain why the 7770 // comparison is deleted: we diagnosed that when initially checking 7771 // the defaulted operator. 7772 if (Diagnose == NoDiagnostics) { 7773 S.Diag( 7774 FD->getLocation(), 7775 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) 7776 << Subobj.Kind << Subobj.Decl; 7777 S.Diag( 7778 Subobj.Loc, 7779 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) 7780 << Subobj.Kind << Subobj.Decl; 7781 S.Diag(BestFD->getLocation(), 7782 diag::note_defaulted_comparison_cannot_deduce_callee) 7783 << Subobj.Kind << Subobj.Decl; 7784 } 7785 return Result::deleted(); 7786 } 7787 if (auto *Info = S.Context.CompCategories.lookupInfoForType( 7788 BestFD->getCallResultType())) { 7789 R.Category = Info->Kind; 7790 } else { 7791 if (Diagnose == ExplainDeleted) { 7792 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 7793 << Subobj.Kind << Subobj.Decl 7794 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 7795 S.Diag(BestFD->getLocation(), 7796 diag::note_defaulted_comparison_cannot_deduce_callee) 7797 << Subobj.Kind << Subobj.Decl; 7798 } 7799 return Result::deleted(); 7800 } 7801 } else { 7802 Optional<ComparisonCategoryType> Cat = 7803 getComparisonCategoryForBuiltinCmp(Args[0]->getType()); 7804 assert(Cat && "no category for builtin comparison?"); 7805 R.Category = *Cat; 7806 } 7807 } 7808 7809 // Note that we might be rewriting to a different operator. That call is 7810 // not considered until we come to actually build the comparison function. 7811 break; 7812 } 7813 7814 case OR_Ambiguous: 7815 if (Diagnose == ExplainDeleted) { 7816 unsigned Kind = 0; 7817 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 7818 Kind = OO == OO_EqualEqual ? 1 : 2; 7819 CandidateSet.NoteCandidates( 7820 PartialDiagnosticAt( 7821 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 7822 << FD << Kind << Subobj.Kind << Subobj.Decl), 7823 S, OCD_AmbiguousCandidates, Args); 7824 } 7825 R = Result::deleted(); 7826 break; 7827 7828 case OR_Deleted: 7829 if (Diagnose == ExplainDeleted) { 7830 if ((DCK == DefaultedComparisonKind::NotEqual || 7831 DCK == DefaultedComparisonKind::Relational) && 7832 !Best->RewriteKind) { 7833 S.Diag(Best->Function->getLocation(), 7834 diag::note_defaulted_comparison_not_rewritten_callee) 7835 << FD; 7836 } else { 7837 S.Diag(Subobj.Loc, 7838 diag::note_defaulted_comparison_calls_deleted) 7839 << FD << Subobj.Kind << Subobj.Decl; 7840 S.NoteDeletedFunction(Best->Function); 7841 } 7842 } 7843 R = Result::deleted(); 7844 break; 7845 7846 case OR_No_Viable_Function: 7847 // If there's no usable candidate, we're done unless we can rewrite a 7848 // '<=>' in terms of '==' and '<'. 7849 if (OO == OO_Spaceship && 7850 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 7851 // For any kind of comparison category return type, we need a usable 7852 // '==' and a usable '<'. 7853 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 7854 &CandidateSet))) 7855 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 7856 break; 7857 } 7858 7859 if (Diagnose == ExplainDeleted) { 7860 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 7861 << FD << Subobj.Kind << Subobj.Decl; 7862 7863 // For a three-way comparison, list both the candidates for the 7864 // original operator and the candidates for the synthesized operator. 7865 if (SpaceshipCandidates) { 7866 SpaceshipCandidates->NoteCandidates( 7867 S, Args, 7868 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 7869 Args, FD->getLocation())); 7870 S.Diag(Subobj.Loc, 7871 diag::note_defaulted_comparison_no_viable_function_synthesized) 7872 << (OO == OO_EqualEqual ? 0 : 1); 7873 } 7874 7875 CandidateSet.NoteCandidates( 7876 S, Args, 7877 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 7878 FD->getLocation())); 7879 } 7880 R = Result::deleted(); 7881 break; 7882 } 7883 7884 return R; 7885 } 7886 }; 7887 7888 /// A list of statements. 7889 struct StmtListResult { 7890 bool IsInvalid = false; 7891 llvm::SmallVector<Stmt*, 16> Stmts; 7892 7893 bool add(const StmtResult &S) { 7894 IsInvalid |= S.isInvalid(); 7895 if (IsInvalid) 7896 return true; 7897 Stmts.push_back(S.get()); 7898 return false; 7899 } 7900 }; 7901 7902 /// A visitor over the notional body of a defaulted comparison that synthesizes 7903 /// the actual body. 7904 class DefaultedComparisonSynthesizer 7905 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 7906 StmtListResult, StmtResult, 7907 std::pair<ExprResult, ExprResult>> { 7908 SourceLocation Loc; 7909 unsigned ArrayDepth = 0; 7910 7911 public: 7912 using Base = DefaultedComparisonVisitor; 7913 using ExprPair = std::pair<ExprResult, ExprResult>; 7914 7915 friend Base; 7916 7917 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7918 DefaultedComparisonKind DCK, 7919 SourceLocation BodyLoc) 7920 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 7921 7922 /// Build a suitable function body for this defaulted comparison operator. 7923 StmtResult build() { 7924 Sema::CompoundScopeRAII CompoundScope(S); 7925 7926 StmtListResult Stmts = visit(); 7927 if (Stmts.IsInvalid) 7928 return StmtError(); 7929 7930 ExprResult RetVal; 7931 switch (DCK) { 7932 case DefaultedComparisonKind::None: 7933 llvm_unreachable("not a defaulted comparison"); 7934 7935 case DefaultedComparisonKind::Equal: { 7936 // C++2a [class.eq]p3: 7937 // [...] compar[e] the corresponding elements [...] until the first 7938 // index i where xi == yi yields [...] false. If no such index exists, 7939 // V is true. Otherwise, V is false. 7940 // 7941 // Join the comparisons with '&&'s and return the result. Use a right 7942 // fold (traversing the conditions right-to-left), because that 7943 // short-circuits more naturally. 7944 auto OldStmts = std::move(Stmts.Stmts); 7945 Stmts.Stmts.clear(); 7946 ExprResult CmpSoFar; 7947 // Finish a particular comparison chain. 7948 auto FinishCmp = [&] { 7949 if (Expr *Prior = CmpSoFar.get()) { 7950 // Convert the last expression to 'return ...;' 7951 if (RetVal.isUnset() && Stmts.Stmts.empty()) 7952 RetVal = CmpSoFar; 7953 // Convert any prior comparison to 'if (!(...)) return false;' 7954 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 7955 return true; 7956 CmpSoFar = ExprResult(); 7957 } 7958 return false; 7959 }; 7960 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 7961 Expr *E = dyn_cast<Expr>(EAsStmt); 7962 if (!E) { 7963 // Found an array comparison. 7964 if (FinishCmp() || Stmts.add(EAsStmt)) 7965 return StmtError(); 7966 continue; 7967 } 7968 7969 if (CmpSoFar.isUnset()) { 7970 CmpSoFar = E; 7971 continue; 7972 } 7973 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 7974 if (CmpSoFar.isInvalid()) 7975 return StmtError(); 7976 } 7977 if (FinishCmp()) 7978 return StmtError(); 7979 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 7980 // If no such index exists, V is true. 7981 if (RetVal.isUnset()) 7982 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 7983 break; 7984 } 7985 7986 case DefaultedComparisonKind::ThreeWay: { 7987 // Per C++2a [class.spaceship]p3, as a fallback add: 7988 // return static_cast<R>(std::strong_ordering::equal); 7989 QualType StrongOrdering = S.CheckComparisonCategoryType( 7990 ComparisonCategoryType::StrongOrdering, Loc, 7991 Sema::ComparisonCategoryUsage::DefaultedOperator); 7992 if (StrongOrdering.isNull()) 7993 return StmtError(); 7994 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 7995 .getValueInfo(ComparisonCategoryResult::Equal) 7996 ->VD; 7997 RetVal = getDecl(EqualVD); 7998 if (RetVal.isInvalid()) 7999 return StmtError(); 8000 RetVal = buildStaticCastToR(RetVal.get()); 8001 break; 8002 } 8003 8004 case DefaultedComparisonKind::NotEqual: 8005 case DefaultedComparisonKind::Relational: 8006 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 8007 break; 8008 } 8009 8010 // Build the final return statement. 8011 if (RetVal.isInvalid()) 8012 return StmtError(); 8013 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 8014 if (ReturnStmt.isInvalid()) 8015 return StmtError(); 8016 Stmts.Stmts.push_back(ReturnStmt.get()); 8017 8018 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 8019 } 8020 8021 private: 8022 ExprResult getDecl(ValueDecl *VD) { 8023 return S.BuildDeclarationNameExpr( 8024 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 8025 } 8026 8027 ExprResult getParam(unsigned I) { 8028 ParmVarDecl *PD = FD->getParamDecl(I); 8029 return getDecl(PD); 8030 } 8031 8032 ExprPair getCompleteObject() { 8033 unsigned Param = 0; 8034 ExprResult LHS; 8035 if (isa<CXXMethodDecl>(FD)) { 8036 // LHS is '*this'. 8037 LHS = S.ActOnCXXThis(Loc); 8038 if (!LHS.isInvalid()) 8039 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 8040 } else { 8041 LHS = getParam(Param++); 8042 } 8043 ExprResult RHS = getParam(Param++); 8044 assert(Param == FD->getNumParams()); 8045 return {LHS, RHS}; 8046 } 8047 8048 ExprPair getBase(CXXBaseSpecifier *Base) { 8049 ExprPair Obj = getCompleteObject(); 8050 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8051 return {ExprError(), ExprError()}; 8052 CXXCastPath Path = {Base}; 8053 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 8054 CK_DerivedToBase, VK_LValue, &Path), 8055 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 8056 CK_DerivedToBase, VK_LValue, &Path)}; 8057 } 8058 8059 ExprPair getField(FieldDecl *Field) { 8060 ExprPair Obj = getCompleteObject(); 8061 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8062 return {ExprError(), ExprError()}; 8063 8064 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 8065 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 8066 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 8067 CXXScopeSpec(), Field, Found, NameInfo), 8068 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 8069 CXXScopeSpec(), Field, Found, NameInfo)}; 8070 } 8071 8072 // FIXME: When expanding a subobject, register a note in the code synthesis 8073 // stack to say which subobject we're comparing. 8074 8075 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 8076 if (Cond.isInvalid()) 8077 return StmtError(); 8078 8079 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 8080 if (NotCond.isInvalid()) 8081 return StmtError(); 8082 8083 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 8084 assert(!False.isInvalid() && "should never fail"); 8085 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 8086 if (ReturnFalse.isInvalid()) 8087 return StmtError(); 8088 8089 return S.ActOnIfStmt(Loc, false, Loc, nullptr, 8090 S.ActOnCondition(nullptr, Loc, NotCond.get(), 8091 Sema::ConditionKind::Boolean), 8092 Loc, ReturnFalse.get(), SourceLocation(), nullptr); 8093 } 8094 8095 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 8096 ExprPair Subobj) { 8097 QualType SizeType = S.Context.getSizeType(); 8098 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 8099 8100 // Build 'size_t i$n = 0'. 8101 IdentifierInfo *IterationVarName = nullptr; 8102 { 8103 SmallString<8> Str; 8104 llvm::raw_svector_ostream OS(Str); 8105 OS << "i" << ArrayDepth; 8106 IterationVarName = &S.Context.Idents.get(OS.str()); 8107 } 8108 VarDecl *IterationVar = VarDecl::Create( 8109 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 8110 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 8111 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8112 IterationVar->setInit( 8113 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8114 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 8115 8116 auto IterRef = [&] { 8117 ExprResult Ref = S.BuildDeclarationNameExpr( 8118 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 8119 IterationVar); 8120 assert(!Ref.isInvalid() && "can't reference our own variable?"); 8121 return Ref.get(); 8122 }; 8123 8124 // Build 'i$n != Size'. 8125 ExprResult Cond = S.CreateBuiltinBinOp( 8126 Loc, BO_NE, IterRef(), 8127 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 8128 assert(!Cond.isInvalid() && "should never fail"); 8129 8130 // Build '++i$n'. 8131 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 8132 assert(!Inc.isInvalid() && "should never fail"); 8133 8134 // Build 'a[i$n]' and 'b[i$n]'. 8135 auto Index = [&](ExprResult E) { 8136 if (E.isInvalid()) 8137 return ExprError(); 8138 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 8139 }; 8140 Subobj.first = Index(Subobj.first); 8141 Subobj.second = Index(Subobj.second); 8142 8143 // Compare the array elements. 8144 ++ArrayDepth; 8145 StmtResult Substmt = visitSubobject(Type, Subobj); 8146 --ArrayDepth; 8147 8148 if (Substmt.isInvalid()) 8149 return StmtError(); 8150 8151 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 8152 // For outer levels or for an 'operator<=>' we already have a suitable 8153 // statement that returns as necessary. 8154 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 8155 assert(DCK == DefaultedComparisonKind::Equal && 8156 "should have non-expression statement"); 8157 Substmt = buildIfNotCondReturnFalse(ElemCmp); 8158 if (Substmt.isInvalid()) 8159 return StmtError(); 8160 } 8161 8162 // Build 'for (...) ...' 8163 return S.ActOnForStmt(Loc, Loc, Init, 8164 S.ActOnCondition(nullptr, Loc, Cond.get(), 8165 Sema::ConditionKind::Boolean), 8166 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 8167 Substmt.get()); 8168 } 8169 8170 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 8171 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8172 return StmtError(); 8173 8174 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 8175 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); 8176 ExprResult Op; 8177 if (Type->isOverloadableType()) 8178 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(), 8179 Obj.second.get(), /*PerformADL=*/true, 8180 /*AllowRewrittenCandidates=*/true, FD); 8181 else 8182 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get()); 8183 if (Op.isInvalid()) 8184 return StmtError(); 8185 8186 switch (DCK) { 8187 case DefaultedComparisonKind::None: 8188 llvm_unreachable("not a defaulted comparison"); 8189 8190 case DefaultedComparisonKind::Equal: 8191 // Per C++2a [class.eq]p2, each comparison is individually contextually 8192 // converted to bool. 8193 Op = S.PerformContextuallyConvertToBool(Op.get()); 8194 if (Op.isInvalid()) 8195 return StmtError(); 8196 return Op.get(); 8197 8198 case DefaultedComparisonKind::ThreeWay: { 8199 // Per C++2a [class.spaceship]p3, form: 8200 // if (R cmp = static_cast<R>(op); cmp != 0) 8201 // return cmp; 8202 QualType R = FD->getReturnType(); 8203 Op = buildStaticCastToR(Op.get()); 8204 if (Op.isInvalid()) 8205 return StmtError(); 8206 8207 // R cmp = ...; 8208 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 8209 VarDecl *VD = 8210 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 8211 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 8212 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 8213 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 8214 8215 // cmp != 0 8216 ExprResult VDRef = getDecl(VD); 8217 if (VDRef.isInvalid()) 8218 return StmtError(); 8219 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 8220 Expr *Zero = 8221 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 8222 ExprResult Comp; 8223 if (VDRef.get()->getType()->isOverloadableType()) 8224 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true, 8225 true, FD); 8226 else 8227 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero); 8228 if (Comp.isInvalid()) 8229 return StmtError(); 8230 Sema::ConditionResult Cond = S.ActOnCondition( 8231 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 8232 if (Cond.isInvalid()) 8233 return StmtError(); 8234 8235 // return cmp; 8236 VDRef = getDecl(VD); 8237 if (VDRef.isInvalid()) 8238 return StmtError(); 8239 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 8240 if (ReturnStmt.isInvalid()) 8241 return StmtError(); 8242 8243 // if (...) 8244 return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc, 8245 ReturnStmt.get(), 8246 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr); 8247 } 8248 8249 case DefaultedComparisonKind::NotEqual: 8250 case DefaultedComparisonKind::Relational: 8251 // C++2a [class.compare.secondary]p2: 8252 // Otherwise, the operator function yields x @ y. 8253 return Op.get(); 8254 } 8255 llvm_unreachable(""); 8256 } 8257 8258 /// Build "static_cast<R>(E)". 8259 ExprResult buildStaticCastToR(Expr *E) { 8260 QualType R = FD->getReturnType(); 8261 assert(!R->isUndeducedType() && "type should have been deduced already"); 8262 8263 // Don't bother forming a no-op cast in the common case. 8264 if (E->isRValue() && S.Context.hasSameType(E->getType(), R)) 8265 return E; 8266 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 8267 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 8268 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 8269 } 8270 }; 8271 } 8272 8273 /// Perform the unqualified lookups that might be needed to form a defaulted 8274 /// comparison function for the given operator. 8275 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 8276 UnresolvedSetImpl &Operators, 8277 OverloadedOperatorKind Op) { 8278 auto Lookup = [&](OverloadedOperatorKind OO) { 8279 Self.LookupOverloadedOperatorName(OO, S, Operators); 8280 }; 8281 8282 // Every defaulted operator looks up itself. 8283 Lookup(Op); 8284 // ... and the rewritten form of itself, if any. 8285 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 8286 Lookup(ExtraOp); 8287 8288 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 8289 // synthesize a three-way comparison from '<' and '=='. In a dependent 8290 // context, we also need to look up '==' in case we implicitly declare a 8291 // defaulted 'operator=='. 8292 if (Op == OO_Spaceship) { 8293 Lookup(OO_ExclaimEqual); 8294 Lookup(OO_Less); 8295 Lookup(OO_EqualEqual); 8296 } 8297 } 8298 8299 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 8300 DefaultedComparisonKind DCK) { 8301 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison"); 8302 8303 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 8304 assert(RD && "defaulted comparison is not defaulted in a class"); 8305 8306 // Perform any unqualified lookups we're going to need to default this 8307 // function. 8308 if (S) { 8309 UnresolvedSet<32> Operators; 8310 lookupOperatorsForDefaultedComparison(*this, S, Operators, 8311 FD->getOverloadedOperator()); 8312 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 8313 Context, Operators.pairs())); 8314 } 8315 8316 // C++2a [class.compare.default]p1: 8317 // A defaulted comparison operator function for some class C shall be a 8318 // non-template function declared in the member-specification of C that is 8319 // -- a non-static const member of C having one parameter of type 8320 // const C&, or 8321 // -- a friend of C having two parameters of type const C& or two 8322 // parameters of type C. 8323 QualType ExpectedParmType1 = Context.getRecordType(RD); 8324 QualType ExpectedParmType2 = 8325 Context.getLValueReferenceType(ExpectedParmType1.withConst()); 8326 if (isa<CXXMethodDecl>(FD)) 8327 ExpectedParmType1 = ExpectedParmType2; 8328 for (const ParmVarDecl *Param : FD->parameters()) { 8329 if (!Param->getType()->isDependentType() && 8330 !Context.hasSameType(Param->getType(), ExpectedParmType1) && 8331 !Context.hasSameType(Param->getType(), ExpectedParmType2)) { 8332 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8333 // corresponding defaulted 'operator<=>' already. 8334 if (!FD->isImplicit()) { 8335 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 8336 << (int)DCK << Param->getType() << ExpectedParmType1 8337 << !isa<CXXMethodDecl>(FD) 8338 << ExpectedParmType2 << Param->getSourceRange(); 8339 } 8340 return true; 8341 } 8342 } 8343 if (FD->getNumParams() == 2 && 8344 !Context.hasSameType(FD->getParamDecl(0)->getType(), 8345 FD->getParamDecl(1)->getType())) { 8346 if (!FD->isImplicit()) { 8347 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 8348 << (int)DCK 8349 << FD->getParamDecl(0)->getType() 8350 << FD->getParamDecl(0)->getSourceRange() 8351 << FD->getParamDecl(1)->getType() 8352 << FD->getParamDecl(1)->getSourceRange(); 8353 } 8354 return true; 8355 } 8356 8357 // ... non-static const member ... 8358 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 8359 assert(!MD->isStatic() && "comparison function cannot be a static member"); 8360 if (!MD->isConst()) { 8361 SourceLocation InsertLoc; 8362 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 8363 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 8364 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8365 // corresponding defaulted 'operator<=>' already. 8366 if (!MD->isImplicit()) { 8367 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 8368 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 8369 } 8370 8371 // Add the 'const' to the type to recover. 8372 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 8373 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8374 EPI.TypeQuals.addConst(); 8375 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8376 FPT->getParamTypes(), EPI)); 8377 } 8378 } else { 8379 // A non-member function declared in a class must be a friend. 8380 assert(FD->getFriendObjectKind() && "expected a friend declaration"); 8381 } 8382 8383 // C++2a [class.eq]p1, [class.rel]p1: 8384 // A [defaulted comparison other than <=>] shall have a declared return 8385 // type bool. 8386 if (DCK != DefaultedComparisonKind::ThreeWay && 8387 !FD->getDeclaredReturnType()->isDependentType() && 8388 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8389 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8390 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8391 << FD->getReturnTypeSourceRange(); 8392 return true; 8393 } 8394 // C++2a [class.spaceship]p2 [P2002R0]: 8395 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8396 // R shall not contain a placeholder type. 8397 if (DCK == DefaultedComparisonKind::ThreeWay && 8398 FD->getDeclaredReturnType()->getContainedDeducedType() && 8399 !Context.hasSameType(FD->getDeclaredReturnType(), 8400 Context.getAutoDeductType())) { 8401 Diag(FD->getLocation(), 8402 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8403 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8404 << FD->getReturnTypeSourceRange(); 8405 return true; 8406 } 8407 8408 // For a defaulted function in a dependent class, defer all remaining checks 8409 // until instantiation. 8410 if (RD->isDependentType()) 8411 return false; 8412 8413 // Determine whether the function should be defined as deleted. 8414 DefaultedComparisonInfo Info = 8415 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8416 8417 bool First = FD == FD->getCanonicalDecl(); 8418 8419 // If we want to delete the function, then do so; there's nothing else to 8420 // check in that case. 8421 if (Info.Deleted) { 8422 if (!First) { 8423 // C++11 [dcl.fct.def.default]p4: 8424 // [For a] user-provided explicitly-defaulted function [...] if such a 8425 // function is implicitly defined as deleted, the program is ill-formed. 8426 // 8427 // This is really just a consequence of the general rule that you can 8428 // only delete a function on its first declaration. 8429 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8430 << FD->isImplicit() << (int)DCK; 8431 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8432 DefaultedComparisonAnalyzer::ExplainDeleted) 8433 .visit(); 8434 return true; 8435 } 8436 8437 SetDeclDeleted(FD, FD->getLocation()); 8438 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8439 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8440 << (int)DCK; 8441 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8442 DefaultedComparisonAnalyzer::ExplainDeleted) 8443 .visit(); 8444 } 8445 return false; 8446 } 8447 8448 // C++2a [class.spaceship]p2: 8449 // The return type is deduced as the common comparison type of R0, R1, ... 8450 if (DCK == DefaultedComparisonKind::ThreeWay && 8451 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8452 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8453 if (RetLoc.isInvalid()) 8454 RetLoc = FD->getBeginLoc(); 8455 // FIXME: Should we really care whether we have the complete type and the 8456 // 'enumerator' constants here? A forward declaration seems sufficient. 8457 QualType Cat = CheckComparisonCategoryType( 8458 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8459 if (Cat.isNull()) 8460 return true; 8461 Context.adjustDeducedFunctionResultType( 8462 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8463 } 8464 8465 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8466 // An explicitly-defaulted function that is not defined as deleted may be 8467 // declared constexpr or consteval only if it is constexpr-compatible. 8468 // C++2a [class.compare.default]p3 [P2002R0]: 8469 // A defaulted comparison function is constexpr-compatible if it satisfies 8470 // the requirements for a constexpr function [...] 8471 // The only relevant requirements are that the parameter and return types are 8472 // literal types. The remaining conditions are checked by the analyzer. 8473 if (FD->isConstexpr()) { 8474 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8475 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8476 !Info.Constexpr) { 8477 Diag(FD->getBeginLoc(), 8478 diag::err_incorrect_defaulted_comparison_constexpr) 8479 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8480 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8481 DefaultedComparisonAnalyzer::ExplainConstexpr) 8482 .visit(); 8483 } 8484 } 8485 8486 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8487 // If a constexpr-compatible function is explicitly defaulted on its first 8488 // declaration, it is implicitly considered to be constexpr. 8489 // FIXME: Only applying this to the first declaration seems problematic, as 8490 // simple reorderings can affect the meaning of the program. 8491 if (First && !FD->isConstexpr() && Info.Constexpr) 8492 FD->setConstexprKind(ConstexprSpecKind::Constexpr); 8493 8494 // C++2a [except.spec]p3: 8495 // If a declaration of a function does not have a noexcept-specifier 8496 // [and] is defaulted on its first declaration, [...] the exception 8497 // specification is as specified below 8498 if (FD->getExceptionSpecType() == EST_None) { 8499 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8500 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8501 EPI.ExceptionSpec.Type = EST_Unevaluated; 8502 EPI.ExceptionSpec.SourceDecl = FD; 8503 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8504 FPT->getParamTypes(), EPI)); 8505 } 8506 8507 return false; 8508 } 8509 8510 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8511 FunctionDecl *Spaceship) { 8512 Sema::CodeSynthesisContext Ctx; 8513 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8514 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8515 Ctx.Entity = Spaceship; 8516 pushCodeSynthesisContext(Ctx); 8517 8518 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8519 EqualEqual->setImplicit(); 8520 8521 popCodeSynthesisContext(); 8522 } 8523 8524 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8525 DefaultedComparisonKind DCK) { 8526 assert(FD->isDefaulted() && !FD->isDeleted() && 8527 !FD->doesThisDeclarationHaveABody()); 8528 if (FD->willHaveBody() || FD->isInvalidDecl()) 8529 return; 8530 8531 SynthesizedFunctionScope Scope(*this, FD); 8532 8533 // Add a context note for diagnostics produced after this point. 8534 Scope.addContextNote(UseLoc); 8535 8536 { 8537 // Build and set up the function body. 8538 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8539 SourceLocation BodyLoc = 8540 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8541 StmtResult Body = 8542 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8543 if (Body.isInvalid()) { 8544 FD->setInvalidDecl(); 8545 return; 8546 } 8547 FD->setBody(Body.get()); 8548 FD->markUsed(Context); 8549 } 8550 8551 // The exception specification is needed because we are defining the 8552 // function. Note that this will reuse the body we just built. 8553 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8554 8555 if (ASTMutationListener *L = getASTMutationListener()) 8556 L->CompletedImplicitDefinition(FD); 8557 } 8558 8559 static Sema::ImplicitExceptionSpecification 8560 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8561 FunctionDecl *FD, 8562 Sema::DefaultedComparisonKind DCK) { 8563 ComputingExceptionSpec CES(S, FD, Loc); 8564 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8565 8566 if (FD->isInvalidDecl()) 8567 return ExceptSpec; 8568 8569 // The common case is that we just defined the comparison function. In that 8570 // case, just look at whether the body can throw. 8571 if (FD->hasBody()) { 8572 ExceptSpec.CalledStmt(FD->getBody()); 8573 } else { 8574 // Otherwise, build a body so we can check it. This should ideally only 8575 // happen when we're not actually marking the function referenced. (This is 8576 // only really important for efficiency: we don't want to build and throw 8577 // away bodies for comparison functions more than we strictly need to.) 8578 8579 // Pretend to synthesize the function body in an unevaluated context. 8580 // Note that we can't actually just go ahead and define the function here: 8581 // we are not permitted to mark its callees as referenced. 8582 Sema::SynthesizedFunctionScope Scope(S, FD); 8583 EnterExpressionEvaluationContext Context( 8584 S, Sema::ExpressionEvaluationContext::Unevaluated); 8585 8586 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8587 SourceLocation BodyLoc = 8588 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8589 StmtResult Body = 8590 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8591 if (!Body.isInvalid()) 8592 ExceptSpec.CalledStmt(Body.get()); 8593 8594 // FIXME: Can we hold onto this body and just transform it to potentially 8595 // evaluated when we're asked to define the function rather than rebuilding 8596 // it? Either that, or we should only build the bits of the body that we 8597 // need (the expressions, not the statements). 8598 } 8599 8600 return ExceptSpec; 8601 } 8602 8603 void Sema::CheckDelayedMemberExceptionSpecs() { 8604 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8605 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8606 8607 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8608 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8609 8610 // Perform any deferred checking of exception specifications for virtual 8611 // destructors. 8612 for (auto &Check : Overriding) 8613 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8614 8615 // Perform any deferred checking of exception specifications for befriended 8616 // special members. 8617 for (auto &Check : Equivalent) 8618 CheckEquivalentExceptionSpec(Check.second, Check.first); 8619 } 8620 8621 namespace { 8622 /// CRTP base class for visiting operations performed by a special member 8623 /// function (or inherited constructor). 8624 template<typename Derived> 8625 struct SpecialMemberVisitor { 8626 Sema &S; 8627 CXXMethodDecl *MD; 8628 Sema::CXXSpecialMember CSM; 8629 Sema::InheritedConstructorInfo *ICI; 8630 8631 // Properties of the special member, computed for convenience. 8632 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8633 8634 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8635 Sema::InheritedConstructorInfo *ICI) 8636 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8637 switch (CSM) { 8638 case Sema::CXXDefaultConstructor: 8639 case Sema::CXXCopyConstructor: 8640 case Sema::CXXMoveConstructor: 8641 IsConstructor = true; 8642 break; 8643 case Sema::CXXCopyAssignment: 8644 case Sema::CXXMoveAssignment: 8645 IsAssignment = true; 8646 break; 8647 case Sema::CXXDestructor: 8648 break; 8649 case Sema::CXXInvalid: 8650 llvm_unreachable("invalid special member kind"); 8651 } 8652 8653 if (MD->getNumParams()) { 8654 if (const ReferenceType *RT = 8655 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8656 ConstArg = RT->getPointeeType().isConstQualified(); 8657 } 8658 } 8659 8660 Derived &getDerived() { return static_cast<Derived&>(*this); } 8661 8662 /// Is this a "move" special member? 8663 bool isMove() const { 8664 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8665 } 8666 8667 /// Look up the corresponding special member in the given class. 8668 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8669 unsigned Quals, bool IsMutable) { 8670 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8671 ConstArg && !IsMutable); 8672 } 8673 8674 /// Look up the constructor for the specified base class to see if it's 8675 /// overridden due to this being an inherited constructor. 8676 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8677 if (!ICI) 8678 return {}; 8679 assert(CSM == Sema::CXXDefaultConstructor); 8680 auto *BaseCtor = 8681 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8682 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8683 return MD; 8684 return {}; 8685 } 8686 8687 /// A base or member subobject. 8688 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8689 8690 /// Get the location to use for a subobject in diagnostics. 8691 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8692 // FIXME: For an indirect virtual base, the direct base leading to 8693 // the indirect virtual base would be a more useful choice. 8694 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8695 return B->getBaseTypeLoc(); 8696 else 8697 return Subobj.get<FieldDecl*>()->getLocation(); 8698 } 8699 8700 enum BasesToVisit { 8701 /// Visit all non-virtual (direct) bases. 8702 VisitNonVirtualBases, 8703 /// Visit all direct bases, virtual or not. 8704 VisitDirectBases, 8705 /// Visit all non-virtual bases, and all virtual bases if the class 8706 /// is not abstract. 8707 VisitPotentiallyConstructedBases, 8708 /// Visit all direct or virtual bases. 8709 VisitAllBases 8710 }; 8711 8712 // Visit the bases and members of the class. 8713 bool visit(BasesToVisit Bases) { 8714 CXXRecordDecl *RD = MD->getParent(); 8715 8716 if (Bases == VisitPotentiallyConstructedBases) 8717 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8718 8719 for (auto &B : RD->bases()) 8720 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8721 getDerived().visitBase(&B)) 8722 return true; 8723 8724 if (Bases == VisitAllBases) 8725 for (auto &B : RD->vbases()) 8726 if (getDerived().visitBase(&B)) 8727 return true; 8728 8729 for (auto *F : RD->fields()) 8730 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8731 getDerived().visitField(F)) 8732 return true; 8733 8734 return false; 8735 } 8736 }; 8737 } 8738 8739 namespace { 8740 struct SpecialMemberDeletionInfo 8741 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8742 bool Diagnose; 8743 8744 SourceLocation Loc; 8745 8746 bool AllFieldsAreConst; 8747 8748 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 8749 Sema::CXXSpecialMember CSM, 8750 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 8751 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 8752 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 8753 8754 bool inUnion() const { return MD->getParent()->isUnion(); } 8755 8756 Sema::CXXSpecialMember getEffectiveCSM() { 8757 return ICI ? Sema::CXXInvalid : CSM; 8758 } 8759 8760 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 8761 8762 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 8763 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 8764 8765 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 8766 bool shouldDeleteForField(FieldDecl *FD); 8767 bool shouldDeleteForAllConstMembers(); 8768 8769 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 8770 unsigned Quals); 8771 bool shouldDeleteForSubobjectCall(Subobject Subobj, 8772 Sema::SpecialMemberOverloadResult SMOR, 8773 bool IsDtorCallInCtor); 8774 8775 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 8776 }; 8777 } 8778 8779 /// Is the given special member inaccessible when used on the given 8780 /// sub-object. 8781 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 8782 CXXMethodDecl *target) { 8783 /// If we're operating on a base class, the object type is the 8784 /// type of this special member. 8785 QualType objectTy; 8786 AccessSpecifier access = target->getAccess(); 8787 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 8788 objectTy = S.Context.getTypeDeclType(MD->getParent()); 8789 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 8790 8791 // If we're operating on a field, the object type is the type of the field. 8792 } else { 8793 objectTy = S.Context.getTypeDeclType(target->getParent()); 8794 } 8795 8796 return S.isMemberAccessibleForDeletion( 8797 target->getParent(), DeclAccessPair::make(target, access), objectTy); 8798 } 8799 8800 /// Check whether we should delete a special member due to the implicit 8801 /// definition containing a call to a special member of a subobject. 8802 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 8803 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 8804 bool IsDtorCallInCtor) { 8805 CXXMethodDecl *Decl = SMOR.getMethod(); 8806 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8807 8808 int DiagKind = -1; 8809 8810 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 8811 DiagKind = !Decl ? 0 : 1; 8812 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 8813 DiagKind = 2; 8814 else if (!isAccessible(Subobj, Decl)) 8815 DiagKind = 3; 8816 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 8817 !Decl->isTrivial()) { 8818 // A member of a union must have a trivial corresponding special member. 8819 // As a weird special case, a destructor call from a union's constructor 8820 // must be accessible and non-deleted, but need not be trivial. Such a 8821 // destructor is never actually called, but is semantically checked as 8822 // if it were. 8823 DiagKind = 4; 8824 } 8825 8826 if (DiagKind == -1) 8827 return false; 8828 8829 if (Diagnose) { 8830 if (Field) { 8831 S.Diag(Field->getLocation(), 8832 diag::note_deleted_special_member_class_subobject) 8833 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 8834 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 8835 } else { 8836 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 8837 S.Diag(Base->getBeginLoc(), 8838 diag::note_deleted_special_member_class_subobject) 8839 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8840 << Base->getType() << DiagKind << IsDtorCallInCtor 8841 << /*IsObjCPtr*/false; 8842 } 8843 8844 if (DiagKind == 1) 8845 S.NoteDeletedFunction(Decl); 8846 // FIXME: Explain inaccessibility if DiagKind == 3. 8847 } 8848 8849 return true; 8850 } 8851 8852 /// Check whether we should delete a special member function due to having a 8853 /// direct or virtual base class or non-static data member of class type M. 8854 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 8855 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 8856 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8857 bool IsMutable = Field && Field->isMutable(); 8858 8859 // C++11 [class.ctor]p5: 8860 // -- any direct or virtual base class, or non-static data member with no 8861 // brace-or-equal-initializer, has class type M (or array thereof) and 8862 // either M has no default constructor or overload resolution as applied 8863 // to M's default constructor results in an ambiguity or in a function 8864 // that is deleted or inaccessible 8865 // C++11 [class.copy]p11, C++11 [class.copy]p23: 8866 // -- a direct or virtual base class B that cannot be copied/moved because 8867 // overload resolution, as applied to B's corresponding special member, 8868 // results in an ambiguity or a function that is deleted or inaccessible 8869 // from the defaulted special member 8870 // C++11 [class.dtor]p5: 8871 // -- any direct or virtual base class [...] has a type with a destructor 8872 // that is deleted or inaccessible 8873 if (!(CSM == Sema::CXXDefaultConstructor && 8874 Field && Field->hasInClassInitializer()) && 8875 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 8876 false)) 8877 return true; 8878 8879 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 8880 // -- any direct or virtual base class or non-static data member has a 8881 // type with a destructor that is deleted or inaccessible 8882 if (IsConstructor) { 8883 Sema::SpecialMemberOverloadResult SMOR = 8884 S.LookupSpecialMember(Class, Sema::CXXDestructor, 8885 false, false, false, false, false); 8886 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 8887 return true; 8888 } 8889 8890 return false; 8891 } 8892 8893 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 8894 FieldDecl *FD, QualType FieldType) { 8895 // The defaulted special functions are defined as deleted if this is a variant 8896 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 8897 // type under ARC. 8898 if (!FieldType.hasNonTrivialObjCLifetime()) 8899 return false; 8900 8901 // Don't make the defaulted default constructor defined as deleted if the 8902 // member has an in-class initializer. 8903 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 8904 return false; 8905 8906 if (Diagnose) { 8907 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 8908 S.Diag(FD->getLocation(), 8909 diag::note_deleted_special_member_class_subobject) 8910 << getEffectiveCSM() << ParentClass << /*IsField*/true 8911 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 8912 } 8913 8914 return true; 8915 } 8916 8917 /// Check whether we should delete a special member function due to the class 8918 /// having a particular direct or virtual base class. 8919 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 8920 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 8921 // If program is correct, BaseClass cannot be null, but if it is, the error 8922 // must be reported elsewhere. 8923 if (!BaseClass) 8924 return false; 8925 // If we have an inheriting constructor, check whether we're calling an 8926 // inherited constructor instead of a default constructor. 8927 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 8928 if (auto *BaseCtor = SMOR.getMethod()) { 8929 // Note that we do not check access along this path; other than that, 8930 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 8931 // FIXME: Check that the base has a usable destructor! Sink this into 8932 // shouldDeleteForClassSubobject. 8933 if (BaseCtor->isDeleted() && Diagnose) { 8934 S.Diag(Base->getBeginLoc(), 8935 diag::note_deleted_special_member_class_subobject) 8936 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8937 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 8938 << /*IsObjCPtr*/false; 8939 S.NoteDeletedFunction(BaseCtor); 8940 } 8941 return BaseCtor->isDeleted(); 8942 } 8943 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 8944 } 8945 8946 /// Check whether we should delete a special member function due to the class 8947 /// having a particular non-static data member. 8948 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 8949 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 8950 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 8951 8952 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 8953 return true; 8954 8955 if (CSM == Sema::CXXDefaultConstructor) { 8956 // For a default constructor, all references must be initialized in-class 8957 // and, if a union, it must have a non-const member. 8958 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 8959 if (Diagnose) 8960 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8961 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 8962 return true; 8963 } 8964 // C++11 [class.ctor]p5: any non-variant non-static data member of 8965 // const-qualified type (or array thereof) with no 8966 // brace-or-equal-initializer does not have a user-provided default 8967 // constructor. 8968 if (!inUnion() && FieldType.isConstQualified() && 8969 !FD->hasInClassInitializer() && 8970 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 8971 if (Diagnose) 8972 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8973 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 8974 return true; 8975 } 8976 8977 if (inUnion() && !FieldType.isConstQualified()) 8978 AllFieldsAreConst = false; 8979 } else if (CSM == Sema::CXXCopyConstructor) { 8980 // For a copy constructor, data members must not be of rvalue reference 8981 // type. 8982 if (FieldType->isRValueReferenceType()) { 8983 if (Diagnose) 8984 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 8985 << MD->getParent() << FD << FieldType; 8986 return true; 8987 } 8988 } else if (IsAssignment) { 8989 // For an assignment operator, data members must not be of reference type. 8990 if (FieldType->isReferenceType()) { 8991 if (Diagnose) 8992 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 8993 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 8994 return true; 8995 } 8996 if (!FieldRecord && FieldType.isConstQualified()) { 8997 // C++11 [class.copy]p23: 8998 // -- a non-static data member of const non-class type (or array thereof) 8999 if (Diagnose) 9000 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9001 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 9002 return true; 9003 } 9004 } 9005 9006 if (FieldRecord) { 9007 // Some additional restrictions exist on the variant members. 9008 if (!inUnion() && FieldRecord->isUnion() && 9009 FieldRecord->isAnonymousStructOrUnion()) { 9010 bool AllVariantFieldsAreConst = true; 9011 9012 // FIXME: Handle anonymous unions declared within anonymous unions. 9013 for (auto *UI : FieldRecord->fields()) { 9014 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 9015 9016 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 9017 return true; 9018 9019 if (!UnionFieldType.isConstQualified()) 9020 AllVariantFieldsAreConst = false; 9021 9022 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 9023 if (UnionFieldRecord && 9024 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 9025 UnionFieldType.getCVRQualifiers())) 9026 return true; 9027 } 9028 9029 // At least one member in each anonymous union must be non-const 9030 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 9031 !FieldRecord->field_empty()) { 9032 if (Diagnose) 9033 S.Diag(FieldRecord->getLocation(), 9034 diag::note_deleted_default_ctor_all_const) 9035 << !!ICI << MD->getParent() << /*anonymous union*/1; 9036 return true; 9037 } 9038 9039 // Don't check the implicit member of the anonymous union type. 9040 // This is technically non-conformant, but sanity demands it. 9041 return false; 9042 } 9043 9044 if (shouldDeleteForClassSubobject(FieldRecord, FD, 9045 FieldType.getCVRQualifiers())) 9046 return true; 9047 } 9048 9049 return false; 9050 } 9051 9052 /// C++11 [class.ctor] p5: 9053 /// A defaulted default constructor for a class X is defined as deleted if 9054 /// X is a union and all of its variant members are of const-qualified type. 9055 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 9056 // This is a silly definition, because it gives an empty union a deleted 9057 // default constructor. Don't do that. 9058 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 9059 bool AnyFields = false; 9060 for (auto *F : MD->getParent()->fields()) 9061 if ((AnyFields = !F->isUnnamedBitfield())) 9062 break; 9063 if (!AnyFields) 9064 return false; 9065 if (Diagnose) 9066 S.Diag(MD->getParent()->getLocation(), 9067 diag::note_deleted_default_ctor_all_const) 9068 << !!ICI << MD->getParent() << /*not anonymous union*/0; 9069 return true; 9070 } 9071 return false; 9072 } 9073 9074 /// Determine whether a defaulted special member function should be defined as 9075 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 9076 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 9077 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 9078 InheritedConstructorInfo *ICI, 9079 bool Diagnose) { 9080 if (MD->isInvalidDecl()) 9081 return false; 9082 CXXRecordDecl *RD = MD->getParent(); 9083 assert(!RD->isDependentType() && "do deletion after instantiation"); 9084 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 9085 return false; 9086 9087 // C++11 [expr.lambda.prim]p19: 9088 // The closure type associated with a lambda-expression has a 9089 // deleted (8.4.3) default constructor and a deleted copy 9090 // assignment operator. 9091 // C++2a adds back these operators if the lambda has no lambda-capture. 9092 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 9093 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 9094 if (Diagnose) 9095 Diag(RD->getLocation(), diag::note_lambda_decl); 9096 return true; 9097 } 9098 9099 // For an anonymous struct or union, the copy and assignment special members 9100 // will never be used, so skip the check. For an anonymous union declared at 9101 // namespace scope, the constructor and destructor are used. 9102 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 9103 RD->isAnonymousStructOrUnion()) 9104 return false; 9105 9106 // C++11 [class.copy]p7, p18: 9107 // If the class definition declares a move constructor or move assignment 9108 // operator, an implicitly declared copy constructor or copy assignment 9109 // operator is defined as deleted. 9110 if (MD->isImplicit() && 9111 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 9112 CXXMethodDecl *UserDeclaredMove = nullptr; 9113 9114 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 9115 // deletion of the corresponding copy operation, not both copy operations. 9116 // MSVC 2015 has adopted the standards conforming behavior. 9117 bool DeletesOnlyMatchingCopy = 9118 getLangOpts().MSVCCompat && 9119 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 9120 9121 if (RD->hasUserDeclaredMoveConstructor() && 9122 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 9123 if (!Diagnose) return true; 9124 9125 // Find any user-declared move constructor. 9126 for (auto *I : RD->ctors()) { 9127 if (I->isMoveConstructor()) { 9128 UserDeclaredMove = I; 9129 break; 9130 } 9131 } 9132 assert(UserDeclaredMove); 9133 } else if (RD->hasUserDeclaredMoveAssignment() && 9134 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 9135 if (!Diagnose) return true; 9136 9137 // Find any user-declared move assignment operator. 9138 for (auto *I : RD->methods()) { 9139 if (I->isMoveAssignmentOperator()) { 9140 UserDeclaredMove = I; 9141 break; 9142 } 9143 } 9144 assert(UserDeclaredMove); 9145 } 9146 9147 if (UserDeclaredMove) { 9148 Diag(UserDeclaredMove->getLocation(), 9149 diag::note_deleted_copy_user_declared_move) 9150 << (CSM == CXXCopyAssignment) << RD 9151 << UserDeclaredMove->isMoveAssignmentOperator(); 9152 return true; 9153 } 9154 } 9155 9156 // Do access control from the special member function 9157 ContextRAII MethodContext(*this, MD); 9158 9159 // C++11 [class.dtor]p5: 9160 // -- for a virtual destructor, lookup of the non-array deallocation function 9161 // results in an ambiguity or in a function that is deleted or inaccessible 9162 if (CSM == CXXDestructor && MD->isVirtual()) { 9163 FunctionDecl *OperatorDelete = nullptr; 9164 DeclarationName Name = 9165 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 9166 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 9167 OperatorDelete, /*Diagnose*/false)) { 9168 if (Diagnose) 9169 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 9170 return true; 9171 } 9172 } 9173 9174 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 9175 9176 // Per DR1611, do not consider virtual bases of constructors of abstract 9177 // classes, since we are not going to construct them. 9178 // Per DR1658, do not consider virtual bases of destructors of abstract 9179 // classes either. 9180 // Per DR2180, for assignment operators we only assign (and thus only 9181 // consider) direct bases. 9182 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 9183 : SMI.VisitPotentiallyConstructedBases)) 9184 return true; 9185 9186 if (SMI.shouldDeleteForAllConstMembers()) 9187 return true; 9188 9189 if (getLangOpts().CUDA) { 9190 // We should delete the special member in CUDA mode if target inference 9191 // failed. 9192 // For inherited constructors (non-null ICI), CSM may be passed so that MD 9193 // is treated as certain special member, which may not reflect what special 9194 // member MD really is. However inferCUDATargetForImplicitSpecialMember 9195 // expects CSM to match MD, therefore recalculate CSM. 9196 assert(ICI || CSM == getSpecialMember(MD)); 9197 auto RealCSM = CSM; 9198 if (ICI) 9199 RealCSM = getSpecialMember(MD); 9200 9201 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 9202 SMI.ConstArg, Diagnose); 9203 } 9204 9205 return false; 9206 } 9207 9208 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 9209 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 9210 assert(DFK && "not a defaultable function"); 9211 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted"); 9212 9213 if (DFK.isSpecialMember()) { 9214 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 9215 nullptr, /*Diagnose=*/true); 9216 } else { 9217 DefaultedComparisonAnalyzer( 9218 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 9219 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 9220 .visit(); 9221 } 9222 } 9223 9224 /// Perform lookup for a special member of the specified kind, and determine 9225 /// whether it is trivial. If the triviality can be determined without the 9226 /// lookup, skip it. This is intended for use when determining whether a 9227 /// special member of a containing object is trivial, and thus does not ever 9228 /// perform overload resolution for default constructors. 9229 /// 9230 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 9231 /// member that was most likely to be intended to be trivial, if any. 9232 /// 9233 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 9234 /// determine whether the special member is trivial. 9235 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 9236 Sema::CXXSpecialMember CSM, unsigned Quals, 9237 bool ConstRHS, 9238 Sema::TrivialABIHandling TAH, 9239 CXXMethodDecl **Selected) { 9240 if (Selected) 9241 *Selected = nullptr; 9242 9243 switch (CSM) { 9244 case Sema::CXXInvalid: 9245 llvm_unreachable("not a special member"); 9246 9247 case Sema::CXXDefaultConstructor: 9248 // C++11 [class.ctor]p5: 9249 // A default constructor is trivial if: 9250 // - all the [direct subobjects] have trivial default constructors 9251 // 9252 // Note, no overload resolution is performed in this case. 9253 if (RD->hasTrivialDefaultConstructor()) 9254 return true; 9255 9256 if (Selected) { 9257 // If there's a default constructor which could have been trivial, dig it 9258 // out. Otherwise, if there's any user-provided default constructor, point 9259 // to that as an example of why there's not a trivial one. 9260 CXXConstructorDecl *DefCtor = nullptr; 9261 if (RD->needsImplicitDefaultConstructor()) 9262 S.DeclareImplicitDefaultConstructor(RD); 9263 for (auto *CI : RD->ctors()) { 9264 if (!CI->isDefaultConstructor()) 9265 continue; 9266 DefCtor = CI; 9267 if (!DefCtor->isUserProvided()) 9268 break; 9269 } 9270 9271 *Selected = DefCtor; 9272 } 9273 9274 return false; 9275 9276 case Sema::CXXDestructor: 9277 // C++11 [class.dtor]p5: 9278 // A destructor is trivial if: 9279 // - all the direct [subobjects] have trivial destructors 9280 if (RD->hasTrivialDestructor() || 9281 (TAH == Sema::TAH_ConsiderTrivialABI && 9282 RD->hasTrivialDestructorForCall())) 9283 return true; 9284 9285 if (Selected) { 9286 if (RD->needsImplicitDestructor()) 9287 S.DeclareImplicitDestructor(RD); 9288 *Selected = RD->getDestructor(); 9289 } 9290 9291 return false; 9292 9293 case Sema::CXXCopyConstructor: 9294 // C++11 [class.copy]p12: 9295 // A copy constructor is trivial if: 9296 // - the constructor selected to copy each direct [subobject] is trivial 9297 if (RD->hasTrivialCopyConstructor() || 9298 (TAH == Sema::TAH_ConsiderTrivialABI && 9299 RD->hasTrivialCopyConstructorForCall())) { 9300 if (Quals == Qualifiers::Const) 9301 // We must either select the trivial copy constructor or reach an 9302 // ambiguity; no need to actually perform overload resolution. 9303 return true; 9304 } else if (!Selected) { 9305 return false; 9306 } 9307 // In C++98, we are not supposed to perform overload resolution here, but we 9308 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 9309 // cases like B as having a non-trivial copy constructor: 9310 // struct A { template<typename T> A(T&); }; 9311 // struct B { mutable A a; }; 9312 goto NeedOverloadResolution; 9313 9314 case Sema::CXXCopyAssignment: 9315 // C++11 [class.copy]p25: 9316 // A copy assignment operator is trivial if: 9317 // - the assignment operator selected to copy each direct [subobject] is 9318 // trivial 9319 if (RD->hasTrivialCopyAssignment()) { 9320 if (Quals == Qualifiers::Const) 9321 return true; 9322 } else if (!Selected) { 9323 return false; 9324 } 9325 // In C++98, we are not supposed to perform overload resolution here, but we 9326 // treat that as a language defect. 9327 goto NeedOverloadResolution; 9328 9329 case Sema::CXXMoveConstructor: 9330 case Sema::CXXMoveAssignment: 9331 NeedOverloadResolution: 9332 Sema::SpecialMemberOverloadResult SMOR = 9333 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 9334 9335 // The standard doesn't describe how to behave if the lookup is ambiguous. 9336 // We treat it as not making the member non-trivial, just like the standard 9337 // mandates for the default constructor. This should rarely matter, because 9338 // the member will also be deleted. 9339 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9340 return true; 9341 9342 if (!SMOR.getMethod()) { 9343 assert(SMOR.getKind() == 9344 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 9345 return false; 9346 } 9347 9348 // We deliberately don't check if we found a deleted special member. We're 9349 // not supposed to! 9350 if (Selected) 9351 *Selected = SMOR.getMethod(); 9352 9353 if (TAH == Sema::TAH_ConsiderTrivialABI && 9354 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 9355 return SMOR.getMethod()->isTrivialForCall(); 9356 return SMOR.getMethod()->isTrivial(); 9357 } 9358 9359 llvm_unreachable("unknown special method kind"); 9360 } 9361 9362 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 9363 for (auto *CI : RD->ctors()) 9364 if (!CI->isImplicit()) 9365 return CI; 9366 9367 // Look for constructor templates. 9368 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 9369 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 9370 if (CXXConstructorDecl *CD = 9371 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 9372 return CD; 9373 } 9374 9375 return nullptr; 9376 } 9377 9378 /// The kind of subobject we are checking for triviality. The values of this 9379 /// enumeration are used in diagnostics. 9380 enum TrivialSubobjectKind { 9381 /// The subobject is a base class. 9382 TSK_BaseClass, 9383 /// The subobject is a non-static data member. 9384 TSK_Field, 9385 /// The object is actually the complete object. 9386 TSK_CompleteObject 9387 }; 9388 9389 /// Check whether the special member selected for a given type would be trivial. 9390 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9391 QualType SubType, bool ConstRHS, 9392 Sema::CXXSpecialMember CSM, 9393 TrivialSubobjectKind Kind, 9394 Sema::TrivialABIHandling TAH, bool Diagnose) { 9395 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9396 if (!SubRD) 9397 return true; 9398 9399 CXXMethodDecl *Selected; 9400 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9401 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9402 return true; 9403 9404 if (Diagnose) { 9405 if (ConstRHS) 9406 SubType.addConst(); 9407 9408 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9409 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9410 << Kind << SubType.getUnqualifiedType(); 9411 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9412 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9413 } else if (!Selected) 9414 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9415 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9416 else if (Selected->isUserProvided()) { 9417 if (Kind == TSK_CompleteObject) 9418 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9419 << Kind << SubType.getUnqualifiedType() << CSM; 9420 else { 9421 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9422 << Kind << SubType.getUnqualifiedType() << CSM; 9423 S.Diag(Selected->getLocation(), diag::note_declared_at); 9424 } 9425 } else { 9426 if (Kind != TSK_CompleteObject) 9427 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9428 << Kind << SubType.getUnqualifiedType() << CSM; 9429 9430 // Explain why the defaulted or deleted special member isn't trivial. 9431 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9432 Diagnose); 9433 } 9434 } 9435 9436 return false; 9437 } 9438 9439 /// Check whether the members of a class type allow a special member to be 9440 /// trivial. 9441 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9442 Sema::CXXSpecialMember CSM, 9443 bool ConstArg, 9444 Sema::TrivialABIHandling TAH, 9445 bool Diagnose) { 9446 for (const auto *FI : RD->fields()) { 9447 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9448 continue; 9449 9450 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9451 9452 // Pretend anonymous struct or union members are members of this class. 9453 if (FI->isAnonymousStructOrUnion()) { 9454 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9455 CSM, ConstArg, TAH, Diagnose)) 9456 return false; 9457 continue; 9458 } 9459 9460 // C++11 [class.ctor]p5: 9461 // A default constructor is trivial if [...] 9462 // -- no non-static data member of its class has a 9463 // brace-or-equal-initializer 9464 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9465 if (Diagnose) 9466 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init) 9467 << FI; 9468 return false; 9469 } 9470 9471 // Objective C ARC 4.3.5: 9472 // [...] nontrivally ownership-qualified types are [...] not trivially 9473 // default constructible, copy constructible, move constructible, copy 9474 // assignable, move assignable, or destructible [...] 9475 if (FieldType.hasNonTrivialObjCLifetime()) { 9476 if (Diagnose) 9477 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9478 << RD << FieldType.getObjCLifetime(); 9479 return false; 9480 } 9481 9482 bool ConstRHS = ConstArg && !FI->isMutable(); 9483 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9484 CSM, TSK_Field, TAH, Diagnose)) 9485 return false; 9486 } 9487 9488 return true; 9489 } 9490 9491 /// Diagnose why the specified class does not have a trivial special member of 9492 /// the given kind. 9493 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9494 QualType Ty = Context.getRecordType(RD); 9495 9496 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9497 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9498 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9499 /*Diagnose*/true); 9500 } 9501 9502 /// Determine whether a defaulted or deleted special member function is trivial, 9503 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9504 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9505 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9506 TrivialABIHandling TAH, bool Diagnose) { 9507 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 9508 9509 CXXRecordDecl *RD = MD->getParent(); 9510 9511 bool ConstArg = false; 9512 9513 // C++11 [class.copy]p12, p25: [DR1593] 9514 // A [special member] is trivial if [...] its parameter-type-list is 9515 // equivalent to the parameter-type-list of an implicit declaration [...] 9516 switch (CSM) { 9517 case CXXDefaultConstructor: 9518 case CXXDestructor: 9519 // Trivial default constructors and destructors cannot have parameters. 9520 break; 9521 9522 case CXXCopyConstructor: 9523 case CXXCopyAssignment: { 9524 // Trivial copy operations always have const, non-volatile parameter types. 9525 ConstArg = true; 9526 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9527 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9528 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 9529 if (Diagnose) 9530 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9531 << Param0->getSourceRange() << Param0->getType() 9532 << Context.getLValueReferenceType( 9533 Context.getRecordType(RD).withConst()); 9534 return false; 9535 } 9536 break; 9537 } 9538 9539 case CXXMoveConstructor: 9540 case CXXMoveAssignment: { 9541 // Trivial move operations always have non-cv-qualified parameters. 9542 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9543 const RValueReferenceType *RT = 9544 Param0->getType()->getAs<RValueReferenceType>(); 9545 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9546 if (Diagnose) 9547 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9548 << Param0->getSourceRange() << Param0->getType() 9549 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9550 return false; 9551 } 9552 break; 9553 } 9554 9555 case CXXInvalid: 9556 llvm_unreachable("not a special member"); 9557 } 9558 9559 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9560 if (Diagnose) 9561 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9562 diag::note_nontrivial_default_arg) 9563 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9564 return false; 9565 } 9566 if (MD->isVariadic()) { 9567 if (Diagnose) 9568 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9569 return false; 9570 } 9571 9572 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9573 // A copy/move [constructor or assignment operator] is trivial if 9574 // -- the [member] selected to copy/move each direct base class subobject 9575 // is trivial 9576 // 9577 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9578 // A [default constructor or destructor] is trivial if 9579 // -- all the direct base classes have trivial [default constructors or 9580 // destructors] 9581 for (const auto &BI : RD->bases()) 9582 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9583 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9584 return false; 9585 9586 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9587 // A copy/move [constructor or assignment operator] for a class X is 9588 // trivial if 9589 // -- for each non-static data member of X that is of class type (or array 9590 // thereof), the constructor selected to copy/move that member is 9591 // trivial 9592 // 9593 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9594 // A [default constructor or destructor] is trivial if 9595 // -- for all of the non-static data members of its class that are of class 9596 // type (or array thereof), each such class has a trivial [default 9597 // constructor or destructor] 9598 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9599 return false; 9600 9601 // C++11 [class.dtor]p5: 9602 // A destructor is trivial if [...] 9603 // -- the destructor is not virtual 9604 if (CSM == CXXDestructor && MD->isVirtual()) { 9605 if (Diagnose) 9606 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9607 return false; 9608 } 9609 9610 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9611 // A [special member] for class X is trivial if [...] 9612 // -- class X has no virtual functions and no virtual base classes 9613 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9614 if (!Diagnose) 9615 return false; 9616 9617 if (RD->getNumVBases()) { 9618 // Check for virtual bases. We already know that the corresponding 9619 // member in all bases is trivial, so vbases must all be direct. 9620 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9621 assert(BS.isVirtual()); 9622 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9623 return false; 9624 } 9625 9626 // Must have a virtual method. 9627 for (const auto *MI : RD->methods()) { 9628 if (MI->isVirtual()) { 9629 SourceLocation MLoc = MI->getBeginLoc(); 9630 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9631 return false; 9632 } 9633 } 9634 9635 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 9636 } 9637 9638 // Looks like it's trivial! 9639 return true; 9640 } 9641 9642 namespace { 9643 struct FindHiddenVirtualMethod { 9644 Sema *S; 9645 CXXMethodDecl *Method; 9646 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9647 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9648 9649 private: 9650 /// Check whether any most overridden method from MD in Methods 9651 static bool CheckMostOverridenMethods( 9652 const CXXMethodDecl *MD, 9653 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9654 if (MD->size_overridden_methods() == 0) 9655 return Methods.count(MD->getCanonicalDecl()); 9656 for (const CXXMethodDecl *O : MD->overridden_methods()) 9657 if (CheckMostOverridenMethods(O, Methods)) 9658 return true; 9659 return false; 9660 } 9661 9662 public: 9663 /// Member lookup function that determines whether a given C++ 9664 /// method overloads virtual methods in a base class without overriding any, 9665 /// to be used with CXXRecordDecl::lookupInBases(). 9666 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9667 RecordDecl *BaseRecord = 9668 Specifier->getType()->castAs<RecordType>()->getDecl(); 9669 9670 DeclarationName Name = Method->getDeclName(); 9671 assert(Name.getNameKind() == DeclarationName::Identifier); 9672 9673 bool foundSameNameMethod = false; 9674 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9675 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 9676 Path.Decls = Path.Decls.slice(1)) { 9677 NamedDecl *D = Path.Decls.front(); 9678 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9679 MD = MD->getCanonicalDecl(); 9680 foundSameNameMethod = true; 9681 // Interested only in hidden virtual methods. 9682 if (!MD->isVirtual()) 9683 continue; 9684 // If the method we are checking overrides a method from its base 9685 // don't warn about the other overloaded methods. Clang deviates from 9686 // GCC by only diagnosing overloads of inherited virtual functions that 9687 // do not override any other virtual functions in the base. GCC's 9688 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9689 // function from a base class. These cases may be better served by a 9690 // warning (not specific to virtual functions) on call sites when the 9691 // call would select a different function from the base class, were it 9692 // visible. 9693 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9694 if (!S->IsOverload(Method, MD, false)) 9695 return true; 9696 // Collect the overload only if its hidden. 9697 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9698 overloadedMethods.push_back(MD); 9699 } 9700 } 9701 9702 if (foundSameNameMethod) 9703 OverloadedMethods.append(overloadedMethods.begin(), 9704 overloadedMethods.end()); 9705 return foundSameNameMethod; 9706 } 9707 }; 9708 } // end anonymous namespace 9709 9710 /// Add the most overriden methods from MD to Methods 9711 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9712 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9713 if (MD->size_overridden_methods() == 0) 9714 Methods.insert(MD->getCanonicalDecl()); 9715 else 9716 for (const CXXMethodDecl *O : MD->overridden_methods()) 9717 AddMostOverridenMethods(O, Methods); 9718 } 9719 9720 /// Check if a method overloads virtual methods in a base class without 9721 /// overriding any. 9722 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9723 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9724 if (!MD->getDeclName().isIdentifier()) 9725 return; 9726 9727 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9728 /*bool RecordPaths=*/false, 9729 /*bool DetectVirtual=*/false); 9730 FindHiddenVirtualMethod FHVM; 9731 FHVM.Method = MD; 9732 FHVM.S = this; 9733 9734 // Keep the base methods that were overridden or introduced in the subclass 9735 // by 'using' in a set. A base method not in this set is hidden. 9736 CXXRecordDecl *DC = MD->getParent(); 9737 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9738 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9739 NamedDecl *ND = *I; 9740 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9741 ND = shad->getTargetDecl(); 9742 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9743 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9744 } 9745 9746 if (DC->lookupInBases(FHVM, Paths)) 9747 OverloadedMethods = FHVM.OverloadedMethods; 9748 } 9749 9750 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 9751 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9752 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 9753 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 9754 PartialDiagnostic PD = PDiag( 9755 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 9756 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 9757 Diag(overloadedMD->getLocation(), PD); 9758 } 9759 } 9760 9761 /// Diagnose methods which overload virtual methods in a base class 9762 /// without overriding any. 9763 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 9764 if (MD->isInvalidDecl()) 9765 return; 9766 9767 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 9768 return; 9769 9770 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9771 FindHiddenVirtualMethods(MD, OverloadedMethods); 9772 if (!OverloadedMethods.empty()) { 9773 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 9774 << MD << (OverloadedMethods.size() > 1); 9775 9776 NoteHiddenVirtualMethods(MD, OverloadedMethods); 9777 } 9778 } 9779 9780 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 9781 auto PrintDiagAndRemoveAttr = [&](unsigned N) { 9782 // No diagnostics if this is a template instantiation. 9783 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) { 9784 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9785 diag::ext_cannot_use_trivial_abi) << &RD; 9786 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9787 diag::note_cannot_use_trivial_abi_reason) << &RD << N; 9788 } 9789 RD.dropAttr<TrivialABIAttr>(); 9790 }; 9791 9792 // Ill-formed if the copy and move constructors are deleted. 9793 auto HasNonDeletedCopyOrMoveConstructor = [&]() { 9794 // If the type is dependent, then assume it might have 9795 // implicit copy or move ctor because we won't know yet at this point. 9796 if (RD.isDependentType()) 9797 return true; 9798 if (RD.needsImplicitCopyConstructor() && 9799 !RD.defaultedCopyConstructorIsDeleted()) 9800 return true; 9801 if (RD.needsImplicitMoveConstructor() && 9802 !RD.defaultedMoveConstructorIsDeleted()) 9803 return true; 9804 for (const CXXConstructorDecl *CD : RD.ctors()) 9805 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted()) 9806 return true; 9807 return false; 9808 }; 9809 9810 if (!HasNonDeletedCopyOrMoveConstructor()) { 9811 PrintDiagAndRemoveAttr(0); 9812 return; 9813 } 9814 9815 // Ill-formed if the struct has virtual functions. 9816 if (RD.isPolymorphic()) { 9817 PrintDiagAndRemoveAttr(1); 9818 return; 9819 } 9820 9821 for (const auto &B : RD.bases()) { 9822 // Ill-formed if the base class is non-trivial for the purpose of calls or a 9823 // virtual base. 9824 if (!B.getType()->isDependentType() && 9825 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) { 9826 PrintDiagAndRemoveAttr(2); 9827 return; 9828 } 9829 9830 if (B.isVirtual()) { 9831 PrintDiagAndRemoveAttr(3); 9832 return; 9833 } 9834 } 9835 9836 for (const auto *FD : RD.fields()) { 9837 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 9838 // non-trivial for the purpose of calls. 9839 QualType FT = FD->getType(); 9840 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 9841 PrintDiagAndRemoveAttr(4); 9842 return; 9843 } 9844 9845 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 9846 if (!RT->isDependentType() && 9847 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 9848 PrintDiagAndRemoveAttr(5); 9849 return; 9850 } 9851 } 9852 } 9853 9854 void Sema::ActOnFinishCXXMemberSpecification( 9855 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 9856 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 9857 if (!TagDecl) 9858 return; 9859 9860 AdjustDeclIfTemplate(TagDecl); 9861 9862 for (const ParsedAttr &AL : AttrList) { 9863 if (AL.getKind() != ParsedAttr::AT_Visibility) 9864 continue; 9865 AL.setInvalid(); 9866 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 9867 } 9868 9869 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 9870 // strict aliasing violation! 9871 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 9872 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 9873 9874 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 9875 } 9876 9877 /// Find the equality comparison functions that should be implicitly declared 9878 /// in a given class definition, per C++2a [class.compare.default]p3. 9879 static void findImplicitlyDeclaredEqualityComparisons( 9880 ASTContext &Ctx, CXXRecordDecl *RD, 9881 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 9882 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 9883 if (!RD->lookup(EqEq).empty()) 9884 // Member operator== explicitly declared: no implicit operator==s. 9885 return; 9886 9887 // Traverse friends looking for an '==' or a '<=>'. 9888 for (FriendDecl *Friend : RD->friends()) { 9889 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 9890 if (!FD) continue; 9891 9892 if (FD->getOverloadedOperator() == OO_EqualEqual) { 9893 // Friend operator== explicitly declared: no implicit operator==s. 9894 Spaceships.clear(); 9895 return; 9896 } 9897 9898 if (FD->getOverloadedOperator() == OO_Spaceship && 9899 FD->isExplicitlyDefaulted()) 9900 Spaceships.push_back(FD); 9901 } 9902 9903 // Look for members named 'operator<=>'. 9904 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 9905 for (NamedDecl *ND : RD->lookup(Cmp)) { 9906 // Note that we could find a non-function here (either a function template 9907 // or a using-declaration). Neither case results in an implicit 9908 // 'operator=='. 9909 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 9910 if (FD->isExplicitlyDefaulted()) 9911 Spaceships.push_back(FD); 9912 } 9913 } 9914 9915 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 9916 /// special functions, such as the default constructor, copy 9917 /// constructor, or destructor, to the given C++ class (C++ 9918 /// [special]p1). This routine can only be executed just before the 9919 /// definition of the class is complete. 9920 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 9921 // Don't add implicit special members to templated classes. 9922 // FIXME: This means unqualified lookups for 'operator=' within a class 9923 // template don't work properly. 9924 if (!ClassDecl->isDependentType()) { 9925 if (ClassDecl->needsImplicitDefaultConstructor()) { 9926 ++getASTContext().NumImplicitDefaultConstructors; 9927 9928 if (ClassDecl->hasInheritedConstructor()) 9929 DeclareImplicitDefaultConstructor(ClassDecl); 9930 } 9931 9932 if (ClassDecl->needsImplicitCopyConstructor()) { 9933 ++getASTContext().NumImplicitCopyConstructors; 9934 9935 // If the properties or semantics of the copy constructor couldn't be 9936 // determined while the class was being declared, force a declaration 9937 // of it now. 9938 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 9939 ClassDecl->hasInheritedConstructor()) 9940 DeclareImplicitCopyConstructor(ClassDecl); 9941 // For the MS ABI we need to know whether the copy ctor is deleted. A 9942 // prerequisite for deleting the implicit copy ctor is that the class has 9943 // a move ctor or move assignment that is either user-declared or whose 9944 // semantics are inherited from a subobject. FIXME: We should provide a 9945 // more direct way for CodeGen to ask whether the constructor was deleted. 9946 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 9947 (ClassDecl->hasUserDeclaredMoveConstructor() || 9948 ClassDecl->needsOverloadResolutionForMoveConstructor() || 9949 ClassDecl->hasUserDeclaredMoveAssignment() || 9950 ClassDecl->needsOverloadResolutionForMoveAssignment())) 9951 DeclareImplicitCopyConstructor(ClassDecl); 9952 } 9953 9954 if (getLangOpts().CPlusPlus11 && 9955 ClassDecl->needsImplicitMoveConstructor()) { 9956 ++getASTContext().NumImplicitMoveConstructors; 9957 9958 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 9959 ClassDecl->hasInheritedConstructor()) 9960 DeclareImplicitMoveConstructor(ClassDecl); 9961 } 9962 9963 if (ClassDecl->needsImplicitCopyAssignment()) { 9964 ++getASTContext().NumImplicitCopyAssignmentOperators; 9965 9966 // If we have a dynamic class, then the copy assignment operator may be 9967 // virtual, so we have to declare it immediately. This ensures that, e.g., 9968 // it shows up in the right place in the vtable and that we diagnose 9969 // problems with the implicit exception specification. 9970 if (ClassDecl->isDynamicClass() || 9971 ClassDecl->needsOverloadResolutionForCopyAssignment() || 9972 ClassDecl->hasInheritedAssignment()) 9973 DeclareImplicitCopyAssignment(ClassDecl); 9974 } 9975 9976 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 9977 ++getASTContext().NumImplicitMoveAssignmentOperators; 9978 9979 // Likewise for the move assignment operator. 9980 if (ClassDecl->isDynamicClass() || 9981 ClassDecl->needsOverloadResolutionForMoveAssignment() || 9982 ClassDecl->hasInheritedAssignment()) 9983 DeclareImplicitMoveAssignment(ClassDecl); 9984 } 9985 9986 if (ClassDecl->needsImplicitDestructor()) { 9987 ++getASTContext().NumImplicitDestructors; 9988 9989 // If we have a dynamic class, then the destructor may be virtual, so we 9990 // have to declare the destructor immediately. This ensures that, e.g., it 9991 // shows up in the right place in the vtable and that we diagnose problems 9992 // with the implicit exception specification. 9993 if (ClassDecl->isDynamicClass() || 9994 ClassDecl->needsOverloadResolutionForDestructor()) 9995 DeclareImplicitDestructor(ClassDecl); 9996 } 9997 } 9998 9999 // C++2a [class.compare.default]p3: 10000 // If the member-specification does not explicitly declare any member or 10001 // friend named operator==, an == operator function is declared implicitly 10002 // for each defaulted three-way comparison operator function defined in 10003 // the member-specification 10004 // FIXME: Consider doing this lazily. 10005 // We do this during the initial parse for a class template, not during 10006 // instantiation, so that we can handle unqualified lookups for 'operator==' 10007 // when parsing the template. 10008 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) { 10009 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships; 10010 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 10011 DefaultedSpaceships); 10012 for (auto *FD : DefaultedSpaceships) 10013 DeclareImplicitEqualityComparison(ClassDecl, FD); 10014 } 10015 } 10016 10017 unsigned 10018 Sema::ActOnReenterTemplateScope(Decl *D, 10019 llvm::function_ref<Scope *()> EnterScope) { 10020 if (!D) 10021 return 0; 10022 AdjustDeclIfTemplate(D); 10023 10024 // In order to get name lookup right, reenter template scopes in order from 10025 // outermost to innermost. 10026 SmallVector<TemplateParameterList *, 4> ParameterLists; 10027 DeclContext *LookupDC = dyn_cast<DeclContext>(D); 10028 10029 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 10030 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 10031 ParameterLists.push_back(DD->getTemplateParameterList(i)); 10032 10033 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10034 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 10035 ParameterLists.push_back(FTD->getTemplateParameters()); 10036 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 10037 LookupDC = VD->getDeclContext(); 10038 10039 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate()) 10040 ParameterLists.push_back(VTD->getTemplateParameters()); 10041 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) 10042 ParameterLists.push_back(PSD->getTemplateParameters()); 10043 } 10044 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 10045 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 10046 ParameterLists.push_back(TD->getTemplateParameterList(i)); 10047 10048 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 10049 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 10050 ParameterLists.push_back(CTD->getTemplateParameters()); 10051 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 10052 ParameterLists.push_back(PSD->getTemplateParameters()); 10053 } 10054 } 10055 // FIXME: Alias declarations and concepts. 10056 10057 unsigned Count = 0; 10058 Scope *InnermostTemplateScope = nullptr; 10059 for (TemplateParameterList *Params : ParameterLists) { 10060 // Ignore explicit specializations; they don't contribute to the template 10061 // depth. 10062 if (Params->size() == 0) 10063 continue; 10064 10065 InnermostTemplateScope = EnterScope(); 10066 for (NamedDecl *Param : *Params) { 10067 if (Param->getDeclName()) { 10068 InnermostTemplateScope->AddDecl(Param); 10069 IdResolver.AddDecl(Param); 10070 } 10071 } 10072 ++Count; 10073 } 10074 10075 // Associate the new template scopes with the corresponding entities. 10076 if (InnermostTemplateScope) { 10077 assert(LookupDC && "no enclosing DeclContext for template lookup"); 10078 EnterTemplatedContext(InnermostTemplateScope, LookupDC); 10079 } 10080 10081 return Count; 10082 } 10083 10084 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10085 if (!RecordD) return; 10086 AdjustDeclIfTemplate(RecordD); 10087 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 10088 PushDeclContext(S, Record); 10089 } 10090 10091 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10092 if (!RecordD) return; 10093 PopDeclContext(); 10094 } 10095 10096 /// This is used to implement the constant expression evaluation part of the 10097 /// attribute enable_if extension. There is nothing in standard C++ which would 10098 /// require reentering parameters. 10099 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 10100 if (!Param) 10101 return; 10102 10103 S->AddDecl(Param); 10104 if (Param->getDeclName()) 10105 IdResolver.AddDecl(Param); 10106 } 10107 10108 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 10109 /// parsing a top-level (non-nested) C++ class, and we are now 10110 /// parsing those parts of the given Method declaration that could 10111 /// not be parsed earlier (C++ [class.mem]p2), such as default 10112 /// arguments. This action should enter the scope of the given 10113 /// Method declaration as if we had just parsed the qualified method 10114 /// name. However, it should not bring the parameters into scope; 10115 /// that will be performed by ActOnDelayedCXXMethodParameter. 10116 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10117 } 10118 10119 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 10120 /// C++ method declaration. We're (re-)introducing the given 10121 /// function parameter into scope for use in parsing later parts of 10122 /// the method declaration. For example, we could see an 10123 /// ActOnParamDefaultArgument event for this parameter. 10124 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 10125 if (!ParamD) 10126 return; 10127 10128 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 10129 10130 S->AddDecl(Param); 10131 if (Param->getDeclName()) 10132 IdResolver.AddDecl(Param); 10133 } 10134 10135 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 10136 /// processing the delayed method declaration for Method. The method 10137 /// declaration is now considered finished. There may be a separate 10138 /// ActOnStartOfFunctionDef action later (not necessarily 10139 /// immediately!) for this method, if it was also defined inside the 10140 /// class body. 10141 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10142 if (!MethodD) 10143 return; 10144 10145 AdjustDeclIfTemplate(MethodD); 10146 10147 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 10148 10149 // Now that we have our default arguments, check the constructor 10150 // again. It could produce additional diagnostics or affect whether 10151 // the class has implicitly-declared destructors, among other 10152 // things. 10153 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 10154 CheckConstructor(Constructor); 10155 10156 // Check the default arguments, which we may have added. 10157 if (!Method->isInvalidDecl()) 10158 CheckCXXDefaultArguments(Method); 10159 } 10160 10161 // Emit the given diagnostic for each non-address-space qualifier. 10162 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 10163 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 10164 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10165 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 10166 bool DiagOccured = false; 10167 FTI.MethodQualifiers->forEachQualifier( 10168 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 10169 SourceLocation SL) { 10170 // This diagnostic should be emitted on any qualifier except an addr 10171 // space qualifier. However, forEachQualifier currently doesn't visit 10172 // addr space qualifiers, so there's no way to write this condition 10173 // right now; we just diagnose on everything. 10174 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 10175 DiagOccured = true; 10176 }); 10177 if (DiagOccured) 10178 D.setInvalidType(); 10179 } 10180 } 10181 10182 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 10183 /// the well-formedness of the constructor declarator @p D with type @p 10184 /// R. If there are any errors in the declarator, this routine will 10185 /// emit diagnostics and set the invalid bit to true. In any case, the type 10186 /// will be updated to reflect a well-formed type for the constructor and 10187 /// returned. 10188 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 10189 StorageClass &SC) { 10190 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 10191 10192 // C++ [class.ctor]p3: 10193 // A constructor shall not be virtual (10.3) or static (9.4). A 10194 // constructor can be invoked for a const, volatile or const 10195 // volatile object. A constructor shall not be declared const, 10196 // volatile, or const volatile (9.3.2). 10197 if (isVirtual) { 10198 if (!D.isInvalidType()) 10199 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10200 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 10201 << SourceRange(D.getIdentifierLoc()); 10202 D.setInvalidType(); 10203 } 10204 if (SC == SC_Static) { 10205 if (!D.isInvalidType()) 10206 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10207 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10208 << SourceRange(D.getIdentifierLoc()); 10209 D.setInvalidType(); 10210 SC = SC_None; 10211 } 10212 10213 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10214 diagnoseIgnoredQualifiers( 10215 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 10216 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 10217 D.getDeclSpec().getRestrictSpecLoc(), 10218 D.getDeclSpec().getAtomicSpecLoc()); 10219 D.setInvalidType(); 10220 } 10221 10222 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 10223 10224 // C++0x [class.ctor]p4: 10225 // A constructor shall not be declared with a ref-qualifier. 10226 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10227 if (FTI.hasRefQualifier()) { 10228 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 10229 << FTI.RefQualifierIsLValueRef 10230 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10231 D.setInvalidType(); 10232 } 10233 10234 // Rebuild the function type "R" without any type qualifiers (in 10235 // case any of the errors above fired) and with "void" as the 10236 // return type, since constructors don't have return types. 10237 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10238 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 10239 return R; 10240 10241 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10242 EPI.TypeQuals = Qualifiers(); 10243 EPI.RefQualifier = RQ_None; 10244 10245 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 10246 } 10247 10248 /// CheckConstructor - Checks a fully-formed constructor for 10249 /// well-formedness, issuing any diagnostics required. Returns true if 10250 /// the constructor declarator is invalid. 10251 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 10252 CXXRecordDecl *ClassDecl 10253 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 10254 if (!ClassDecl) 10255 return Constructor->setInvalidDecl(); 10256 10257 // C++ [class.copy]p3: 10258 // A declaration of a constructor for a class X is ill-formed if 10259 // its first parameter is of type (optionally cv-qualified) X and 10260 // either there are no other parameters or else all other 10261 // parameters have default arguments. 10262 if (!Constructor->isInvalidDecl() && 10263 Constructor->hasOneParamOrDefaultArgs() && 10264 Constructor->getTemplateSpecializationKind() != 10265 TSK_ImplicitInstantiation) { 10266 QualType ParamType = Constructor->getParamDecl(0)->getType(); 10267 QualType ClassTy = Context.getTagDeclType(ClassDecl); 10268 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 10269 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 10270 const char *ConstRef 10271 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 10272 : " const &"; 10273 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 10274 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 10275 10276 // FIXME: Rather that making the constructor invalid, we should endeavor 10277 // to fix the type. 10278 Constructor->setInvalidDecl(); 10279 } 10280 } 10281 } 10282 10283 /// CheckDestructor - Checks a fully-formed destructor definition for 10284 /// well-formedness, issuing any diagnostics required. Returns true 10285 /// on error. 10286 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 10287 CXXRecordDecl *RD = Destructor->getParent(); 10288 10289 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 10290 SourceLocation Loc; 10291 10292 if (!Destructor->isImplicit()) 10293 Loc = Destructor->getLocation(); 10294 else 10295 Loc = RD->getLocation(); 10296 10297 // If we have a virtual destructor, look up the deallocation function 10298 if (FunctionDecl *OperatorDelete = 10299 FindDeallocationFunctionForDestructor(Loc, RD)) { 10300 Expr *ThisArg = nullptr; 10301 10302 // If the notional 'delete this' expression requires a non-trivial 10303 // conversion from 'this' to the type of a destroying operator delete's 10304 // first parameter, perform that conversion now. 10305 if (OperatorDelete->isDestroyingOperatorDelete()) { 10306 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 10307 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 10308 // C++ [class.dtor]p13: 10309 // ... as if for the expression 'delete this' appearing in a 10310 // non-virtual destructor of the destructor's class. 10311 ContextRAII SwitchContext(*this, Destructor); 10312 ExprResult This = 10313 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 10314 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 10315 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 10316 if (This.isInvalid()) { 10317 // FIXME: Register this as a context note so that it comes out 10318 // in the right order. 10319 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 10320 return true; 10321 } 10322 ThisArg = This.get(); 10323 } 10324 } 10325 10326 DiagnoseUseOfDecl(OperatorDelete, Loc); 10327 MarkFunctionReferenced(Loc, OperatorDelete); 10328 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 10329 } 10330 } 10331 10332 return false; 10333 } 10334 10335 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 10336 /// the well-formednes of the destructor declarator @p D with type @p 10337 /// R. If there are any errors in the declarator, this routine will 10338 /// emit diagnostics and set the declarator to invalid. Even if this happens, 10339 /// will be updated to reflect a well-formed type for the destructor and 10340 /// returned. 10341 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 10342 StorageClass& SC) { 10343 // C++ [class.dtor]p1: 10344 // [...] A typedef-name that names a class is a class-name 10345 // (7.1.3); however, a typedef-name that names a class shall not 10346 // be used as the identifier in the declarator for a destructor 10347 // declaration. 10348 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 10349 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 10350 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10351 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 10352 else if (const TemplateSpecializationType *TST = 10353 DeclaratorType->getAs<TemplateSpecializationType>()) 10354 if (TST->isTypeAlias()) 10355 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10356 << DeclaratorType << 1; 10357 10358 // C++ [class.dtor]p2: 10359 // A destructor is used to destroy objects of its class type. A 10360 // destructor takes no parameters, and no return type can be 10361 // specified for it (not even void). The address of a destructor 10362 // shall not be taken. A destructor shall not be static. A 10363 // destructor can be invoked for a const, volatile or const 10364 // volatile object. A destructor shall not be declared const, 10365 // volatile or const volatile (9.3.2). 10366 if (SC == SC_Static) { 10367 if (!D.isInvalidType()) 10368 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 10369 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10370 << SourceRange(D.getIdentifierLoc()) 10371 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10372 10373 SC = SC_None; 10374 } 10375 if (!D.isInvalidType()) { 10376 // Destructors don't have return types, but the parser will 10377 // happily parse something like: 10378 // 10379 // class X { 10380 // float ~X(); 10381 // }; 10382 // 10383 // The return type will be eliminated later. 10384 if (D.getDeclSpec().hasTypeSpecifier()) 10385 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 10386 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 10387 << SourceRange(D.getIdentifierLoc()); 10388 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10389 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 10390 SourceLocation(), 10391 D.getDeclSpec().getConstSpecLoc(), 10392 D.getDeclSpec().getVolatileSpecLoc(), 10393 D.getDeclSpec().getRestrictSpecLoc(), 10394 D.getDeclSpec().getAtomicSpecLoc()); 10395 D.setInvalidType(); 10396 } 10397 } 10398 10399 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 10400 10401 // C++0x [class.dtor]p2: 10402 // A destructor shall not be declared with a ref-qualifier. 10403 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10404 if (FTI.hasRefQualifier()) { 10405 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 10406 << FTI.RefQualifierIsLValueRef 10407 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10408 D.setInvalidType(); 10409 } 10410 10411 // Make sure we don't have any parameters. 10412 if (FTIHasNonVoidParameters(FTI)) { 10413 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 10414 10415 // Delete the parameters. 10416 FTI.freeParams(); 10417 D.setInvalidType(); 10418 } 10419 10420 // Make sure the destructor isn't variadic. 10421 if (FTI.isVariadic) { 10422 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10423 D.setInvalidType(); 10424 } 10425 10426 // Rebuild the function type "R" without any type qualifiers or 10427 // parameters (in case any of the errors above fired) and with 10428 // "void" as the return type, since destructors don't have return 10429 // types. 10430 if (!D.isInvalidType()) 10431 return R; 10432 10433 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10434 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10435 EPI.Variadic = false; 10436 EPI.TypeQuals = Qualifiers(); 10437 EPI.RefQualifier = RQ_None; 10438 return Context.getFunctionType(Context.VoidTy, None, EPI); 10439 } 10440 10441 static void extendLeft(SourceRange &R, SourceRange Before) { 10442 if (Before.isInvalid()) 10443 return; 10444 R.setBegin(Before.getBegin()); 10445 if (R.getEnd().isInvalid()) 10446 R.setEnd(Before.getEnd()); 10447 } 10448 10449 static void extendRight(SourceRange &R, SourceRange After) { 10450 if (After.isInvalid()) 10451 return; 10452 if (R.getBegin().isInvalid()) 10453 R.setBegin(After.getBegin()); 10454 R.setEnd(After.getEnd()); 10455 } 10456 10457 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10458 /// well-formednes of the conversion function declarator @p D with 10459 /// type @p R. If there are any errors in the declarator, this routine 10460 /// will emit diagnostics and return true. Otherwise, it will return 10461 /// false. Either way, the type @p R will be updated to reflect a 10462 /// well-formed type for the conversion operator. 10463 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10464 StorageClass& SC) { 10465 // C++ [class.conv.fct]p1: 10466 // Neither parameter types nor return type can be specified. The 10467 // type of a conversion function (8.3.5) is "function taking no 10468 // parameter returning conversion-type-id." 10469 if (SC == SC_Static) { 10470 if (!D.isInvalidType()) 10471 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10472 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10473 << D.getName().getSourceRange(); 10474 D.setInvalidType(); 10475 SC = SC_None; 10476 } 10477 10478 TypeSourceInfo *ConvTSI = nullptr; 10479 QualType ConvType = 10480 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10481 10482 const DeclSpec &DS = D.getDeclSpec(); 10483 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10484 // Conversion functions don't have return types, but the parser will 10485 // happily parse something like: 10486 // 10487 // class X { 10488 // float operator bool(); 10489 // }; 10490 // 10491 // The return type will be changed later anyway. 10492 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10493 << SourceRange(DS.getTypeSpecTypeLoc()) 10494 << SourceRange(D.getIdentifierLoc()); 10495 D.setInvalidType(); 10496 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10497 // It's also plausible that the user writes type qualifiers in the wrong 10498 // place, such as: 10499 // struct S { const operator int(); }; 10500 // FIXME: we could provide a fixit to move the qualifiers onto the 10501 // conversion type. 10502 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10503 << SourceRange(D.getIdentifierLoc()) << 0; 10504 D.setInvalidType(); 10505 } 10506 10507 const auto *Proto = R->castAs<FunctionProtoType>(); 10508 10509 // Make sure we don't have any parameters. 10510 if (Proto->getNumParams() > 0) { 10511 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10512 10513 // Delete the parameters. 10514 D.getFunctionTypeInfo().freeParams(); 10515 D.setInvalidType(); 10516 } else if (Proto->isVariadic()) { 10517 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10518 D.setInvalidType(); 10519 } 10520 10521 // Diagnose "&operator bool()" and other such nonsense. This 10522 // is actually a gcc extension which we don't support. 10523 if (Proto->getReturnType() != ConvType) { 10524 bool NeedsTypedef = false; 10525 SourceRange Before, After; 10526 10527 // Walk the chunks and extract information on them for our diagnostic. 10528 bool PastFunctionChunk = false; 10529 for (auto &Chunk : D.type_objects()) { 10530 switch (Chunk.Kind) { 10531 case DeclaratorChunk::Function: 10532 if (!PastFunctionChunk) { 10533 if (Chunk.Fun.HasTrailingReturnType) { 10534 TypeSourceInfo *TRT = nullptr; 10535 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10536 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10537 } 10538 PastFunctionChunk = true; 10539 break; 10540 } 10541 LLVM_FALLTHROUGH; 10542 case DeclaratorChunk::Array: 10543 NeedsTypedef = true; 10544 extendRight(After, Chunk.getSourceRange()); 10545 break; 10546 10547 case DeclaratorChunk::Pointer: 10548 case DeclaratorChunk::BlockPointer: 10549 case DeclaratorChunk::Reference: 10550 case DeclaratorChunk::MemberPointer: 10551 case DeclaratorChunk::Pipe: 10552 extendLeft(Before, Chunk.getSourceRange()); 10553 break; 10554 10555 case DeclaratorChunk::Paren: 10556 extendLeft(Before, Chunk.Loc); 10557 extendRight(After, Chunk.EndLoc); 10558 break; 10559 } 10560 } 10561 10562 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10563 After.isValid() ? After.getBegin() : 10564 D.getIdentifierLoc(); 10565 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10566 DB << Before << After; 10567 10568 if (!NeedsTypedef) { 10569 DB << /*don't need a typedef*/0; 10570 10571 // If we can provide a correct fix-it hint, do so. 10572 if (After.isInvalid() && ConvTSI) { 10573 SourceLocation InsertLoc = 10574 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10575 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10576 << FixItHint::CreateInsertionFromRange( 10577 InsertLoc, CharSourceRange::getTokenRange(Before)) 10578 << FixItHint::CreateRemoval(Before); 10579 } 10580 } else if (!Proto->getReturnType()->isDependentType()) { 10581 DB << /*typedef*/1 << Proto->getReturnType(); 10582 } else if (getLangOpts().CPlusPlus11) { 10583 DB << /*alias template*/2 << Proto->getReturnType(); 10584 } else { 10585 DB << /*might not be fixable*/3; 10586 } 10587 10588 // Recover by incorporating the other type chunks into the result type. 10589 // Note, this does *not* change the name of the function. This is compatible 10590 // with the GCC extension: 10591 // struct S { &operator int(); } s; 10592 // int &r = s.operator int(); // ok in GCC 10593 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10594 ConvType = Proto->getReturnType(); 10595 } 10596 10597 // C++ [class.conv.fct]p4: 10598 // The conversion-type-id shall not represent a function type nor 10599 // an array type. 10600 if (ConvType->isArrayType()) { 10601 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10602 ConvType = Context.getPointerType(ConvType); 10603 D.setInvalidType(); 10604 } else if (ConvType->isFunctionType()) { 10605 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10606 ConvType = Context.getPointerType(ConvType); 10607 D.setInvalidType(); 10608 } 10609 10610 // Rebuild the function type "R" without any parameters (in case any 10611 // of the errors above fired) and with the conversion type as the 10612 // return type. 10613 if (D.isInvalidType()) 10614 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 10615 10616 // C++0x explicit conversion operators. 10617 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20) 10618 Diag(DS.getExplicitSpecLoc(), 10619 getLangOpts().CPlusPlus11 10620 ? diag::warn_cxx98_compat_explicit_conversion_functions 10621 : diag::ext_explicit_conversion_functions) 10622 << SourceRange(DS.getExplicitSpecRange()); 10623 } 10624 10625 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 10626 /// the declaration of the given C++ conversion function. This routine 10627 /// is responsible for recording the conversion function in the C++ 10628 /// class, if possible. 10629 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 10630 assert(Conversion && "Expected to receive a conversion function declaration"); 10631 10632 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 10633 10634 // Make sure we aren't redeclaring the conversion function. 10635 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 10636 // C++ [class.conv.fct]p1: 10637 // [...] A conversion function is never used to convert a 10638 // (possibly cv-qualified) object to the (possibly cv-qualified) 10639 // same object type (or a reference to it), to a (possibly 10640 // cv-qualified) base class of that type (or a reference to it), 10641 // or to (possibly cv-qualified) void. 10642 QualType ClassType 10643 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10644 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 10645 ConvType = ConvTypeRef->getPointeeType(); 10646 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 10647 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 10648 /* Suppress diagnostics for instantiations. */; 10649 else if (Conversion->size_overridden_methods() != 0) 10650 /* Suppress diagnostics for overriding virtual function in a base class. */; 10651 else if (ConvType->isRecordType()) { 10652 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 10653 if (ConvType == ClassType) 10654 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 10655 << ClassType; 10656 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 10657 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 10658 << ClassType << ConvType; 10659 } else if (ConvType->isVoidType()) { 10660 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 10661 << ClassType << ConvType; 10662 } 10663 10664 if (FunctionTemplateDecl *ConversionTemplate 10665 = Conversion->getDescribedFunctionTemplate()) 10666 return ConversionTemplate; 10667 10668 return Conversion; 10669 } 10670 10671 namespace { 10672 /// Utility class to accumulate and print a diagnostic listing the invalid 10673 /// specifier(s) on a declaration. 10674 struct BadSpecifierDiagnoser { 10675 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10676 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10677 ~BadSpecifierDiagnoser() { 10678 Diagnostic << Specifiers; 10679 } 10680 10681 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10682 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10683 } 10684 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10685 return check(SpecLoc, 10686 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10687 } 10688 void check(SourceLocation SpecLoc, const char *Spec) { 10689 if (SpecLoc.isInvalid()) return; 10690 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10691 if (!Specifiers.empty()) Specifiers += " "; 10692 Specifiers += Spec; 10693 } 10694 10695 Sema &S; 10696 Sema::SemaDiagnosticBuilder Diagnostic; 10697 std::string Specifiers; 10698 }; 10699 } 10700 10701 /// Check the validity of a declarator that we parsed for a deduction-guide. 10702 /// These aren't actually declarators in the grammar, so we need to check that 10703 /// the user didn't specify any pieces that are not part of the deduction-guide 10704 /// grammar. 10705 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10706 StorageClass &SC) { 10707 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10708 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10709 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 10710 10711 // C++ [temp.deduct.guide]p3: 10712 // A deduction-gide shall be declared in the same scope as the 10713 // corresponding class template. 10714 if (!CurContext->getRedeclContext()->Equals( 10715 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10716 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10717 << GuidedTemplateDecl; 10718 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10719 } 10720 10721 auto &DS = D.getMutableDeclSpec(); 10722 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10723 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10724 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10725 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10726 BadSpecifierDiagnoser Diagnoser( 10727 *this, D.getIdentifierLoc(), 10728 diag::err_deduction_guide_invalid_specifier); 10729 10730 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10731 DS.ClearStorageClassSpecs(); 10732 SC = SC_None; 10733 10734 // 'explicit' is permitted. 10735 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10736 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10737 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10738 DS.ClearConstexprSpec(); 10739 10740 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10741 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10742 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10743 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10744 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10745 DS.ClearTypeQualifiers(); 10746 10747 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 10748 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 10749 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 10750 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 10751 DS.ClearTypeSpecType(); 10752 } 10753 10754 if (D.isInvalidType()) 10755 return; 10756 10757 // Check the declarator is simple enough. 10758 bool FoundFunction = false; 10759 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 10760 if (Chunk.Kind == DeclaratorChunk::Paren) 10761 continue; 10762 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 10763 Diag(D.getDeclSpec().getBeginLoc(), 10764 diag::err_deduction_guide_with_complex_decl) 10765 << D.getSourceRange(); 10766 break; 10767 } 10768 if (!Chunk.Fun.hasTrailingReturnType()) { 10769 Diag(D.getName().getBeginLoc(), 10770 diag::err_deduction_guide_no_trailing_return_type); 10771 break; 10772 } 10773 10774 // Check that the return type is written as a specialization of 10775 // the template specified as the deduction-guide's name. 10776 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 10777 TypeSourceInfo *TSI = nullptr; 10778 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 10779 assert(TSI && "deduction guide has valid type but invalid return type?"); 10780 bool AcceptableReturnType = false; 10781 bool MightInstantiateToSpecialization = false; 10782 if (auto RetTST = 10783 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 10784 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 10785 bool TemplateMatches = 10786 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 10787 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 10788 AcceptableReturnType = true; 10789 else { 10790 // This could still instantiate to the right type, unless we know it 10791 // names the wrong class template. 10792 auto *TD = SpecifiedName.getAsTemplateDecl(); 10793 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 10794 !TemplateMatches); 10795 } 10796 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 10797 MightInstantiateToSpecialization = true; 10798 } 10799 10800 if (!AcceptableReturnType) { 10801 Diag(TSI->getTypeLoc().getBeginLoc(), 10802 diag::err_deduction_guide_bad_trailing_return_type) 10803 << GuidedTemplate << TSI->getType() 10804 << MightInstantiateToSpecialization 10805 << TSI->getTypeLoc().getSourceRange(); 10806 } 10807 10808 // Keep going to check that we don't have any inner declarator pieces (we 10809 // could still have a function returning a pointer to a function). 10810 FoundFunction = true; 10811 } 10812 10813 if (D.isFunctionDefinition()) 10814 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 10815 } 10816 10817 //===----------------------------------------------------------------------===// 10818 // Namespace Handling 10819 //===----------------------------------------------------------------------===// 10820 10821 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 10822 /// reopened. 10823 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 10824 SourceLocation Loc, 10825 IdentifierInfo *II, bool *IsInline, 10826 NamespaceDecl *PrevNS) { 10827 assert(*IsInline != PrevNS->isInline()); 10828 10829 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 10830 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 10831 // inline namespaces, with the intention of bringing names into namespace std. 10832 // 10833 // We support this just well enough to get that case working; this is not 10834 // sufficient to support reopening namespaces as inline in general. 10835 if (*IsInline && II && II->getName().startswith("__atomic") && 10836 S.getSourceManager().isInSystemHeader(Loc)) { 10837 // Mark all prior declarations of the namespace as inline. 10838 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 10839 NS = NS->getPreviousDecl()) 10840 NS->setInline(*IsInline); 10841 // Patch up the lookup table for the containing namespace. This isn't really 10842 // correct, but it's good enough for this particular case. 10843 for (auto *I : PrevNS->decls()) 10844 if (auto *ND = dyn_cast<NamedDecl>(I)) 10845 PrevNS->getParent()->makeDeclVisibleInContext(ND); 10846 return; 10847 } 10848 10849 if (PrevNS->isInline()) 10850 // The user probably just forgot the 'inline', so suggest that it 10851 // be added back. 10852 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 10853 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 10854 else 10855 S.Diag(Loc, diag::err_inline_namespace_mismatch); 10856 10857 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 10858 *IsInline = PrevNS->isInline(); 10859 } 10860 10861 /// ActOnStartNamespaceDef - This is called at the start of a namespace 10862 /// definition. 10863 Decl *Sema::ActOnStartNamespaceDef( 10864 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 10865 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 10866 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 10867 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 10868 // For anonymous namespace, take the location of the left brace. 10869 SourceLocation Loc = II ? IdentLoc : LBrace; 10870 bool IsInline = InlineLoc.isValid(); 10871 bool IsInvalid = false; 10872 bool IsStd = false; 10873 bool AddToKnown = false; 10874 Scope *DeclRegionScope = NamespcScope->getParent(); 10875 10876 NamespaceDecl *PrevNS = nullptr; 10877 if (II) { 10878 // C++ [namespace.def]p2: 10879 // The identifier in an original-namespace-definition shall not 10880 // have been previously defined in the declarative region in 10881 // which the original-namespace-definition appears. The 10882 // identifier in an original-namespace-definition is the name of 10883 // the namespace. Subsequently in that declarative region, it is 10884 // treated as an original-namespace-name. 10885 // 10886 // Since namespace names are unique in their scope, and we don't 10887 // look through using directives, just look for any ordinary names 10888 // as if by qualified name lookup. 10889 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 10890 ForExternalRedeclaration); 10891 LookupQualifiedName(R, CurContext->getRedeclContext()); 10892 NamedDecl *PrevDecl = 10893 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 10894 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 10895 10896 if (PrevNS) { 10897 // This is an extended namespace definition. 10898 if (IsInline != PrevNS->isInline()) 10899 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 10900 &IsInline, PrevNS); 10901 } else if (PrevDecl) { 10902 // This is an invalid name redefinition. 10903 Diag(Loc, diag::err_redefinition_different_kind) 10904 << II; 10905 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10906 IsInvalid = true; 10907 // Continue on to push Namespc as current DeclContext and return it. 10908 } else if (II->isStr("std") && 10909 CurContext->getRedeclContext()->isTranslationUnit()) { 10910 // This is the first "real" definition of the namespace "std", so update 10911 // our cache of the "std" namespace to point at this definition. 10912 PrevNS = getStdNamespace(); 10913 IsStd = true; 10914 AddToKnown = !IsInline; 10915 } else { 10916 // We've seen this namespace for the first time. 10917 AddToKnown = !IsInline; 10918 } 10919 } else { 10920 // Anonymous namespaces. 10921 10922 // Determine whether the parent already has an anonymous namespace. 10923 DeclContext *Parent = CurContext->getRedeclContext(); 10924 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10925 PrevNS = TU->getAnonymousNamespace(); 10926 } else { 10927 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 10928 PrevNS = ND->getAnonymousNamespace(); 10929 } 10930 10931 if (PrevNS && IsInline != PrevNS->isInline()) 10932 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 10933 &IsInline, PrevNS); 10934 } 10935 10936 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 10937 StartLoc, Loc, II, PrevNS); 10938 if (IsInvalid) 10939 Namespc->setInvalidDecl(); 10940 10941 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 10942 AddPragmaAttributes(DeclRegionScope, Namespc); 10943 10944 // FIXME: Should we be merging attributes? 10945 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 10946 PushNamespaceVisibilityAttr(Attr, Loc); 10947 10948 if (IsStd) 10949 StdNamespace = Namespc; 10950 if (AddToKnown) 10951 KnownNamespaces[Namespc] = false; 10952 10953 if (II) { 10954 PushOnScopeChains(Namespc, DeclRegionScope); 10955 } else { 10956 // Link the anonymous namespace into its parent. 10957 DeclContext *Parent = CurContext->getRedeclContext(); 10958 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10959 TU->setAnonymousNamespace(Namespc); 10960 } else { 10961 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 10962 } 10963 10964 CurContext->addDecl(Namespc); 10965 10966 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 10967 // behaves as if it were replaced by 10968 // namespace unique { /* empty body */ } 10969 // using namespace unique; 10970 // namespace unique { namespace-body } 10971 // where all occurrences of 'unique' in a translation unit are 10972 // replaced by the same identifier and this identifier differs 10973 // from all other identifiers in the entire program. 10974 10975 // We just create the namespace with an empty name and then add an 10976 // implicit using declaration, just like the standard suggests. 10977 // 10978 // CodeGen enforces the "universally unique" aspect by giving all 10979 // declarations semantically contained within an anonymous 10980 // namespace internal linkage. 10981 10982 if (!PrevNS) { 10983 UD = UsingDirectiveDecl::Create(Context, Parent, 10984 /* 'using' */ LBrace, 10985 /* 'namespace' */ SourceLocation(), 10986 /* qualifier */ NestedNameSpecifierLoc(), 10987 /* identifier */ SourceLocation(), 10988 Namespc, 10989 /* Ancestor */ Parent); 10990 UD->setImplicit(); 10991 Parent->addDecl(UD); 10992 } 10993 } 10994 10995 ActOnDocumentableDecl(Namespc); 10996 10997 // Although we could have an invalid decl (i.e. the namespace name is a 10998 // redefinition), push it as current DeclContext and try to continue parsing. 10999 // FIXME: We should be able to push Namespc here, so that the each DeclContext 11000 // for the namespace has the declarations that showed up in that particular 11001 // namespace definition. 11002 PushDeclContext(NamespcScope, Namespc); 11003 return Namespc; 11004 } 11005 11006 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 11007 /// is a namespace alias, returns the namespace it points to. 11008 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 11009 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 11010 return AD->getNamespace(); 11011 return dyn_cast_or_null<NamespaceDecl>(D); 11012 } 11013 11014 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 11015 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 11016 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 11017 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 11018 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 11019 Namespc->setRBraceLoc(RBrace); 11020 PopDeclContext(); 11021 if (Namespc->hasAttr<VisibilityAttr>()) 11022 PopPragmaVisibility(true, RBrace); 11023 // If this namespace contains an export-declaration, export it now. 11024 if (DeferredExportedNamespaces.erase(Namespc)) 11025 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 11026 } 11027 11028 CXXRecordDecl *Sema::getStdBadAlloc() const { 11029 return cast_or_null<CXXRecordDecl>( 11030 StdBadAlloc.get(Context.getExternalSource())); 11031 } 11032 11033 EnumDecl *Sema::getStdAlignValT() const { 11034 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 11035 } 11036 11037 NamespaceDecl *Sema::getStdNamespace() const { 11038 return cast_or_null<NamespaceDecl>( 11039 StdNamespace.get(Context.getExternalSource())); 11040 } 11041 11042 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 11043 if (!StdExperimentalNamespaceCache) { 11044 if (auto Std = getStdNamespace()) { 11045 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 11046 SourceLocation(), LookupNamespaceName); 11047 if (!LookupQualifiedName(Result, Std) || 11048 !(StdExperimentalNamespaceCache = 11049 Result.getAsSingle<NamespaceDecl>())) 11050 Result.suppressDiagnostics(); 11051 } 11052 } 11053 return StdExperimentalNamespaceCache; 11054 } 11055 11056 namespace { 11057 11058 enum UnsupportedSTLSelect { 11059 USS_InvalidMember, 11060 USS_MissingMember, 11061 USS_NonTrivial, 11062 USS_Other 11063 }; 11064 11065 struct InvalidSTLDiagnoser { 11066 Sema &S; 11067 SourceLocation Loc; 11068 QualType TyForDiags; 11069 11070 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 11071 const VarDecl *VD = nullptr) { 11072 { 11073 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 11074 << TyForDiags << ((int)Sel); 11075 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 11076 assert(!Name.empty()); 11077 D << Name; 11078 } 11079 } 11080 if (Sel == USS_InvalidMember) { 11081 S.Diag(VD->getLocation(), diag::note_var_declared_here) 11082 << VD << VD->getSourceRange(); 11083 } 11084 return QualType(); 11085 } 11086 }; 11087 } // namespace 11088 11089 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 11090 SourceLocation Loc, 11091 ComparisonCategoryUsage Usage) { 11092 assert(getLangOpts().CPlusPlus && 11093 "Looking for comparison category type outside of C++."); 11094 11095 // Use an elaborated type for diagnostics which has a name containing the 11096 // prepended 'std' namespace but not any inline namespace names. 11097 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 11098 auto *NNS = 11099 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 11100 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 11101 }; 11102 11103 // Check if we've already successfully checked the comparison category type 11104 // before. If so, skip checking it again. 11105 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 11106 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 11107 // The only thing we need to check is that the type has a reachable 11108 // definition in the current context. 11109 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11110 return QualType(); 11111 11112 return Info->getType(); 11113 } 11114 11115 // If lookup failed 11116 if (!Info) { 11117 std::string NameForDiags = "std::"; 11118 NameForDiags += ComparisonCategories::getCategoryString(Kind); 11119 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 11120 << NameForDiags << (int)Usage; 11121 return QualType(); 11122 } 11123 11124 assert(Info->Kind == Kind); 11125 assert(Info->Record); 11126 11127 // Update the Record decl in case we encountered a forward declaration on our 11128 // first pass. FIXME: This is a bit of a hack. 11129 if (Info->Record->hasDefinition()) 11130 Info->Record = Info->Record->getDefinition(); 11131 11132 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11133 return QualType(); 11134 11135 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 11136 11137 if (!Info->Record->isTriviallyCopyable()) 11138 return UnsupportedSTLError(USS_NonTrivial); 11139 11140 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 11141 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 11142 // Tolerate empty base classes. 11143 if (Base->isEmpty()) 11144 continue; 11145 // Reject STL implementations which have at least one non-empty base. 11146 return UnsupportedSTLError(); 11147 } 11148 11149 // Check that the STL has implemented the types using a single integer field. 11150 // This expectation allows better codegen for builtin operators. We require: 11151 // (1) The class has exactly one field. 11152 // (2) The field is an integral or enumeration type. 11153 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 11154 if (std::distance(FIt, FEnd) != 1 || 11155 !FIt->getType()->isIntegralOrEnumerationType()) { 11156 return UnsupportedSTLError(); 11157 } 11158 11159 // Build each of the require values and store them in Info. 11160 for (ComparisonCategoryResult CCR : 11161 ComparisonCategories::getPossibleResultsForType(Kind)) { 11162 StringRef MemName = ComparisonCategories::getResultString(CCR); 11163 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 11164 11165 if (!ValInfo) 11166 return UnsupportedSTLError(USS_MissingMember, MemName); 11167 11168 VarDecl *VD = ValInfo->VD; 11169 assert(VD && "should not be null!"); 11170 11171 // Attempt to diagnose reasons why the STL definition of this type 11172 // might be foobar, including it failing to be a constant expression. 11173 // TODO Handle more ways the lookup or result can be invalid. 11174 if (!VD->isStaticDataMember() || 11175 !VD->isUsableInConstantExpressions(Context)) 11176 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 11177 11178 // Attempt to evaluate the var decl as a constant expression and extract 11179 // the value of its first field as a ICE. If this fails, the STL 11180 // implementation is not supported. 11181 if (!ValInfo->hasValidIntValue()) 11182 return UnsupportedSTLError(); 11183 11184 MarkVariableReferenced(Loc, VD); 11185 } 11186 11187 // We've successfully built the required types and expressions. Update 11188 // the cache and return the newly cached value. 11189 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 11190 return Info->getType(); 11191 } 11192 11193 /// Retrieve the special "std" namespace, which may require us to 11194 /// implicitly define the namespace. 11195 NamespaceDecl *Sema::getOrCreateStdNamespace() { 11196 if (!StdNamespace) { 11197 // The "std" namespace has not yet been defined, so build one implicitly. 11198 StdNamespace = NamespaceDecl::Create(Context, 11199 Context.getTranslationUnitDecl(), 11200 /*Inline=*/false, 11201 SourceLocation(), SourceLocation(), 11202 &PP.getIdentifierTable().get("std"), 11203 /*PrevDecl=*/nullptr); 11204 getStdNamespace()->setImplicit(true); 11205 } 11206 11207 return getStdNamespace(); 11208 } 11209 11210 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 11211 assert(getLangOpts().CPlusPlus && 11212 "Looking for std::initializer_list outside of C++."); 11213 11214 // We're looking for implicit instantiations of 11215 // template <typename E> class std::initializer_list. 11216 11217 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 11218 return false; 11219 11220 ClassTemplateDecl *Template = nullptr; 11221 const TemplateArgument *Arguments = nullptr; 11222 11223 if (const RecordType *RT = Ty->getAs<RecordType>()) { 11224 11225 ClassTemplateSpecializationDecl *Specialization = 11226 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 11227 if (!Specialization) 11228 return false; 11229 11230 Template = Specialization->getSpecializedTemplate(); 11231 Arguments = Specialization->getTemplateArgs().data(); 11232 } else if (const TemplateSpecializationType *TST = 11233 Ty->getAs<TemplateSpecializationType>()) { 11234 Template = dyn_cast_or_null<ClassTemplateDecl>( 11235 TST->getTemplateName().getAsTemplateDecl()); 11236 Arguments = TST->getArgs(); 11237 } 11238 if (!Template) 11239 return false; 11240 11241 if (!StdInitializerList) { 11242 // Haven't recognized std::initializer_list yet, maybe this is it. 11243 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 11244 if (TemplateClass->getIdentifier() != 11245 &PP.getIdentifierTable().get("initializer_list") || 11246 !getStdNamespace()->InEnclosingNamespaceSetOf( 11247 TemplateClass->getDeclContext())) 11248 return false; 11249 // This is a template called std::initializer_list, but is it the right 11250 // template? 11251 TemplateParameterList *Params = Template->getTemplateParameters(); 11252 if (Params->getMinRequiredArguments() != 1) 11253 return false; 11254 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 11255 return false; 11256 11257 // It's the right template. 11258 StdInitializerList = Template; 11259 } 11260 11261 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 11262 return false; 11263 11264 // This is an instance of std::initializer_list. Find the argument type. 11265 if (Element) 11266 *Element = Arguments[0].getAsType(); 11267 return true; 11268 } 11269 11270 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 11271 NamespaceDecl *Std = S.getStdNamespace(); 11272 if (!Std) { 11273 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11274 return nullptr; 11275 } 11276 11277 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 11278 Loc, Sema::LookupOrdinaryName); 11279 if (!S.LookupQualifiedName(Result, Std)) { 11280 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11281 return nullptr; 11282 } 11283 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 11284 if (!Template) { 11285 Result.suppressDiagnostics(); 11286 // We found something weird. Complain about the first thing we found. 11287 NamedDecl *Found = *Result.begin(); 11288 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 11289 return nullptr; 11290 } 11291 11292 // We found some template called std::initializer_list. Now verify that it's 11293 // correct. 11294 TemplateParameterList *Params = Template->getTemplateParameters(); 11295 if (Params->getMinRequiredArguments() != 1 || 11296 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 11297 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 11298 return nullptr; 11299 } 11300 11301 return Template; 11302 } 11303 11304 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 11305 if (!StdInitializerList) { 11306 StdInitializerList = LookupStdInitializerList(*this, Loc); 11307 if (!StdInitializerList) 11308 return QualType(); 11309 } 11310 11311 TemplateArgumentListInfo Args(Loc, Loc); 11312 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 11313 Context.getTrivialTypeSourceInfo(Element, 11314 Loc))); 11315 return Context.getCanonicalType( 11316 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 11317 } 11318 11319 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 11320 // C++ [dcl.init.list]p2: 11321 // A constructor is an initializer-list constructor if its first parameter 11322 // is of type std::initializer_list<E> or reference to possibly cv-qualified 11323 // std::initializer_list<E> for some type E, and either there are no other 11324 // parameters or else all other parameters have default arguments. 11325 if (!Ctor->hasOneParamOrDefaultArgs()) 11326 return false; 11327 11328 QualType ArgType = Ctor->getParamDecl(0)->getType(); 11329 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 11330 ArgType = RT->getPointeeType().getUnqualifiedType(); 11331 11332 return isStdInitializerList(ArgType, nullptr); 11333 } 11334 11335 /// Determine whether a using statement is in a context where it will be 11336 /// apply in all contexts. 11337 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 11338 switch (CurContext->getDeclKind()) { 11339 case Decl::TranslationUnit: 11340 return true; 11341 case Decl::LinkageSpec: 11342 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 11343 default: 11344 return false; 11345 } 11346 } 11347 11348 namespace { 11349 11350 // Callback to only accept typo corrections that are namespaces. 11351 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 11352 public: 11353 bool ValidateCandidate(const TypoCorrection &candidate) override { 11354 if (NamedDecl *ND = candidate.getCorrectionDecl()) 11355 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 11356 return false; 11357 } 11358 11359 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11360 return std::make_unique<NamespaceValidatorCCC>(*this); 11361 } 11362 }; 11363 11364 } 11365 11366 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 11367 CXXScopeSpec &SS, 11368 SourceLocation IdentLoc, 11369 IdentifierInfo *Ident) { 11370 R.clear(); 11371 NamespaceValidatorCCC CCC{}; 11372 if (TypoCorrection Corrected = 11373 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 11374 Sema::CTK_ErrorRecovery)) { 11375 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 11376 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 11377 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 11378 Ident->getName().equals(CorrectedStr); 11379 S.diagnoseTypo(Corrected, 11380 S.PDiag(diag::err_using_directive_member_suggest) 11381 << Ident << DC << DroppedSpecifier << SS.getRange(), 11382 S.PDiag(diag::note_namespace_defined_here)); 11383 } else { 11384 S.diagnoseTypo(Corrected, 11385 S.PDiag(diag::err_using_directive_suggest) << Ident, 11386 S.PDiag(diag::note_namespace_defined_here)); 11387 } 11388 R.addDecl(Corrected.getFoundDecl()); 11389 return true; 11390 } 11391 return false; 11392 } 11393 11394 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 11395 SourceLocation NamespcLoc, CXXScopeSpec &SS, 11396 SourceLocation IdentLoc, 11397 IdentifierInfo *NamespcName, 11398 const ParsedAttributesView &AttrList) { 11399 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11400 assert(NamespcName && "Invalid NamespcName."); 11401 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 11402 11403 // This can only happen along a recovery path. 11404 while (S->isTemplateParamScope()) 11405 S = S->getParent(); 11406 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11407 11408 UsingDirectiveDecl *UDir = nullptr; 11409 NestedNameSpecifier *Qualifier = nullptr; 11410 if (SS.isSet()) 11411 Qualifier = SS.getScopeRep(); 11412 11413 // Lookup namespace name. 11414 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 11415 LookupParsedName(R, S, &SS); 11416 if (R.isAmbiguous()) 11417 return nullptr; 11418 11419 if (R.empty()) { 11420 R.clear(); 11421 // Allow "using namespace std;" or "using namespace ::std;" even if 11422 // "std" hasn't been defined yet, for GCC compatibility. 11423 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11424 NamespcName->isStr("std")) { 11425 Diag(IdentLoc, diag::ext_using_undefined_std); 11426 R.addDecl(getOrCreateStdNamespace()); 11427 R.resolveKind(); 11428 } 11429 // Otherwise, attempt typo correction. 11430 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11431 } 11432 11433 if (!R.empty()) { 11434 NamedDecl *Named = R.getRepresentativeDecl(); 11435 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11436 assert(NS && "expected namespace decl"); 11437 11438 // The use of a nested name specifier may trigger deprecation warnings. 11439 DiagnoseUseOfDecl(Named, IdentLoc); 11440 11441 // C++ [namespace.udir]p1: 11442 // A using-directive specifies that the names in the nominated 11443 // namespace can be used in the scope in which the 11444 // using-directive appears after the using-directive. During 11445 // unqualified name lookup (3.4.1), the names appear as if they 11446 // were declared in the nearest enclosing namespace which 11447 // contains both the using-directive and the nominated 11448 // namespace. [Note: in this context, "contains" means "contains 11449 // directly or indirectly". ] 11450 11451 // Find enclosing context containing both using-directive and 11452 // nominated namespace. 11453 DeclContext *CommonAncestor = NS; 11454 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11455 CommonAncestor = CommonAncestor->getParent(); 11456 11457 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11458 SS.getWithLocInContext(Context), 11459 IdentLoc, Named, CommonAncestor); 11460 11461 if (IsUsingDirectiveInToplevelContext(CurContext) && 11462 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11463 Diag(IdentLoc, diag::warn_using_directive_in_header); 11464 } 11465 11466 PushUsingDirective(S, UDir); 11467 } else { 11468 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11469 } 11470 11471 if (UDir) 11472 ProcessDeclAttributeList(S, UDir, AttrList); 11473 11474 return UDir; 11475 } 11476 11477 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11478 // If the scope has an associated entity and the using directive is at 11479 // namespace or translation unit scope, add the UsingDirectiveDecl into 11480 // its lookup structure so qualified name lookup can find it. 11481 DeclContext *Ctx = S->getEntity(); 11482 if (Ctx && !Ctx->isFunctionOrMethod()) 11483 Ctx->addDecl(UDir); 11484 else 11485 // Otherwise, it is at block scope. The using-directives will affect lookup 11486 // only to the end of the scope. 11487 S->PushUsingDirective(UDir); 11488 } 11489 11490 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11491 SourceLocation UsingLoc, 11492 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11493 UnqualifiedId &Name, 11494 SourceLocation EllipsisLoc, 11495 const ParsedAttributesView &AttrList) { 11496 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11497 11498 if (SS.isEmpty()) { 11499 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11500 return nullptr; 11501 } 11502 11503 switch (Name.getKind()) { 11504 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11505 case UnqualifiedIdKind::IK_Identifier: 11506 case UnqualifiedIdKind::IK_OperatorFunctionId: 11507 case UnqualifiedIdKind::IK_LiteralOperatorId: 11508 case UnqualifiedIdKind::IK_ConversionFunctionId: 11509 break; 11510 11511 case UnqualifiedIdKind::IK_ConstructorName: 11512 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11513 // C++11 inheriting constructors. 11514 Diag(Name.getBeginLoc(), 11515 getLangOpts().CPlusPlus11 11516 ? diag::warn_cxx98_compat_using_decl_constructor 11517 : diag::err_using_decl_constructor) 11518 << SS.getRange(); 11519 11520 if (getLangOpts().CPlusPlus11) break; 11521 11522 return nullptr; 11523 11524 case UnqualifiedIdKind::IK_DestructorName: 11525 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11526 return nullptr; 11527 11528 case UnqualifiedIdKind::IK_TemplateId: 11529 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11530 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11531 return nullptr; 11532 11533 case UnqualifiedIdKind::IK_DeductionGuideName: 11534 llvm_unreachable("cannot parse qualified deduction guide name"); 11535 } 11536 11537 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11538 DeclarationName TargetName = TargetNameInfo.getName(); 11539 if (!TargetName) 11540 return nullptr; 11541 11542 // Warn about access declarations. 11543 if (UsingLoc.isInvalid()) { 11544 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11545 ? diag::err_access_decl 11546 : diag::warn_access_decl_deprecated) 11547 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11548 } 11549 11550 if (EllipsisLoc.isInvalid()) { 11551 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11552 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11553 return nullptr; 11554 } else { 11555 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11556 !TargetNameInfo.containsUnexpandedParameterPack()) { 11557 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11558 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11559 EllipsisLoc = SourceLocation(); 11560 } 11561 } 11562 11563 NamedDecl *UD = 11564 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 11565 SS, TargetNameInfo, EllipsisLoc, AttrList, 11566 /*IsInstantiation*/false); 11567 if (UD) 11568 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11569 11570 return UD; 11571 } 11572 11573 /// Determine whether a using declaration considers the given 11574 /// declarations as "equivalent", e.g., if they are redeclarations of 11575 /// the same entity or are both typedefs of the same type. 11576 static bool 11577 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11578 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11579 return true; 11580 11581 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11582 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11583 return Context.hasSameType(TD1->getUnderlyingType(), 11584 TD2->getUnderlyingType()); 11585 11586 return false; 11587 } 11588 11589 11590 /// Determines whether to create a using shadow decl for a particular 11591 /// decl, given the set of decls existing prior to this using lookup. 11592 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 11593 const LookupResult &Previous, 11594 UsingShadowDecl *&PrevShadow) { 11595 // Diagnose finding a decl which is not from a base class of the 11596 // current class. We do this now because there are cases where this 11597 // function will silently decide not to build a shadow decl, which 11598 // will pre-empt further diagnostics. 11599 // 11600 // We don't need to do this in C++11 because we do the check once on 11601 // the qualifier. 11602 // 11603 // FIXME: diagnose the following if we care enough: 11604 // struct A { int foo; }; 11605 // struct B : A { using A::foo; }; 11606 // template <class T> struct C : A {}; 11607 // template <class T> struct D : C<T> { using B::foo; } // <--- 11608 // This is invalid (during instantiation) in C++03 because B::foo 11609 // resolves to the using decl in B, which is not a base class of D<T>. 11610 // We can't diagnose it immediately because C<T> is an unknown 11611 // specialization. The UsingShadowDecl in D<T> then points directly 11612 // to A::foo, which will look well-formed when we instantiate. 11613 // The right solution is to not collapse the shadow-decl chain. 11614 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 11615 DeclContext *OrigDC = Orig->getDeclContext(); 11616 11617 // Handle enums and anonymous structs. 11618 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 11619 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 11620 while (OrigRec->isAnonymousStructOrUnion()) 11621 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 11622 11623 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 11624 if (OrigDC == CurContext) { 11625 Diag(Using->getLocation(), 11626 diag::err_using_decl_nested_name_specifier_is_current_class) 11627 << Using->getQualifierLoc().getSourceRange(); 11628 Diag(Orig->getLocation(), diag::note_using_decl_target); 11629 Using->setInvalidDecl(); 11630 return true; 11631 } 11632 11633 Diag(Using->getQualifierLoc().getBeginLoc(), 11634 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11635 << Using->getQualifier() 11636 << cast<CXXRecordDecl>(CurContext) 11637 << Using->getQualifierLoc().getSourceRange(); 11638 Diag(Orig->getLocation(), diag::note_using_decl_target); 11639 Using->setInvalidDecl(); 11640 return true; 11641 } 11642 } 11643 11644 if (Previous.empty()) return false; 11645 11646 NamedDecl *Target = Orig; 11647 if (isa<UsingShadowDecl>(Target)) 11648 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11649 11650 // If the target happens to be one of the previous declarations, we 11651 // don't have a conflict. 11652 // 11653 // FIXME: but we might be increasing its access, in which case we 11654 // should redeclare it. 11655 NamedDecl *NonTag = nullptr, *Tag = nullptr; 11656 bool FoundEquivalentDecl = false; 11657 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 11658 I != E; ++I) { 11659 NamedDecl *D = (*I)->getUnderlyingDecl(); 11660 // We can have UsingDecls in our Previous results because we use the same 11661 // LookupResult for checking whether the UsingDecl itself is a valid 11662 // redeclaration. 11663 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 11664 continue; 11665 11666 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 11667 // C++ [class.mem]p19: 11668 // If T is the name of a class, then [every named member other than 11669 // a non-static data member] shall have a name different from T 11670 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11671 !isa<IndirectFieldDecl>(Target) && 11672 !isa<UnresolvedUsingValueDecl>(Target) && 11673 DiagnoseClassNameShadow( 11674 CurContext, 11675 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 11676 return true; 11677 } 11678 11679 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11680 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11681 PrevShadow = Shadow; 11682 FoundEquivalentDecl = true; 11683 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11684 // We don't conflict with an existing using shadow decl of an equivalent 11685 // declaration, but we're not a redeclaration of it. 11686 FoundEquivalentDecl = true; 11687 } 11688 11689 if (isVisible(D)) 11690 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11691 } 11692 11693 if (FoundEquivalentDecl) 11694 return false; 11695 11696 if (FunctionDecl *FD = Target->getAsFunction()) { 11697 NamedDecl *OldDecl = nullptr; 11698 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11699 /*IsForUsingDecl*/ true)) { 11700 case Ovl_Overload: 11701 return false; 11702 11703 case Ovl_NonFunction: 11704 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11705 break; 11706 11707 // We found a decl with the exact signature. 11708 case Ovl_Match: 11709 // If we're in a record, we want to hide the target, so we 11710 // return true (without a diagnostic) to tell the caller not to 11711 // build a shadow decl. 11712 if (CurContext->isRecord()) 11713 return true; 11714 11715 // If we're not in a record, this is an error. 11716 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11717 break; 11718 } 11719 11720 Diag(Target->getLocation(), diag::note_using_decl_target); 11721 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 11722 Using->setInvalidDecl(); 11723 return true; 11724 } 11725 11726 // Target is not a function. 11727 11728 if (isa<TagDecl>(Target)) { 11729 // No conflict between a tag and a non-tag. 11730 if (!Tag) return false; 11731 11732 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11733 Diag(Target->getLocation(), diag::note_using_decl_target); 11734 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 11735 Using->setInvalidDecl(); 11736 return true; 11737 } 11738 11739 // No conflict between a tag and a non-tag. 11740 if (!NonTag) return false; 11741 11742 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11743 Diag(Target->getLocation(), diag::note_using_decl_target); 11744 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 11745 Using->setInvalidDecl(); 11746 return true; 11747 } 11748 11749 /// Determine whether a direct base class is a virtual base class. 11750 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 11751 if (!Derived->getNumVBases()) 11752 return false; 11753 for (auto &B : Derived->bases()) 11754 if (B.getType()->getAsCXXRecordDecl() == Base) 11755 return B.isVirtual(); 11756 llvm_unreachable("not a direct base class"); 11757 } 11758 11759 /// Builds a shadow declaration corresponding to a 'using' declaration. 11760 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 11761 UsingDecl *UD, 11762 NamedDecl *Orig, 11763 UsingShadowDecl *PrevDecl) { 11764 // If we resolved to another shadow declaration, just coalesce them. 11765 NamedDecl *Target = Orig; 11766 if (isa<UsingShadowDecl>(Target)) { 11767 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11768 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 11769 } 11770 11771 NamedDecl *NonTemplateTarget = Target; 11772 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 11773 NonTemplateTarget = TargetTD->getTemplatedDecl(); 11774 11775 UsingShadowDecl *Shadow; 11776 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 11777 bool IsVirtualBase = 11778 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 11779 UD->getQualifier()->getAsRecordDecl()); 11780 Shadow = ConstructorUsingShadowDecl::Create( 11781 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 11782 } else { 11783 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 11784 Target); 11785 } 11786 UD->addShadowDecl(Shadow); 11787 11788 Shadow->setAccess(UD->getAccess()); 11789 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 11790 Shadow->setInvalidDecl(); 11791 11792 Shadow->setPreviousDecl(PrevDecl); 11793 11794 if (S) 11795 PushOnScopeChains(Shadow, S); 11796 else 11797 CurContext->addDecl(Shadow); 11798 11799 11800 return Shadow; 11801 } 11802 11803 /// Hides a using shadow declaration. This is required by the current 11804 /// using-decl implementation when a resolvable using declaration in a 11805 /// class is followed by a declaration which would hide or override 11806 /// one or more of the using decl's targets; for example: 11807 /// 11808 /// struct Base { void foo(int); }; 11809 /// struct Derived : Base { 11810 /// using Base::foo; 11811 /// void foo(int); 11812 /// }; 11813 /// 11814 /// The governing language is C++03 [namespace.udecl]p12: 11815 /// 11816 /// When a using-declaration brings names from a base class into a 11817 /// derived class scope, member functions in the derived class 11818 /// override and/or hide member functions with the same name and 11819 /// parameter types in a base class (rather than conflicting). 11820 /// 11821 /// There are two ways to implement this: 11822 /// (1) optimistically create shadow decls when they're not hidden 11823 /// by existing declarations, or 11824 /// (2) don't create any shadow decls (or at least don't make them 11825 /// visible) until we've fully parsed/instantiated the class. 11826 /// The problem with (1) is that we might have to retroactively remove 11827 /// a shadow decl, which requires several O(n) operations because the 11828 /// decl structures are (very reasonably) not designed for removal. 11829 /// (2) avoids this but is very fiddly and phase-dependent. 11830 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 11831 if (Shadow->getDeclName().getNameKind() == 11832 DeclarationName::CXXConversionFunctionName) 11833 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 11834 11835 // Remove it from the DeclContext... 11836 Shadow->getDeclContext()->removeDecl(Shadow); 11837 11838 // ...and the scope, if applicable... 11839 if (S) { 11840 S->RemoveDecl(Shadow); 11841 IdResolver.RemoveDecl(Shadow); 11842 } 11843 11844 // ...and the using decl. 11845 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 11846 11847 // TODO: complain somehow if Shadow was used. It shouldn't 11848 // be possible for this to happen, because...? 11849 } 11850 11851 /// Find the base specifier for a base class with the given type. 11852 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 11853 QualType DesiredBase, 11854 bool &AnyDependentBases) { 11855 // Check whether the named type is a direct base class. 11856 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 11857 .getUnqualifiedType(); 11858 for (auto &Base : Derived->bases()) { 11859 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 11860 if (CanonicalDesiredBase == BaseType) 11861 return &Base; 11862 if (BaseType->isDependentType()) 11863 AnyDependentBases = true; 11864 } 11865 return nullptr; 11866 } 11867 11868 namespace { 11869 class UsingValidatorCCC final : public CorrectionCandidateCallback { 11870 public: 11871 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 11872 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 11873 : HasTypenameKeyword(HasTypenameKeyword), 11874 IsInstantiation(IsInstantiation), OldNNS(NNS), 11875 RequireMemberOf(RequireMemberOf) {} 11876 11877 bool ValidateCandidate(const TypoCorrection &Candidate) override { 11878 NamedDecl *ND = Candidate.getCorrectionDecl(); 11879 11880 // Keywords are not valid here. 11881 if (!ND || isa<NamespaceDecl>(ND)) 11882 return false; 11883 11884 // Completely unqualified names are invalid for a 'using' declaration. 11885 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 11886 return false; 11887 11888 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 11889 // reject. 11890 11891 if (RequireMemberOf) { 11892 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11893 if (FoundRecord && FoundRecord->isInjectedClassName()) { 11894 // No-one ever wants a using-declaration to name an injected-class-name 11895 // of a base class, unless they're declaring an inheriting constructor. 11896 ASTContext &Ctx = ND->getASTContext(); 11897 if (!Ctx.getLangOpts().CPlusPlus11) 11898 return false; 11899 QualType FoundType = Ctx.getRecordType(FoundRecord); 11900 11901 // Check that the injected-class-name is named as a member of its own 11902 // type; we don't want to suggest 'using Derived::Base;', since that 11903 // means something else. 11904 NestedNameSpecifier *Specifier = 11905 Candidate.WillReplaceSpecifier() 11906 ? Candidate.getCorrectionSpecifier() 11907 : OldNNS; 11908 if (!Specifier->getAsType() || 11909 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 11910 return false; 11911 11912 // Check that this inheriting constructor declaration actually names a 11913 // direct base class of the current class. 11914 bool AnyDependentBases = false; 11915 if (!findDirectBaseWithType(RequireMemberOf, 11916 Ctx.getRecordType(FoundRecord), 11917 AnyDependentBases) && 11918 !AnyDependentBases) 11919 return false; 11920 } else { 11921 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 11922 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 11923 return false; 11924 11925 // FIXME: Check that the base class member is accessible? 11926 } 11927 } else { 11928 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11929 if (FoundRecord && FoundRecord->isInjectedClassName()) 11930 return false; 11931 } 11932 11933 if (isa<TypeDecl>(ND)) 11934 return HasTypenameKeyword || !IsInstantiation; 11935 11936 return !HasTypenameKeyword; 11937 } 11938 11939 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11940 return std::make_unique<UsingValidatorCCC>(*this); 11941 } 11942 11943 private: 11944 bool HasTypenameKeyword; 11945 bool IsInstantiation; 11946 NestedNameSpecifier *OldNNS; 11947 CXXRecordDecl *RequireMemberOf; 11948 }; 11949 } // end anonymous namespace 11950 11951 /// Builds a using declaration. 11952 /// 11953 /// \param IsInstantiation - Whether this call arises from an 11954 /// instantiation of an unresolved using declaration. We treat 11955 /// the lookup differently for these declarations. 11956 NamedDecl *Sema::BuildUsingDeclaration( 11957 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 11958 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 11959 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 11960 const ParsedAttributesView &AttrList, bool IsInstantiation) { 11961 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11962 SourceLocation IdentLoc = NameInfo.getLoc(); 11963 assert(IdentLoc.isValid() && "Invalid TargetName location."); 11964 11965 // FIXME: We ignore attributes for now. 11966 11967 // For an inheriting constructor declaration, the name of the using 11968 // declaration is the name of a constructor in this class, not in the 11969 // base class. 11970 DeclarationNameInfo UsingName = NameInfo; 11971 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 11972 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 11973 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 11974 Context.getCanonicalType(Context.getRecordType(RD)))); 11975 11976 // Do the redeclaration lookup in the current scope. 11977 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 11978 ForVisibleRedeclaration); 11979 Previous.setHideTags(false); 11980 if (S) { 11981 LookupName(Previous, S); 11982 11983 // It is really dumb that we have to do this. 11984 LookupResult::Filter F = Previous.makeFilter(); 11985 while (F.hasNext()) { 11986 NamedDecl *D = F.next(); 11987 if (!isDeclInScope(D, CurContext, S)) 11988 F.erase(); 11989 // If we found a local extern declaration that's not ordinarily visible, 11990 // and this declaration is being added to a non-block scope, ignore it. 11991 // We're only checking for scope conflicts here, not also for violations 11992 // of the linkage rules. 11993 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 11994 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 11995 F.erase(); 11996 } 11997 F.done(); 11998 } else { 11999 assert(IsInstantiation && "no scope in non-instantiation"); 12000 if (CurContext->isRecord()) 12001 LookupQualifiedName(Previous, CurContext); 12002 else { 12003 // No redeclaration check is needed here; in non-member contexts we 12004 // diagnosed all possible conflicts with other using-declarations when 12005 // building the template: 12006 // 12007 // For a dependent non-type using declaration, the only valid case is 12008 // if we instantiate to a single enumerator. We check for conflicts 12009 // between shadow declarations we introduce, and we check in the template 12010 // definition for conflicts between a non-type using declaration and any 12011 // other declaration, which together covers all cases. 12012 // 12013 // A dependent typename using declaration will never successfully 12014 // instantiate, since it will always name a class member, so we reject 12015 // that in the template definition. 12016 } 12017 } 12018 12019 // Check for invalid redeclarations. 12020 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 12021 SS, IdentLoc, Previous)) 12022 return nullptr; 12023 12024 // Check for bad qualifiers. 12025 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 12026 IdentLoc)) 12027 return nullptr; 12028 12029 DeclContext *LookupContext = computeDeclContext(SS); 12030 NamedDecl *D; 12031 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12032 if (!LookupContext || EllipsisLoc.isValid()) { 12033 if (HasTypenameKeyword) { 12034 // FIXME: not all declaration name kinds are legal here 12035 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 12036 UsingLoc, TypenameLoc, 12037 QualifierLoc, 12038 IdentLoc, NameInfo.getName(), 12039 EllipsisLoc); 12040 } else { 12041 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 12042 QualifierLoc, NameInfo, EllipsisLoc); 12043 } 12044 D->setAccess(AS); 12045 CurContext->addDecl(D); 12046 return D; 12047 } 12048 12049 auto Build = [&](bool Invalid) { 12050 UsingDecl *UD = 12051 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 12052 UsingName, HasTypenameKeyword); 12053 UD->setAccess(AS); 12054 CurContext->addDecl(UD); 12055 UD->setInvalidDecl(Invalid); 12056 return UD; 12057 }; 12058 auto BuildInvalid = [&]{ return Build(true); }; 12059 auto BuildValid = [&]{ return Build(false); }; 12060 12061 if (RequireCompleteDeclContext(SS, LookupContext)) 12062 return BuildInvalid(); 12063 12064 // Look up the target name. 12065 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12066 12067 // Unlike most lookups, we don't always want to hide tag 12068 // declarations: tag names are visible through the using declaration 12069 // even if hidden by ordinary names, *except* in a dependent context 12070 // where it's important for the sanity of two-phase lookup. 12071 if (!IsInstantiation) 12072 R.setHideTags(false); 12073 12074 // For the purposes of this lookup, we have a base object type 12075 // equal to that of the current context. 12076 if (CurContext->isRecord()) { 12077 R.setBaseObjectType( 12078 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 12079 } 12080 12081 LookupQualifiedName(R, LookupContext); 12082 12083 // Try to correct typos if possible. If constructor name lookup finds no 12084 // results, that means the named class has no explicit constructors, and we 12085 // suppressed declaring implicit ones (probably because it's dependent or 12086 // invalid). 12087 if (R.empty() && 12088 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 12089 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 12090 // it will believe that glibc provides a ::gets in cases where it does not, 12091 // and will try to pull it into namespace std with a using-declaration. 12092 // Just ignore the using-declaration in that case. 12093 auto *II = NameInfo.getName().getAsIdentifierInfo(); 12094 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 12095 CurContext->isStdNamespace() && 12096 isa<TranslationUnitDecl>(LookupContext) && 12097 getSourceManager().isInSystemHeader(UsingLoc)) 12098 return nullptr; 12099 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 12100 dyn_cast<CXXRecordDecl>(CurContext)); 12101 if (TypoCorrection Corrected = 12102 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 12103 CTK_ErrorRecovery)) { 12104 // We reject candidates where DroppedSpecifier == true, hence the 12105 // literal '0' below. 12106 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 12107 << NameInfo.getName() << LookupContext << 0 12108 << SS.getRange()); 12109 12110 // If we picked a correction with no attached Decl we can't do anything 12111 // useful with it, bail out. 12112 NamedDecl *ND = Corrected.getCorrectionDecl(); 12113 if (!ND) 12114 return BuildInvalid(); 12115 12116 // If we corrected to an inheriting constructor, handle it as one. 12117 auto *RD = dyn_cast<CXXRecordDecl>(ND); 12118 if (RD && RD->isInjectedClassName()) { 12119 // The parent of the injected class name is the class itself. 12120 RD = cast<CXXRecordDecl>(RD->getParent()); 12121 12122 // Fix up the information we'll use to build the using declaration. 12123 if (Corrected.WillReplaceSpecifier()) { 12124 NestedNameSpecifierLocBuilder Builder; 12125 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 12126 QualifierLoc.getSourceRange()); 12127 QualifierLoc = Builder.getWithLocInContext(Context); 12128 } 12129 12130 // In this case, the name we introduce is the name of a derived class 12131 // constructor. 12132 auto *CurClass = cast<CXXRecordDecl>(CurContext); 12133 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12134 Context.getCanonicalType(Context.getRecordType(CurClass)))); 12135 UsingName.setNamedTypeInfo(nullptr); 12136 for (auto *Ctor : LookupConstructors(RD)) 12137 R.addDecl(Ctor); 12138 R.resolveKind(); 12139 } else { 12140 // FIXME: Pick up all the declarations if we found an overloaded 12141 // function. 12142 UsingName.setName(ND->getDeclName()); 12143 R.addDecl(ND); 12144 } 12145 } else { 12146 Diag(IdentLoc, diag::err_no_member) 12147 << NameInfo.getName() << LookupContext << SS.getRange(); 12148 return BuildInvalid(); 12149 } 12150 } 12151 12152 if (R.isAmbiguous()) 12153 return BuildInvalid(); 12154 12155 if (HasTypenameKeyword) { 12156 // If we asked for a typename and got a non-type decl, error out. 12157 if (!R.getAsSingle<TypeDecl>()) { 12158 Diag(IdentLoc, diag::err_using_typename_non_type); 12159 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12160 Diag((*I)->getUnderlyingDecl()->getLocation(), 12161 diag::note_using_decl_target); 12162 return BuildInvalid(); 12163 } 12164 } else { 12165 // If we asked for a non-typename and we got a type, error out, 12166 // but only if this is an instantiation of an unresolved using 12167 // decl. Otherwise just silently find the type name. 12168 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 12169 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 12170 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 12171 return BuildInvalid(); 12172 } 12173 } 12174 12175 // C++14 [namespace.udecl]p6: 12176 // A using-declaration shall not name a namespace. 12177 if (R.getAsSingle<NamespaceDecl>()) { 12178 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 12179 << SS.getRange(); 12180 return BuildInvalid(); 12181 } 12182 12183 // C++14 [namespace.udecl]p7: 12184 // A using-declaration shall not name a scoped enumerator. 12185 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 12186 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 12187 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 12188 << SS.getRange(); 12189 return BuildInvalid(); 12190 } 12191 } 12192 12193 UsingDecl *UD = BuildValid(); 12194 12195 // Some additional rules apply to inheriting constructors. 12196 if (UsingName.getName().getNameKind() == 12197 DeclarationName::CXXConstructorName) { 12198 // Suppress access diagnostics; the access check is instead performed at the 12199 // point of use for an inheriting constructor. 12200 R.suppressDiagnostics(); 12201 if (CheckInheritingConstructorUsingDecl(UD)) 12202 return UD; 12203 } 12204 12205 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 12206 UsingShadowDecl *PrevDecl = nullptr; 12207 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 12208 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 12209 } 12210 12211 return UD; 12212 } 12213 12214 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 12215 ArrayRef<NamedDecl *> Expansions) { 12216 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 12217 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 12218 isa<UsingPackDecl>(InstantiatedFrom)); 12219 12220 auto *UPD = 12221 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 12222 UPD->setAccess(InstantiatedFrom->getAccess()); 12223 CurContext->addDecl(UPD); 12224 return UPD; 12225 } 12226 12227 /// Additional checks for a using declaration referring to a constructor name. 12228 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 12229 assert(!UD->hasTypename() && "expecting a constructor name"); 12230 12231 const Type *SourceType = UD->getQualifier()->getAsType(); 12232 assert(SourceType && 12233 "Using decl naming constructor doesn't have type in scope spec."); 12234 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 12235 12236 // Check whether the named type is a direct base class. 12237 bool AnyDependentBases = false; 12238 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 12239 AnyDependentBases); 12240 if (!Base && !AnyDependentBases) { 12241 Diag(UD->getUsingLoc(), 12242 diag::err_using_decl_constructor_not_in_direct_base) 12243 << UD->getNameInfo().getSourceRange() 12244 << QualType(SourceType, 0) << TargetClass; 12245 UD->setInvalidDecl(); 12246 return true; 12247 } 12248 12249 if (Base) 12250 Base->setInheritConstructors(); 12251 12252 return false; 12253 } 12254 12255 /// Checks that the given using declaration is not an invalid 12256 /// redeclaration. Note that this is checking only for the using decl 12257 /// itself, not for any ill-formedness among the UsingShadowDecls. 12258 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 12259 bool HasTypenameKeyword, 12260 const CXXScopeSpec &SS, 12261 SourceLocation NameLoc, 12262 const LookupResult &Prev) { 12263 NestedNameSpecifier *Qual = SS.getScopeRep(); 12264 12265 // C++03 [namespace.udecl]p8: 12266 // C++0x [namespace.udecl]p10: 12267 // A using-declaration is a declaration and can therefore be used 12268 // repeatedly where (and only where) multiple declarations are 12269 // allowed. 12270 // 12271 // That's in non-member contexts. 12272 if (!CurContext->getRedeclContext()->isRecord()) { 12273 // A dependent qualifier outside a class can only ever resolve to an 12274 // enumeration type. Therefore it conflicts with any other non-type 12275 // declaration in the same scope. 12276 // FIXME: How should we check for dependent type-type conflicts at block 12277 // scope? 12278 if (Qual->isDependent() && !HasTypenameKeyword) { 12279 for (auto *D : Prev) { 12280 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 12281 bool OldCouldBeEnumerator = 12282 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 12283 Diag(NameLoc, 12284 OldCouldBeEnumerator ? diag::err_redefinition 12285 : diag::err_redefinition_different_kind) 12286 << Prev.getLookupName(); 12287 Diag(D->getLocation(), diag::note_previous_definition); 12288 return true; 12289 } 12290 } 12291 } 12292 return false; 12293 } 12294 12295 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 12296 NamedDecl *D = *I; 12297 12298 bool DTypename; 12299 NestedNameSpecifier *DQual; 12300 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 12301 DTypename = UD->hasTypename(); 12302 DQual = UD->getQualifier(); 12303 } else if (UnresolvedUsingValueDecl *UD 12304 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 12305 DTypename = false; 12306 DQual = UD->getQualifier(); 12307 } else if (UnresolvedUsingTypenameDecl *UD 12308 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 12309 DTypename = true; 12310 DQual = UD->getQualifier(); 12311 } else continue; 12312 12313 // using decls differ if one says 'typename' and the other doesn't. 12314 // FIXME: non-dependent using decls? 12315 if (HasTypenameKeyword != DTypename) continue; 12316 12317 // using decls differ if they name different scopes (but note that 12318 // template instantiation can cause this check to trigger when it 12319 // didn't before instantiation). 12320 if (Context.getCanonicalNestedNameSpecifier(Qual) != 12321 Context.getCanonicalNestedNameSpecifier(DQual)) 12322 continue; 12323 12324 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 12325 Diag(D->getLocation(), diag::note_using_decl) << 1; 12326 return true; 12327 } 12328 12329 return false; 12330 } 12331 12332 12333 /// Checks that the given nested-name qualifier used in a using decl 12334 /// in the current context is appropriately related to the current 12335 /// scope. If an error is found, diagnoses it and returns true. 12336 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 12337 bool HasTypename, 12338 const CXXScopeSpec &SS, 12339 const DeclarationNameInfo &NameInfo, 12340 SourceLocation NameLoc) { 12341 DeclContext *NamedContext = computeDeclContext(SS); 12342 12343 if (!CurContext->isRecord()) { 12344 // C++03 [namespace.udecl]p3: 12345 // C++0x [namespace.udecl]p8: 12346 // A using-declaration for a class member shall be a member-declaration. 12347 12348 // If we weren't able to compute a valid scope, it might validly be a 12349 // dependent class scope or a dependent enumeration unscoped scope. If 12350 // we have a 'typename' keyword, the scope must resolve to a class type. 12351 if ((HasTypename && !NamedContext) || 12352 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 12353 auto *RD = NamedContext 12354 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 12355 : nullptr; 12356 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 12357 RD = nullptr; 12358 12359 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 12360 << SS.getRange(); 12361 12362 // If we have a complete, non-dependent source type, try to suggest a 12363 // way to get the same effect. 12364 if (!RD) 12365 return true; 12366 12367 // Find what this using-declaration was referring to. 12368 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12369 R.setHideTags(false); 12370 R.suppressDiagnostics(); 12371 LookupQualifiedName(R, RD); 12372 12373 if (R.getAsSingle<TypeDecl>()) { 12374 if (getLangOpts().CPlusPlus11) { 12375 // Convert 'using X::Y;' to 'using Y = X::Y;'. 12376 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 12377 << 0 // alias declaration 12378 << FixItHint::CreateInsertion(SS.getBeginLoc(), 12379 NameInfo.getName().getAsString() + 12380 " = "); 12381 } else { 12382 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 12383 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 12384 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 12385 << 1 // typedef declaration 12386 << FixItHint::CreateReplacement(UsingLoc, "typedef") 12387 << FixItHint::CreateInsertion( 12388 InsertLoc, " " + NameInfo.getName().getAsString()); 12389 } 12390 } else if (R.getAsSingle<VarDecl>()) { 12391 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12392 // repeating the type of the static data member here. 12393 FixItHint FixIt; 12394 if (getLangOpts().CPlusPlus11) { 12395 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12396 FixIt = FixItHint::CreateReplacement( 12397 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 12398 } 12399 12400 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12401 << 2 // reference declaration 12402 << FixIt; 12403 } else if (R.getAsSingle<EnumConstantDecl>()) { 12404 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12405 // repeating the type of the enumeration here, and we can't do so if 12406 // the type is anonymous. 12407 FixItHint FixIt; 12408 if (getLangOpts().CPlusPlus11) { 12409 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12410 FixIt = FixItHint::CreateReplacement( 12411 UsingLoc, 12412 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 12413 } 12414 12415 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12416 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 12417 << FixIt; 12418 } 12419 return true; 12420 } 12421 12422 // Otherwise, this might be valid. 12423 return false; 12424 } 12425 12426 // The current scope is a record. 12427 12428 // If the named context is dependent, we can't decide much. 12429 if (!NamedContext) { 12430 // FIXME: in C++0x, we can diagnose if we can prove that the 12431 // nested-name-specifier does not refer to a base class, which is 12432 // still possible in some cases. 12433 12434 // Otherwise we have to conservatively report that things might be 12435 // okay. 12436 return false; 12437 } 12438 12439 if (!NamedContext->isRecord()) { 12440 // Ideally this would point at the last name in the specifier, 12441 // but we don't have that level of source info. 12442 Diag(SS.getRange().getBegin(), 12443 diag::err_using_decl_nested_name_specifier_is_not_class) 12444 << SS.getScopeRep() << SS.getRange(); 12445 return true; 12446 } 12447 12448 if (!NamedContext->isDependentContext() && 12449 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 12450 return true; 12451 12452 if (getLangOpts().CPlusPlus11) { 12453 // C++11 [namespace.udecl]p3: 12454 // In a using-declaration used as a member-declaration, the 12455 // nested-name-specifier shall name a base class of the class 12456 // being defined. 12457 12458 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 12459 cast<CXXRecordDecl>(NamedContext))) { 12460 if (CurContext == NamedContext) { 12461 Diag(NameLoc, 12462 diag::err_using_decl_nested_name_specifier_is_current_class) 12463 << SS.getRange(); 12464 return true; 12465 } 12466 12467 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 12468 Diag(SS.getRange().getBegin(), 12469 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12470 << SS.getScopeRep() 12471 << cast<CXXRecordDecl>(CurContext) 12472 << SS.getRange(); 12473 } 12474 return true; 12475 } 12476 12477 return false; 12478 } 12479 12480 // C++03 [namespace.udecl]p4: 12481 // A using-declaration used as a member-declaration shall refer 12482 // to a member of a base class of the class being defined [etc.]. 12483 12484 // Salient point: SS doesn't have to name a base class as long as 12485 // lookup only finds members from base classes. Therefore we can 12486 // diagnose here only if we can prove that that can't happen, 12487 // i.e. if the class hierarchies provably don't intersect. 12488 12489 // TODO: it would be nice if "definitely valid" results were cached 12490 // in the UsingDecl and UsingShadowDecl so that these checks didn't 12491 // need to be repeated. 12492 12493 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 12494 auto Collect = [&Bases](const CXXRecordDecl *Base) { 12495 Bases.insert(Base); 12496 return true; 12497 }; 12498 12499 // Collect all bases. Return false if we find a dependent base. 12500 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 12501 return false; 12502 12503 // Returns true if the base is dependent or is one of the accumulated base 12504 // classes. 12505 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 12506 return !Bases.count(Base); 12507 }; 12508 12509 // Return false if the class has a dependent base or if it or one 12510 // of its bases is present in the base set of the current context. 12511 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 12512 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 12513 return false; 12514 12515 Diag(SS.getRange().getBegin(), 12516 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12517 << SS.getScopeRep() 12518 << cast<CXXRecordDecl>(CurContext) 12519 << SS.getRange(); 12520 12521 return true; 12522 } 12523 12524 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 12525 MultiTemplateParamsArg TemplateParamLists, 12526 SourceLocation UsingLoc, UnqualifiedId &Name, 12527 const ParsedAttributesView &AttrList, 12528 TypeResult Type, Decl *DeclFromDeclSpec) { 12529 // Skip up to the relevant declaration scope. 12530 while (S->isTemplateParamScope()) 12531 S = S->getParent(); 12532 assert((S->getFlags() & Scope::DeclScope) && 12533 "got alias-declaration outside of declaration scope"); 12534 12535 if (Type.isInvalid()) 12536 return nullptr; 12537 12538 bool Invalid = false; 12539 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 12540 TypeSourceInfo *TInfo = nullptr; 12541 GetTypeFromParser(Type.get(), &TInfo); 12542 12543 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 12544 return nullptr; 12545 12546 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 12547 UPPC_DeclarationType)) { 12548 Invalid = true; 12549 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12550 TInfo->getTypeLoc().getBeginLoc()); 12551 } 12552 12553 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12554 TemplateParamLists.size() 12555 ? forRedeclarationInCurContext() 12556 : ForVisibleRedeclaration); 12557 LookupName(Previous, S); 12558 12559 // Warn about shadowing the name of a template parameter. 12560 if (Previous.isSingleResult() && 12561 Previous.getFoundDecl()->isTemplateParameter()) { 12562 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 12563 Previous.clear(); 12564 } 12565 12566 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 12567 "name in alias declaration must be an identifier"); 12568 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 12569 Name.StartLocation, 12570 Name.Identifier, TInfo); 12571 12572 NewTD->setAccess(AS); 12573 12574 if (Invalid) 12575 NewTD->setInvalidDecl(); 12576 12577 ProcessDeclAttributeList(S, NewTD, AttrList); 12578 AddPragmaAttributes(S, NewTD); 12579 12580 CheckTypedefForVariablyModifiedType(S, NewTD); 12581 Invalid |= NewTD->isInvalidDecl(); 12582 12583 bool Redeclaration = false; 12584 12585 NamedDecl *NewND; 12586 if (TemplateParamLists.size()) { 12587 TypeAliasTemplateDecl *OldDecl = nullptr; 12588 TemplateParameterList *OldTemplateParams = nullptr; 12589 12590 if (TemplateParamLists.size() != 1) { 12591 Diag(UsingLoc, diag::err_alias_template_extra_headers) 12592 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 12593 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 12594 } 12595 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 12596 12597 // Check that we can declare a template here. 12598 if (CheckTemplateDeclScope(S, TemplateParams)) 12599 return nullptr; 12600 12601 // Only consider previous declarations in the same scope. 12602 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 12603 /*ExplicitInstantiationOrSpecialization*/false); 12604 if (!Previous.empty()) { 12605 Redeclaration = true; 12606 12607 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 12608 if (!OldDecl && !Invalid) { 12609 Diag(UsingLoc, diag::err_redefinition_different_kind) 12610 << Name.Identifier; 12611 12612 NamedDecl *OldD = Previous.getRepresentativeDecl(); 12613 if (OldD->getLocation().isValid()) 12614 Diag(OldD->getLocation(), diag::note_previous_definition); 12615 12616 Invalid = true; 12617 } 12618 12619 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 12620 if (TemplateParameterListsAreEqual(TemplateParams, 12621 OldDecl->getTemplateParameters(), 12622 /*Complain=*/true, 12623 TPL_TemplateMatch)) 12624 OldTemplateParams = 12625 OldDecl->getMostRecentDecl()->getTemplateParameters(); 12626 else 12627 Invalid = true; 12628 12629 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 12630 if (!Invalid && 12631 !Context.hasSameType(OldTD->getUnderlyingType(), 12632 NewTD->getUnderlyingType())) { 12633 // FIXME: The C++0x standard does not clearly say this is ill-formed, 12634 // but we can't reasonably accept it. 12635 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 12636 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 12637 if (OldTD->getLocation().isValid()) 12638 Diag(OldTD->getLocation(), diag::note_previous_definition); 12639 Invalid = true; 12640 } 12641 } 12642 } 12643 12644 // Merge any previous default template arguments into our parameters, 12645 // and check the parameter list. 12646 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 12647 TPC_TypeAliasTemplate)) 12648 return nullptr; 12649 12650 TypeAliasTemplateDecl *NewDecl = 12651 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 12652 Name.Identifier, TemplateParams, 12653 NewTD); 12654 NewTD->setDescribedAliasTemplate(NewDecl); 12655 12656 NewDecl->setAccess(AS); 12657 12658 if (Invalid) 12659 NewDecl->setInvalidDecl(); 12660 else if (OldDecl) { 12661 NewDecl->setPreviousDecl(OldDecl); 12662 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 12663 } 12664 12665 NewND = NewDecl; 12666 } else { 12667 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 12668 setTagNameForLinkagePurposes(TD, NewTD); 12669 handleTagNumbering(TD, S); 12670 } 12671 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 12672 NewND = NewTD; 12673 } 12674 12675 PushOnScopeChains(NewND, S); 12676 ActOnDocumentableDecl(NewND); 12677 return NewND; 12678 } 12679 12680 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 12681 SourceLocation AliasLoc, 12682 IdentifierInfo *Alias, CXXScopeSpec &SS, 12683 SourceLocation IdentLoc, 12684 IdentifierInfo *Ident) { 12685 12686 // Lookup the namespace name. 12687 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 12688 LookupParsedName(R, S, &SS); 12689 12690 if (R.isAmbiguous()) 12691 return nullptr; 12692 12693 if (R.empty()) { 12694 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 12695 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 12696 return nullptr; 12697 } 12698 } 12699 assert(!R.isAmbiguous() && !R.empty()); 12700 NamedDecl *ND = R.getRepresentativeDecl(); 12701 12702 // Check if we have a previous declaration with the same name. 12703 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 12704 ForVisibleRedeclaration); 12705 LookupName(PrevR, S); 12706 12707 // Check we're not shadowing a template parameter. 12708 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 12709 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 12710 PrevR.clear(); 12711 } 12712 12713 // Filter out any other lookup result from an enclosing scope. 12714 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 12715 /*AllowInlineNamespace*/false); 12716 12717 // Find the previous declaration and check that we can redeclare it. 12718 NamespaceAliasDecl *Prev = nullptr; 12719 if (PrevR.isSingleResult()) { 12720 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 12721 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 12722 // We already have an alias with the same name that points to the same 12723 // namespace; check that it matches. 12724 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 12725 Prev = AD; 12726 } else if (isVisible(PrevDecl)) { 12727 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 12728 << Alias; 12729 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 12730 << AD->getNamespace(); 12731 return nullptr; 12732 } 12733 } else if (isVisible(PrevDecl)) { 12734 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 12735 ? diag::err_redefinition 12736 : diag::err_redefinition_different_kind; 12737 Diag(AliasLoc, DiagID) << Alias; 12738 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12739 return nullptr; 12740 } 12741 } 12742 12743 // The use of a nested name specifier may trigger deprecation warnings. 12744 DiagnoseUseOfDecl(ND, IdentLoc); 12745 12746 NamespaceAliasDecl *AliasDecl = 12747 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 12748 Alias, SS.getWithLocInContext(Context), 12749 IdentLoc, ND); 12750 if (Prev) 12751 AliasDecl->setPreviousDecl(Prev); 12752 12753 PushOnScopeChains(AliasDecl, S); 12754 return AliasDecl; 12755 } 12756 12757 namespace { 12758 struct SpecialMemberExceptionSpecInfo 12759 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 12760 SourceLocation Loc; 12761 Sema::ImplicitExceptionSpecification ExceptSpec; 12762 12763 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 12764 Sema::CXXSpecialMember CSM, 12765 Sema::InheritedConstructorInfo *ICI, 12766 SourceLocation Loc) 12767 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 12768 12769 bool visitBase(CXXBaseSpecifier *Base); 12770 bool visitField(FieldDecl *FD); 12771 12772 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 12773 unsigned Quals); 12774 12775 void visitSubobjectCall(Subobject Subobj, 12776 Sema::SpecialMemberOverloadResult SMOR); 12777 }; 12778 } 12779 12780 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 12781 auto *RT = Base->getType()->getAs<RecordType>(); 12782 if (!RT) 12783 return false; 12784 12785 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 12786 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 12787 if (auto *BaseCtor = SMOR.getMethod()) { 12788 visitSubobjectCall(Base, BaseCtor); 12789 return false; 12790 } 12791 12792 visitClassSubobject(BaseClass, Base, 0); 12793 return false; 12794 } 12795 12796 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 12797 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 12798 Expr *E = FD->getInClassInitializer(); 12799 if (!E) 12800 // FIXME: It's a little wasteful to build and throw away a 12801 // CXXDefaultInitExpr here. 12802 // FIXME: We should have a single context note pointing at Loc, and 12803 // this location should be MD->getLocation() instead, since that's 12804 // the location where we actually use the default init expression. 12805 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 12806 if (E) 12807 ExceptSpec.CalledExpr(E); 12808 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 12809 ->getAs<RecordType>()) { 12810 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 12811 FD->getType().getCVRQualifiers()); 12812 } 12813 return false; 12814 } 12815 12816 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 12817 Subobject Subobj, 12818 unsigned Quals) { 12819 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 12820 bool IsMutable = Field && Field->isMutable(); 12821 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 12822 } 12823 12824 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 12825 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 12826 // Note, if lookup fails, it doesn't matter what exception specification we 12827 // choose because the special member will be deleted. 12828 if (CXXMethodDecl *MD = SMOR.getMethod()) 12829 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 12830 } 12831 12832 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 12833 llvm::APSInt Result; 12834 ExprResult Converted = CheckConvertedConstantExpression( 12835 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 12836 ExplicitSpec.setExpr(Converted.get()); 12837 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 12838 ExplicitSpec.setKind(Result.getBoolValue() 12839 ? ExplicitSpecKind::ResolvedTrue 12840 : ExplicitSpecKind::ResolvedFalse); 12841 return true; 12842 } 12843 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 12844 return false; 12845 } 12846 12847 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 12848 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 12849 if (!ExplicitExpr->isTypeDependent()) 12850 tryResolveExplicitSpecifier(ES); 12851 return ES; 12852 } 12853 12854 static Sema::ImplicitExceptionSpecification 12855 ComputeDefaultedSpecialMemberExceptionSpec( 12856 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 12857 Sema::InheritedConstructorInfo *ICI) { 12858 ComputingExceptionSpec CES(S, MD, Loc); 12859 12860 CXXRecordDecl *ClassDecl = MD->getParent(); 12861 12862 // C++ [except.spec]p14: 12863 // An implicitly declared special member function (Clause 12) shall have an 12864 // exception-specification. [...] 12865 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 12866 if (ClassDecl->isInvalidDecl()) 12867 return Info.ExceptSpec; 12868 12869 // FIXME: If this diagnostic fires, we're probably missing a check for 12870 // attempting to resolve an exception specification before it's known 12871 // at a higher level. 12872 if (S.RequireCompleteType(MD->getLocation(), 12873 S.Context.getRecordType(ClassDecl), 12874 diag::err_exception_spec_incomplete_type)) 12875 return Info.ExceptSpec; 12876 12877 // C++1z [except.spec]p7: 12878 // [Look for exceptions thrown by] a constructor selected [...] to 12879 // initialize a potentially constructed subobject, 12880 // C++1z [except.spec]p8: 12881 // The exception specification for an implicitly-declared destructor, or a 12882 // destructor without a noexcept-specifier, is potentially-throwing if and 12883 // only if any of the destructors for any of its potentially constructed 12884 // subojects is potentially throwing. 12885 // FIXME: We respect the first rule but ignore the "potentially constructed" 12886 // in the second rule to resolve a core issue (no number yet) that would have 12887 // us reject: 12888 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 12889 // struct B : A {}; 12890 // struct C : B { void f(); }; 12891 // ... due to giving B::~B() a non-throwing exception specification. 12892 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 12893 : Info.VisitAllBases); 12894 12895 return Info.ExceptSpec; 12896 } 12897 12898 namespace { 12899 /// RAII object to register a special member as being currently declared. 12900 struct DeclaringSpecialMember { 12901 Sema &S; 12902 Sema::SpecialMemberDecl D; 12903 Sema::ContextRAII SavedContext; 12904 bool WasAlreadyBeingDeclared; 12905 12906 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 12907 : S(S), D(RD, CSM), SavedContext(S, RD) { 12908 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 12909 if (WasAlreadyBeingDeclared) 12910 // This almost never happens, but if it does, ensure that our cache 12911 // doesn't contain a stale result. 12912 S.SpecialMemberCache.clear(); 12913 else { 12914 // Register a note to be produced if we encounter an error while 12915 // declaring the special member. 12916 Sema::CodeSynthesisContext Ctx; 12917 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 12918 // FIXME: We don't have a location to use here. Using the class's 12919 // location maintains the fiction that we declare all special members 12920 // with the class, but (1) it's not clear that lying about that helps our 12921 // users understand what's going on, and (2) there may be outer contexts 12922 // on the stack (some of which are relevant) and printing them exposes 12923 // our lies. 12924 Ctx.PointOfInstantiation = RD->getLocation(); 12925 Ctx.Entity = RD; 12926 Ctx.SpecialMember = CSM; 12927 S.pushCodeSynthesisContext(Ctx); 12928 } 12929 } 12930 ~DeclaringSpecialMember() { 12931 if (!WasAlreadyBeingDeclared) { 12932 S.SpecialMembersBeingDeclared.erase(D); 12933 S.popCodeSynthesisContext(); 12934 } 12935 } 12936 12937 /// Are we already trying to declare this special member? 12938 bool isAlreadyBeingDeclared() const { 12939 return WasAlreadyBeingDeclared; 12940 } 12941 }; 12942 } 12943 12944 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 12945 // Look up any existing declarations, but don't trigger declaration of all 12946 // implicit special members with this name. 12947 DeclarationName Name = FD->getDeclName(); 12948 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 12949 ForExternalRedeclaration); 12950 for (auto *D : FD->getParent()->lookup(Name)) 12951 if (auto *Acceptable = R.getAcceptableDecl(D)) 12952 R.addDecl(Acceptable); 12953 R.resolveKind(); 12954 R.suppressDiagnostics(); 12955 12956 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 12957 } 12958 12959 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 12960 QualType ResultTy, 12961 ArrayRef<QualType> Args) { 12962 // Build an exception specification pointing back at this constructor. 12963 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 12964 12965 LangAS AS = getDefaultCXXMethodAddrSpace(); 12966 if (AS != LangAS::Default) { 12967 EPI.TypeQuals.addAddressSpace(AS); 12968 } 12969 12970 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 12971 SpecialMem->setType(QT); 12972 } 12973 12974 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 12975 CXXRecordDecl *ClassDecl) { 12976 // C++ [class.ctor]p5: 12977 // A default constructor for a class X is a constructor of class X 12978 // that can be called without an argument. If there is no 12979 // user-declared constructor for class X, a default constructor is 12980 // implicitly declared. An implicitly-declared default constructor 12981 // is an inline public member of its class. 12982 assert(ClassDecl->needsImplicitDefaultConstructor() && 12983 "Should not build implicit default constructor!"); 12984 12985 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 12986 if (DSM.isAlreadyBeingDeclared()) 12987 return nullptr; 12988 12989 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12990 CXXDefaultConstructor, 12991 false); 12992 12993 // Create the actual constructor declaration. 12994 CanQualType ClassType 12995 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 12996 SourceLocation ClassLoc = ClassDecl->getLocation(); 12997 DeclarationName Name 12998 = Context.DeclarationNames.getCXXConstructorName(ClassType); 12999 DeclarationNameInfo NameInfo(Name, ClassLoc); 13000 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 13001 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 13002 /*TInfo=*/nullptr, ExplicitSpecifier(), 13003 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 13004 Constexpr ? ConstexprSpecKind::Constexpr 13005 : ConstexprSpecKind::Unspecified); 13006 DefaultCon->setAccess(AS_public); 13007 DefaultCon->setDefaulted(); 13008 13009 if (getLangOpts().CUDA) { 13010 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 13011 DefaultCon, 13012 /* ConstRHS */ false, 13013 /* Diagnose */ false); 13014 } 13015 13016 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 13017 13018 // We don't need to use SpecialMemberIsTrivial here; triviality for default 13019 // constructors is easy to compute. 13020 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 13021 13022 // Note that we have declared this constructor. 13023 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 13024 13025 Scope *S = getScopeForContext(ClassDecl); 13026 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 13027 13028 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 13029 SetDeclDeleted(DefaultCon, ClassLoc); 13030 13031 if (S) 13032 PushOnScopeChains(DefaultCon, S, false); 13033 ClassDecl->addDecl(DefaultCon); 13034 13035 return DefaultCon; 13036 } 13037 13038 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 13039 CXXConstructorDecl *Constructor) { 13040 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 13041 !Constructor->doesThisDeclarationHaveABody() && 13042 !Constructor->isDeleted()) && 13043 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 13044 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13045 return; 13046 13047 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13048 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 13049 13050 SynthesizedFunctionScope Scope(*this, Constructor); 13051 13052 // The exception specification is needed because we are defining the 13053 // function. 13054 ResolveExceptionSpec(CurrentLocation, 13055 Constructor->getType()->castAs<FunctionProtoType>()); 13056 MarkVTableUsed(CurrentLocation, ClassDecl); 13057 13058 // Add a context note for diagnostics produced after this point. 13059 Scope.addContextNote(CurrentLocation); 13060 13061 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 13062 Constructor->setInvalidDecl(); 13063 return; 13064 } 13065 13066 SourceLocation Loc = Constructor->getEndLoc().isValid() 13067 ? Constructor->getEndLoc() 13068 : Constructor->getLocation(); 13069 Constructor->setBody(new (Context) CompoundStmt(Loc)); 13070 Constructor->markUsed(Context); 13071 13072 if (ASTMutationListener *L = getASTMutationListener()) { 13073 L->CompletedImplicitDefinition(Constructor); 13074 } 13075 13076 DiagnoseUninitializedFields(*this, Constructor); 13077 } 13078 13079 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 13080 // Perform any delayed checks on exception specifications. 13081 CheckDelayedMemberExceptionSpecs(); 13082 } 13083 13084 /// Find or create the fake constructor we synthesize to model constructing an 13085 /// object of a derived class via a constructor of a base class. 13086 CXXConstructorDecl * 13087 Sema::findInheritingConstructor(SourceLocation Loc, 13088 CXXConstructorDecl *BaseCtor, 13089 ConstructorUsingShadowDecl *Shadow) { 13090 CXXRecordDecl *Derived = Shadow->getParent(); 13091 SourceLocation UsingLoc = Shadow->getLocation(); 13092 13093 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 13094 // For now we use the name of the base class constructor as a member of the 13095 // derived class to indicate a (fake) inherited constructor name. 13096 DeclarationName Name = BaseCtor->getDeclName(); 13097 13098 // Check to see if we already have a fake constructor for this inherited 13099 // constructor call. 13100 for (NamedDecl *Ctor : Derived->lookup(Name)) 13101 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 13102 ->getInheritedConstructor() 13103 .getConstructor(), 13104 BaseCtor)) 13105 return cast<CXXConstructorDecl>(Ctor); 13106 13107 DeclarationNameInfo NameInfo(Name, UsingLoc); 13108 TypeSourceInfo *TInfo = 13109 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 13110 FunctionProtoTypeLoc ProtoLoc = 13111 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 13112 13113 // Check the inherited constructor is valid and find the list of base classes 13114 // from which it was inherited. 13115 InheritedConstructorInfo ICI(*this, Loc, Shadow); 13116 13117 bool Constexpr = 13118 BaseCtor->isConstexpr() && 13119 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 13120 false, BaseCtor, &ICI); 13121 13122 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 13123 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 13124 BaseCtor->getExplicitSpecifier(), /*isInline=*/true, 13125 /*isImplicitlyDeclared=*/true, 13126 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified, 13127 InheritedConstructor(Shadow, BaseCtor), 13128 BaseCtor->getTrailingRequiresClause()); 13129 if (Shadow->isInvalidDecl()) 13130 DerivedCtor->setInvalidDecl(); 13131 13132 // Build an unevaluated exception specification for this fake constructor. 13133 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 13134 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13135 EPI.ExceptionSpec.Type = EST_Unevaluated; 13136 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 13137 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 13138 FPT->getParamTypes(), EPI)); 13139 13140 // Build the parameter declarations. 13141 SmallVector<ParmVarDecl *, 16> ParamDecls; 13142 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 13143 TypeSourceInfo *TInfo = 13144 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 13145 ParmVarDecl *PD = ParmVarDecl::Create( 13146 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 13147 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 13148 PD->setScopeInfo(0, I); 13149 PD->setImplicit(); 13150 // Ensure attributes are propagated onto parameters (this matters for 13151 // format, pass_object_size, ...). 13152 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 13153 ParamDecls.push_back(PD); 13154 ProtoLoc.setParam(I, PD); 13155 } 13156 13157 // Set up the new constructor. 13158 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 13159 DerivedCtor->setAccess(BaseCtor->getAccess()); 13160 DerivedCtor->setParams(ParamDecls); 13161 Derived->addDecl(DerivedCtor); 13162 13163 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 13164 SetDeclDeleted(DerivedCtor, UsingLoc); 13165 13166 return DerivedCtor; 13167 } 13168 13169 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 13170 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 13171 Ctor->getInheritedConstructor().getShadowDecl()); 13172 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 13173 /*Diagnose*/true); 13174 } 13175 13176 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 13177 CXXConstructorDecl *Constructor) { 13178 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13179 assert(Constructor->getInheritedConstructor() && 13180 !Constructor->doesThisDeclarationHaveABody() && 13181 !Constructor->isDeleted()); 13182 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13183 return; 13184 13185 // Initializations are performed "as if by a defaulted default constructor", 13186 // so enter the appropriate scope. 13187 SynthesizedFunctionScope Scope(*this, Constructor); 13188 13189 // The exception specification is needed because we are defining the 13190 // function. 13191 ResolveExceptionSpec(CurrentLocation, 13192 Constructor->getType()->castAs<FunctionProtoType>()); 13193 MarkVTableUsed(CurrentLocation, ClassDecl); 13194 13195 // Add a context note for diagnostics produced after this point. 13196 Scope.addContextNote(CurrentLocation); 13197 13198 ConstructorUsingShadowDecl *Shadow = 13199 Constructor->getInheritedConstructor().getShadowDecl(); 13200 CXXConstructorDecl *InheritedCtor = 13201 Constructor->getInheritedConstructor().getConstructor(); 13202 13203 // [class.inhctor.init]p1: 13204 // initialization proceeds as if a defaulted default constructor is used to 13205 // initialize the D object and each base class subobject from which the 13206 // constructor was inherited 13207 13208 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 13209 CXXRecordDecl *RD = Shadow->getParent(); 13210 SourceLocation InitLoc = Shadow->getLocation(); 13211 13212 // Build explicit initializers for all base classes from which the 13213 // constructor was inherited. 13214 SmallVector<CXXCtorInitializer*, 8> Inits; 13215 for (bool VBase : {false, true}) { 13216 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 13217 if (B.isVirtual() != VBase) 13218 continue; 13219 13220 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 13221 if (!BaseRD) 13222 continue; 13223 13224 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 13225 if (!BaseCtor.first) 13226 continue; 13227 13228 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 13229 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 13230 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 13231 13232 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 13233 Inits.push_back(new (Context) CXXCtorInitializer( 13234 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 13235 SourceLocation())); 13236 } 13237 } 13238 13239 // We now proceed as if for a defaulted default constructor, with the relevant 13240 // initializers replaced. 13241 13242 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 13243 Constructor->setInvalidDecl(); 13244 return; 13245 } 13246 13247 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 13248 Constructor->markUsed(Context); 13249 13250 if (ASTMutationListener *L = getASTMutationListener()) { 13251 L->CompletedImplicitDefinition(Constructor); 13252 } 13253 13254 DiagnoseUninitializedFields(*this, Constructor); 13255 } 13256 13257 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 13258 // C++ [class.dtor]p2: 13259 // If a class has no user-declared destructor, a destructor is 13260 // declared implicitly. An implicitly-declared destructor is an 13261 // inline public member of its class. 13262 assert(ClassDecl->needsImplicitDestructor()); 13263 13264 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 13265 if (DSM.isAlreadyBeingDeclared()) 13266 return nullptr; 13267 13268 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13269 CXXDestructor, 13270 false); 13271 13272 // Create the actual destructor declaration. 13273 CanQualType ClassType 13274 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13275 SourceLocation ClassLoc = ClassDecl->getLocation(); 13276 DeclarationName Name 13277 = Context.DeclarationNames.getCXXDestructorName(ClassType); 13278 DeclarationNameInfo NameInfo(Name, ClassLoc); 13279 CXXDestructorDecl *Destructor = 13280 CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 13281 QualType(), nullptr, /*isInline=*/true, 13282 /*isImplicitlyDeclared=*/true, 13283 Constexpr ? ConstexprSpecKind::Constexpr 13284 : ConstexprSpecKind::Unspecified); 13285 Destructor->setAccess(AS_public); 13286 Destructor->setDefaulted(); 13287 13288 if (getLangOpts().CUDA) { 13289 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 13290 Destructor, 13291 /* ConstRHS */ false, 13292 /* Diagnose */ false); 13293 } 13294 13295 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 13296 13297 // We don't need to use SpecialMemberIsTrivial here; triviality for 13298 // destructors is easy to compute. 13299 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 13300 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 13301 ClassDecl->hasTrivialDestructorForCall()); 13302 13303 // Note that we have declared this destructor. 13304 ++getASTContext().NumImplicitDestructorsDeclared; 13305 13306 Scope *S = getScopeForContext(ClassDecl); 13307 CheckImplicitSpecialMemberDeclaration(S, Destructor); 13308 13309 // We can't check whether an implicit destructor is deleted before we complete 13310 // the definition of the class, because its validity depends on the alignment 13311 // of the class. We'll check this from ActOnFields once the class is complete. 13312 if (ClassDecl->isCompleteDefinition() && 13313 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 13314 SetDeclDeleted(Destructor, ClassLoc); 13315 13316 // Introduce this destructor into its scope. 13317 if (S) 13318 PushOnScopeChains(Destructor, S, false); 13319 ClassDecl->addDecl(Destructor); 13320 13321 return Destructor; 13322 } 13323 13324 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 13325 CXXDestructorDecl *Destructor) { 13326 assert((Destructor->isDefaulted() && 13327 !Destructor->doesThisDeclarationHaveABody() && 13328 !Destructor->isDeleted()) && 13329 "DefineImplicitDestructor - call it for implicit default dtor"); 13330 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 13331 return; 13332 13333 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13334 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 13335 13336 SynthesizedFunctionScope Scope(*this, Destructor); 13337 13338 // The exception specification is needed because we are defining the 13339 // function. 13340 ResolveExceptionSpec(CurrentLocation, 13341 Destructor->getType()->castAs<FunctionProtoType>()); 13342 MarkVTableUsed(CurrentLocation, ClassDecl); 13343 13344 // Add a context note for diagnostics produced after this point. 13345 Scope.addContextNote(CurrentLocation); 13346 13347 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13348 Destructor->getParent()); 13349 13350 if (CheckDestructor(Destructor)) { 13351 Destructor->setInvalidDecl(); 13352 return; 13353 } 13354 13355 SourceLocation Loc = Destructor->getEndLoc().isValid() 13356 ? Destructor->getEndLoc() 13357 : Destructor->getLocation(); 13358 Destructor->setBody(new (Context) CompoundStmt(Loc)); 13359 Destructor->markUsed(Context); 13360 13361 if (ASTMutationListener *L = getASTMutationListener()) { 13362 L->CompletedImplicitDefinition(Destructor); 13363 } 13364 } 13365 13366 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 13367 CXXDestructorDecl *Destructor) { 13368 if (Destructor->isInvalidDecl()) 13369 return; 13370 13371 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13372 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() && 13373 "implicit complete dtors unneeded outside MS ABI"); 13374 assert(ClassDecl->getNumVBases() > 0 && 13375 "complete dtor only exists for classes with vbases"); 13376 13377 SynthesizedFunctionScope Scope(*this, Destructor); 13378 13379 // Add a context note for diagnostics produced after this point. 13380 Scope.addContextNote(CurrentLocation); 13381 13382 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl); 13383 } 13384 13385 /// Perform any semantic analysis which needs to be delayed until all 13386 /// pending class member declarations have been parsed. 13387 void Sema::ActOnFinishCXXMemberDecls() { 13388 // If the context is an invalid C++ class, just suppress these checks. 13389 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 13390 if (Record->isInvalidDecl()) { 13391 DelayedOverridingExceptionSpecChecks.clear(); 13392 DelayedEquivalentExceptionSpecChecks.clear(); 13393 return; 13394 } 13395 checkForMultipleExportedDefaultConstructors(*this, Record); 13396 } 13397 } 13398 13399 void Sema::ActOnFinishCXXNonNestedClass() { 13400 referenceDLLExportedClassMethods(); 13401 13402 if (!DelayedDllExportMemberFunctions.empty()) { 13403 SmallVector<CXXMethodDecl*, 4> WorkList; 13404 std::swap(DelayedDllExportMemberFunctions, WorkList); 13405 for (CXXMethodDecl *M : WorkList) { 13406 DefineDefaultedFunction(*this, M, M->getLocation()); 13407 13408 // Pass the method to the consumer to get emitted. This is not necessary 13409 // for explicit instantiation definitions, as they will get emitted 13410 // anyway. 13411 if (M->getParent()->getTemplateSpecializationKind() != 13412 TSK_ExplicitInstantiationDefinition) 13413 ActOnFinishInlineFunctionDef(M); 13414 } 13415 } 13416 } 13417 13418 void Sema::referenceDLLExportedClassMethods() { 13419 if (!DelayedDllExportClasses.empty()) { 13420 // Calling ReferenceDllExportedMembers might cause the current function to 13421 // be called again, so use a local copy of DelayedDllExportClasses. 13422 SmallVector<CXXRecordDecl *, 4> WorkList; 13423 std::swap(DelayedDllExportClasses, WorkList); 13424 for (CXXRecordDecl *Class : WorkList) 13425 ReferenceDllExportedMembers(*this, Class); 13426 } 13427 } 13428 13429 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 13430 assert(getLangOpts().CPlusPlus11 && 13431 "adjusting dtor exception specs was introduced in c++11"); 13432 13433 if (Destructor->isDependentContext()) 13434 return; 13435 13436 // C++11 [class.dtor]p3: 13437 // A declaration of a destructor that does not have an exception- 13438 // specification is implicitly considered to have the same exception- 13439 // specification as an implicit declaration. 13440 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); 13441 if (DtorType->hasExceptionSpec()) 13442 return; 13443 13444 // Replace the destructor's type, building off the existing one. Fortunately, 13445 // the only thing of interest in the destructor type is its extended info. 13446 // The return and arguments are fixed. 13447 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 13448 EPI.ExceptionSpec.Type = EST_Unevaluated; 13449 EPI.ExceptionSpec.SourceDecl = Destructor; 13450 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 13451 13452 // FIXME: If the destructor has a body that could throw, and the newly created 13453 // spec doesn't allow exceptions, we should emit a warning, because this 13454 // change in behavior can break conforming C++03 programs at runtime. 13455 // However, we don't have a body or an exception specification yet, so it 13456 // needs to be done somewhere else. 13457 } 13458 13459 namespace { 13460 /// An abstract base class for all helper classes used in building the 13461 // copy/move operators. These classes serve as factory functions and help us 13462 // avoid using the same Expr* in the AST twice. 13463 class ExprBuilder { 13464 ExprBuilder(const ExprBuilder&) = delete; 13465 ExprBuilder &operator=(const ExprBuilder&) = delete; 13466 13467 protected: 13468 static Expr *assertNotNull(Expr *E) { 13469 assert(E && "Expression construction must not fail."); 13470 return E; 13471 } 13472 13473 public: 13474 ExprBuilder() {} 13475 virtual ~ExprBuilder() {} 13476 13477 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 13478 }; 13479 13480 class RefBuilder: public ExprBuilder { 13481 VarDecl *Var; 13482 QualType VarType; 13483 13484 public: 13485 Expr *build(Sema &S, SourceLocation Loc) const override { 13486 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 13487 } 13488 13489 RefBuilder(VarDecl *Var, QualType VarType) 13490 : Var(Var), VarType(VarType) {} 13491 }; 13492 13493 class ThisBuilder: public ExprBuilder { 13494 public: 13495 Expr *build(Sema &S, SourceLocation Loc) const override { 13496 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 13497 } 13498 }; 13499 13500 class CastBuilder: public ExprBuilder { 13501 const ExprBuilder &Builder; 13502 QualType Type; 13503 ExprValueKind Kind; 13504 const CXXCastPath &Path; 13505 13506 public: 13507 Expr *build(Sema &S, SourceLocation Loc) const override { 13508 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 13509 CK_UncheckedDerivedToBase, Kind, 13510 &Path).get()); 13511 } 13512 13513 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 13514 const CXXCastPath &Path) 13515 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 13516 }; 13517 13518 class DerefBuilder: public ExprBuilder { 13519 const ExprBuilder &Builder; 13520 13521 public: 13522 Expr *build(Sema &S, SourceLocation Loc) const override { 13523 return assertNotNull( 13524 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 13525 } 13526 13527 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13528 }; 13529 13530 class MemberBuilder: public ExprBuilder { 13531 const ExprBuilder &Builder; 13532 QualType Type; 13533 CXXScopeSpec SS; 13534 bool IsArrow; 13535 LookupResult &MemberLookup; 13536 13537 public: 13538 Expr *build(Sema &S, SourceLocation Loc) const override { 13539 return assertNotNull(S.BuildMemberReferenceExpr( 13540 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 13541 nullptr, MemberLookup, nullptr, nullptr).get()); 13542 } 13543 13544 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 13545 LookupResult &MemberLookup) 13546 : Builder(Builder), Type(Type), IsArrow(IsArrow), 13547 MemberLookup(MemberLookup) {} 13548 }; 13549 13550 class MoveCastBuilder: public ExprBuilder { 13551 const ExprBuilder &Builder; 13552 13553 public: 13554 Expr *build(Sema &S, SourceLocation Loc) const override { 13555 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 13556 } 13557 13558 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13559 }; 13560 13561 class LvalueConvBuilder: public ExprBuilder { 13562 const ExprBuilder &Builder; 13563 13564 public: 13565 Expr *build(Sema &S, SourceLocation Loc) const override { 13566 return assertNotNull( 13567 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 13568 } 13569 13570 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13571 }; 13572 13573 class SubscriptBuilder: public ExprBuilder { 13574 const ExprBuilder &Base; 13575 const ExprBuilder &Index; 13576 13577 public: 13578 Expr *build(Sema &S, SourceLocation Loc) const override { 13579 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 13580 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 13581 } 13582 13583 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 13584 : Base(Base), Index(Index) {} 13585 }; 13586 13587 } // end anonymous namespace 13588 13589 /// When generating a defaulted copy or move assignment operator, if a field 13590 /// should be copied with __builtin_memcpy rather than via explicit assignments, 13591 /// do so. This optimization only applies for arrays of scalars, and for arrays 13592 /// of class type where the selected copy/move-assignment operator is trivial. 13593 static StmtResult 13594 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 13595 const ExprBuilder &ToB, const ExprBuilder &FromB) { 13596 // Compute the size of the memory buffer to be copied. 13597 QualType SizeType = S.Context.getSizeType(); 13598 llvm::APInt Size(S.Context.getTypeSize(SizeType), 13599 S.Context.getTypeSizeInChars(T).getQuantity()); 13600 13601 // Take the address of the field references for "from" and "to". We 13602 // directly construct UnaryOperators here because semantic analysis 13603 // does not permit us to take the address of an xvalue. 13604 Expr *From = FromB.build(S, Loc); 13605 From = UnaryOperator::Create( 13606 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()), 13607 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13608 Expr *To = ToB.build(S, Loc); 13609 To = UnaryOperator::Create( 13610 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()), 13611 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13612 13613 const Type *E = T->getBaseElementTypeUnsafe(); 13614 bool NeedsCollectableMemCpy = 13615 E->isRecordType() && 13616 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 13617 13618 // Create a reference to the __builtin_objc_memmove_collectable function 13619 StringRef MemCpyName = NeedsCollectableMemCpy ? 13620 "__builtin_objc_memmove_collectable" : 13621 "__builtin_memcpy"; 13622 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 13623 Sema::LookupOrdinaryName); 13624 S.LookupName(R, S.TUScope, true); 13625 13626 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 13627 if (!MemCpy) 13628 // Something went horribly wrong earlier, and we will have complained 13629 // about it. 13630 return StmtError(); 13631 13632 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 13633 VK_RValue, Loc, nullptr); 13634 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 13635 13636 Expr *CallArgs[] = { 13637 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 13638 }; 13639 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 13640 Loc, CallArgs, Loc); 13641 13642 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 13643 return Call.getAs<Stmt>(); 13644 } 13645 13646 /// Builds a statement that copies/moves the given entity from \p From to 13647 /// \c To. 13648 /// 13649 /// This routine is used to copy/move the members of a class with an 13650 /// implicitly-declared copy/move assignment operator. When the entities being 13651 /// copied are arrays, this routine builds for loops to copy them. 13652 /// 13653 /// \param S The Sema object used for type-checking. 13654 /// 13655 /// \param Loc The location where the implicit copy/move is being generated. 13656 /// 13657 /// \param T The type of the expressions being copied/moved. Both expressions 13658 /// must have this type. 13659 /// 13660 /// \param To The expression we are copying/moving to. 13661 /// 13662 /// \param From The expression we are copying/moving from. 13663 /// 13664 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 13665 /// Otherwise, it's a non-static member subobject. 13666 /// 13667 /// \param Copying Whether we're copying or moving. 13668 /// 13669 /// \param Depth Internal parameter recording the depth of the recursion. 13670 /// 13671 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 13672 /// if a memcpy should be used instead. 13673 static StmtResult 13674 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 13675 const ExprBuilder &To, const ExprBuilder &From, 13676 bool CopyingBaseSubobject, bool Copying, 13677 unsigned Depth = 0) { 13678 // C++11 [class.copy]p28: 13679 // Each subobject is assigned in the manner appropriate to its type: 13680 // 13681 // - if the subobject is of class type, as if by a call to operator= with 13682 // the subobject as the object expression and the corresponding 13683 // subobject of x as a single function argument (as if by explicit 13684 // qualification; that is, ignoring any possible virtual overriding 13685 // functions in more derived classes); 13686 // 13687 // C++03 [class.copy]p13: 13688 // - if the subobject is of class type, the copy assignment operator for 13689 // the class is used (as if by explicit qualification; that is, 13690 // ignoring any possible virtual overriding functions in more derived 13691 // classes); 13692 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 13693 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 13694 13695 // Look for operator=. 13696 DeclarationName Name 13697 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13698 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 13699 S.LookupQualifiedName(OpLookup, ClassDecl, false); 13700 13701 // Prior to C++11, filter out any result that isn't a copy/move-assignment 13702 // operator. 13703 if (!S.getLangOpts().CPlusPlus11) { 13704 LookupResult::Filter F = OpLookup.makeFilter(); 13705 while (F.hasNext()) { 13706 NamedDecl *D = F.next(); 13707 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 13708 if (Method->isCopyAssignmentOperator() || 13709 (!Copying && Method->isMoveAssignmentOperator())) 13710 continue; 13711 13712 F.erase(); 13713 } 13714 F.done(); 13715 } 13716 13717 // Suppress the protected check (C++ [class.protected]) for each of the 13718 // assignment operators we found. This strange dance is required when 13719 // we're assigning via a base classes's copy-assignment operator. To 13720 // ensure that we're getting the right base class subobject (without 13721 // ambiguities), we need to cast "this" to that subobject type; to 13722 // ensure that we don't go through the virtual call mechanism, we need 13723 // to qualify the operator= name with the base class (see below). However, 13724 // this means that if the base class has a protected copy assignment 13725 // operator, the protected member access check will fail. So, we 13726 // rewrite "protected" access to "public" access in this case, since we 13727 // know by construction that we're calling from a derived class. 13728 if (CopyingBaseSubobject) { 13729 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 13730 L != LEnd; ++L) { 13731 if (L.getAccess() == AS_protected) 13732 L.setAccess(AS_public); 13733 } 13734 } 13735 13736 // Create the nested-name-specifier that will be used to qualify the 13737 // reference to operator=; this is required to suppress the virtual 13738 // call mechanism. 13739 CXXScopeSpec SS; 13740 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 13741 SS.MakeTrivial(S.Context, 13742 NestedNameSpecifier::Create(S.Context, nullptr, false, 13743 CanonicalT), 13744 Loc); 13745 13746 // Create the reference to operator=. 13747 ExprResult OpEqualRef 13748 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 13749 SS, /*TemplateKWLoc=*/SourceLocation(), 13750 /*FirstQualifierInScope=*/nullptr, 13751 OpLookup, 13752 /*TemplateArgs=*/nullptr, /*S*/nullptr, 13753 /*SuppressQualifierCheck=*/true); 13754 if (OpEqualRef.isInvalid()) 13755 return StmtError(); 13756 13757 // Build the call to the assignment operator. 13758 13759 Expr *FromInst = From.build(S, Loc); 13760 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 13761 OpEqualRef.getAs<Expr>(), 13762 Loc, FromInst, Loc); 13763 if (Call.isInvalid()) 13764 return StmtError(); 13765 13766 // If we built a call to a trivial 'operator=' while copying an array, 13767 // bail out. We'll replace the whole shebang with a memcpy. 13768 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 13769 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 13770 return StmtResult((Stmt*)nullptr); 13771 13772 // Convert to an expression-statement, and clean up any produced 13773 // temporaries. 13774 return S.ActOnExprStmt(Call); 13775 } 13776 13777 // - if the subobject is of scalar type, the built-in assignment 13778 // operator is used. 13779 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 13780 if (!ArrayTy) { 13781 ExprResult Assignment = S.CreateBuiltinBinOp( 13782 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 13783 if (Assignment.isInvalid()) 13784 return StmtError(); 13785 return S.ActOnExprStmt(Assignment); 13786 } 13787 13788 // - if the subobject is an array, each element is assigned, in the 13789 // manner appropriate to the element type; 13790 13791 // Construct a loop over the array bounds, e.g., 13792 // 13793 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 13794 // 13795 // that will copy each of the array elements. 13796 QualType SizeType = S.Context.getSizeType(); 13797 13798 // Create the iteration variable. 13799 IdentifierInfo *IterationVarName = nullptr; 13800 { 13801 SmallString<8> Str; 13802 llvm::raw_svector_ostream OS(Str); 13803 OS << "__i" << Depth; 13804 IterationVarName = &S.Context.Idents.get(OS.str()); 13805 } 13806 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 13807 IterationVarName, SizeType, 13808 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 13809 SC_None); 13810 13811 // Initialize the iteration variable to zero. 13812 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 13813 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 13814 13815 // Creates a reference to the iteration variable. 13816 RefBuilder IterationVarRef(IterationVar, SizeType); 13817 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 13818 13819 // Create the DeclStmt that holds the iteration variable. 13820 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 13821 13822 // Subscript the "from" and "to" expressions with the iteration variable. 13823 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 13824 MoveCastBuilder FromIndexMove(FromIndexCopy); 13825 const ExprBuilder *FromIndex; 13826 if (Copying) 13827 FromIndex = &FromIndexCopy; 13828 else 13829 FromIndex = &FromIndexMove; 13830 13831 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 13832 13833 // Build the copy/move for an individual element of the array. 13834 StmtResult Copy = 13835 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 13836 ToIndex, *FromIndex, CopyingBaseSubobject, 13837 Copying, Depth + 1); 13838 // Bail out if copying fails or if we determined that we should use memcpy. 13839 if (Copy.isInvalid() || !Copy.get()) 13840 return Copy; 13841 13842 // Create the comparison against the array bound. 13843 llvm::APInt Upper 13844 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 13845 Expr *Comparison = BinaryOperator::Create( 13846 S.Context, IterationVarRefRVal.build(S, Loc), 13847 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE, 13848 S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides()); 13849 13850 // Create the pre-increment of the iteration variable. We can determine 13851 // whether the increment will overflow based on the value of the array 13852 // bound. 13853 Expr *Increment = UnaryOperator::Create( 13854 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue, 13855 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides()); 13856 13857 // Construct the loop that copies all elements of this array. 13858 return S.ActOnForStmt( 13859 Loc, Loc, InitStmt, 13860 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 13861 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 13862 } 13863 13864 static StmtResult 13865 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 13866 const ExprBuilder &To, const ExprBuilder &From, 13867 bool CopyingBaseSubobject, bool Copying) { 13868 // Maybe we should use a memcpy? 13869 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 13870 T.isTriviallyCopyableType(S.Context)) 13871 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13872 13873 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 13874 CopyingBaseSubobject, 13875 Copying, 0)); 13876 13877 // If we ended up picking a trivial assignment operator for an array of a 13878 // non-trivially-copyable class type, just emit a memcpy. 13879 if (!Result.isInvalid() && !Result.get()) 13880 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13881 13882 return Result; 13883 } 13884 13885 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 13886 // Note: The following rules are largely analoguous to the copy 13887 // constructor rules. Note that virtual bases are not taken into account 13888 // for determining the argument type of the operator. Note also that 13889 // operators taking an object instead of a reference are allowed. 13890 assert(ClassDecl->needsImplicitCopyAssignment()); 13891 13892 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 13893 if (DSM.isAlreadyBeingDeclared()) 13894 return nullptr; 13895 13896 QualType ArgType = Context.getTypeDeclType(ClassDecl); 13897 LangAS AS = getDefaultCXXMethodAddrSpace(); 13898 if (AS != LangAS::Default) 13899 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 13900 QualType RetType = Context.getLValueReferenceType(ArgType); 13901 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 13902 if (Const) 13903 ArgType = ArgType.withConst(); 13904 13905 ArgType = Context.getLValueReferenceType(ArgType); 13906 13907 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13908 CXXCopyAssignment, 13909 Const); 13910 13911 // An implicitly-declared copy assignment operator is an inline public 13912 // member of its class. 13913 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13914 SourceLocation ClassLoc = ClassDecl->getLocation(); 13915 DeclarationNameInfo NameInfo(Name, ClassLoc); 13916 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 13917 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 13918 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 13919 /*isInline=*/true, 13920 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 13921 SourceLocation()); 13922 CopyAssignment->setAccess(AS_public); 13923 CopyAssignment->setDefaulted(); 13924 CopyAssignment->setImplicit(); 13925 13926 if (getLangOpts().CUDA) { 13927 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 13928 CopyAssignment, 13929 /* ConstRHS */ Const, 13930 /* Diagnose */ false); 13931 } 13932 13933 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 13934 13935 // Add the parameter to the operator. 13936 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 13937 ClassLoc, ClassLoc, 13938 /*Id=*/nullptr, ArgType, 13939 /*TInfo=*/nullptr, SC_None, 13940 nullptr); 13941 CopyAssignment->setParams(FromParam); 13942 13943 CopyAssignment->setTrivial( 13944 ClassDecl->needsOverloadResolutionForCopyAssignment() 13945 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 13946 : ClassDecl->hasTrivialCopyAssignment()); 13947 13948 // Note that we have added this copy-assignment operator. 13949 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 13950 13951 Scope *S = getScopeForContext(ClassDecl); 13952 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 13953 13954 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) { 13955 ClassDecl->setImplicitCopyAssignmentIsDeleted(); 13956 SetDeclDeleted(CopyAssignment, ClassLoc); 13957 } 13958 13959 if (S) 13960 PushOnScopeChains(CopyAssignment, S, false); 13961 ClassDecl->addDecl(CopyAssignment); 13962 13963 return CopyAssignment; 13964 } 13965 13966 /// Diagnose an implicit copy operation for a class which is odr-used, but 13967 /// which is deprecated because the class has a user-declared copy constructor, 13968 /// copy assignment operator, or destructor. 13969 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 13970 assert(CopyOp->isImplicit()); 13971 13972 CXXRecordDecl *RD = CopyOp->getParent(); 13973 CXXMethodDecl *UserDeclaredOperation = nullptr; 13974 13975 // In Microsoft mode, assignment operations don't affect constructors and 13976 // vice versa. 13977 if (RD->hasUserDeclaredDestructor()) { 13978 UserDeclaredOperation = RD->getDestructor(); 13979 } else if (!isa<CXXConstructorDecl>(CopyOp) && 13980 RD->hasUserDeclaredCopyConstructor() && 13981 !S.getLangOpts().MSVCCompat) { 13982 // Find any user-declared copy constructor. 13983 for (auto *I : RD->ctors()) { 13984 if (I->isCopyConstructor()) { 13985 UserDeclaredOperation = I; 13986 break; 13987 } 13988 } 13989 assert(UserDeclaredOperation); 13990 } else if (isa<CXXConstructorDecl>(CopyOp) && 13991 RD->hasUserDeclaredCopyAssignment() && 13992 !S.getLangOpts().MSVCCompat) { 13993 // Find any user-declared move assignment operator. 13994 for (auto *I : RD->methods()) { 13995 if (I->isCopyAssignmentOperator()) { 13996 UserDeclaredOperation = I; 13997 break; 13998 } 13999 } 14000 assert(UserDeclaredOperation); 14001 } 14002 14003 if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) { 14004 S.Diag(UserDeclaredOperation->getLocation(), 14005 isa<CXXDestructorDecl>(UserDeclaredOperation) 14006 ? diag::warn_deprecated_copy_dtor_operation 14007 : diag::warn_deprecated_copy_operation) 14008 << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp); 14009 } 14010 } 14011 14012 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 14013 CXXMethodDecl *CopyAssignOperator) { 14014 assert((CopyAssignOperator->isDefaulted() && 14015 CopyAssignOperator->isOverloadedOperator() && 14016 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 14017 !CopyAssignOperator->doesThisDeclarationHaveABody() && 14018 !CopyAssignOperator->isDeleted()) && 14019 "DefineImplicitCopyAssignment called for wrong function"); 14020 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 14021 return; 14022 14023 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 14024 if (ClassDecl->isInvalidDecl()) { 14025 CopyAssignOperator->setInvalidDecl(); 14026 return; 14027 } 14028 14029 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 14030 14031 // The exception specification is needed because we are defining the 14032 // function. 14033 ResolveExceptionSpec(CurrentLocation, 14034 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 14035 14036 // Add a context note for diagnostics produced after this point. 14037 Scope.addContextNote(CurrentLocation); 14038 14039 // C++11 [class.copy]p18: 14040 // The [definition of an implicitly declared copy assignment operator] is 14041 // deprecated if the class has a user-declared copy constructor or a 14042 // user-declared destructor. 14043 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 14044 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 14045 14046 // C++0x [class.copy]p30: 14047 // The implicitly-defined or explicitly-defaulted copy assignment operator 14048 // for a non-union class X performs memberwise copy assignment of its 14049 // subobjects. The direct base classes of X are assigned first, in the 14050 // order of their declaration in the base-specifier-list, and then the 14051 // immediate non-static data members of X are assigned, in the order in 14052 // which they were declared in the class definition. 14053 14054 // The statements that form the synthesized function body. 14055 SmallVector<Stmt*, 8> Statements; 14056 14057 // The parameter for the "other" object, which we are copying from. 14058 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 14059 Qualifiers OtherQuals = Other->getType().getQualifiers(); 14060 QualType OtherRefType = Other->getType(); 14061 if (const LValueReferenceType *OtherRef 14062 = OtherRefType->getAs<LValueReferenceType>()) { 14063 OtherRefType = OtherRef->getPointeeType(); 14064 OtherQuals = OtherRefType.getQualifiers(); 14065 } 14066 14067 // Our location for everything implicitly-generated. 14068 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 14069 ? CopyAssignOperator->getEndLoc() 14070 : CopyAssignOperator->getLocation(); 14071 14072 // Builds a DeclRefExpr for the "other" object. 14073 RefBuilder OtherRef(Other, OtherRefType); 14074 14075 // Builds the "this" pointer. 14076 ThisBuilder This; 14077 14078 // Assign base classes. 14079 bool Invalid = false; 14080 for (auto &Base : ClassDecl->bases()) { 14081 // Form the assignment: 14082 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 14083 QualType BaseType = Base.getType().getUnqualifiedType(); 14084 if (!BaseType->isRecordType()) { 14085 Invalid = true; 14086 continue; 14087 } 14088 14089 CXXCastPath BasePath; 14090 BasePath.push_back(&Base); 14091 14092 // Construct the "from" expression, which is an implicit cast to the 14093 // appropriately-qualified base type. 14094 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 14095 VK_LValue, BasePath); 14096 14097 // Dereference "this". 14098 DerefBuilder DerefThis(This); 14099 CastBuilder To(DerefThis, 14100 Context.getQualifiedType( 14101 BaseType, CopyAssignOperator->getMethodQualifiers()), 14102 VK_LValue, BasePath); 14103 14104 // Build the copy. 14105 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 14106 To, From, 14107 /*CopyingBaseSubobject=*/true, 14108 /*Copying=*/true); 14109 if (Copy.isInvalid()) { 14110 CopyAssignOperator->setInvalidDecl(); 14111 return; 14112 } 14113 14114 // Success! Record the copy. 14115 Statements.push_back(Copy.getAs<Expr>()); 14116 } 14117 14118 // Assign non-static members. 14119 for (auto *Field : ClassDecl->fields()) { 14120 // FIXME: We should form some kind of AST representation for the implied 14121 // memcpy in a union copy operation. 14122 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14123 continue; 14124 14125 if (Field->isInvalidDecl()) { 14126 Invalid = true; 14127 continue; 14128 } 14129 14130 // Check for members of reference type; we can't copy those. 14131 if (Field->getType()->isReferenceType()) { 14132 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14133 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14134 Diag(Field->getLocation(), diag::note_declared_at); 14135 Invalid = true; 14136 continue; 14137 } 14138 14139 // Check for members of const-qualified, non-class type. 14140 QualType BaseType = Context.getBaseElementType(Field->getType()); 14141 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14142 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14143 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14144 Diag(Field->getLocation(), diag::note_declared_at); 14145 Invalid = true; 14146 continue; 14147 } 14148 14149 // Suppress assigning zero-width bitfields. 14150 if (Field->isZeroLengthBitField(Context)) 14151 continue; 14152 14153 QualType FieldType = Field->getType().getNonReferenceType(); 14154 if (FieldType->isIncompleteArrayType()) { 14155 assert(ClassDecl->hasFlexibleArrayMember() && 14156 "Incomplete array type is not valid"); 14157 continue; 14158 } 14159 14160 // Build references to the field in the object we're copying from and to. 14161 CXXScopeSpec SS; // Intentionally empty 14162 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14163 LookupMemberName); 14164 MemberLookup.addDecl(Field); 14165 MemberLookup.resolveKind(); 14166 14167 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 14168 14169 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 14170 14171 // Build the copy of this field. 14172 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 14173 To, From, 14174 /*CopyingBaseSubobject=*/false, 14175 /*Copying=*/true); 14176 if (Copy.isInvalid()) { 14177 CopyAssignOperator->setInvalidDecl(); 14178 return; 14179 } 14180 14181 // Success! Record the copy. 14182 Statements.push_back(Copy.getAs<Stmt>()); 14183 } 14184 14185 if (!Invalid) { 14186 // Add a "return *this;" 14187 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14188 14189 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14190 if (Return.isInvalid()) 14191 Invalid = true; 14192 else 14193 Statements.push_back(Return.getAs<Stmt>()); 14194 } 14195 14196 if (Invalid) { 14197 CopyAssignOperator->setInvalidDecl(); 14198 return; 14199 } 14200 14201 StmtResult Body; 14202 { 14203 CompoundScopeRAII CompoundScope(*this); 14204 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14205 /*isStmtExpr=*/false); 14206 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14207 } 14208 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 14209 CopyAssignOperator->markUsed(Context); 14210 14211 if (ASTMutationListener *L = getASTMutationListener()) { 14212 L->CompletedImplicitDefinition(CopyAssignOperator); 14213 } 14214 } 14215 14216 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 14217 assert(ClassDecl->needsImplicitMoveAssignment()); 14218 14219 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 14220 if (DSM.isAlreadyBeingDeclared()) 14221 return nullptr; 14222 14223 // Note: The following rules are largely analoguous to the move 14224 // constructor rules. 14225 14226 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14227 LangAS AS = getDefaultCXXMethodAddrSpace(); 14228 if (AS != LangAS::Default) 14229 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14230 QualType RetType = Context.getLValueReferenceType(ArgType); 14231 ArgType = Context.getRValueReferenceType(ArgType); 14232 14233 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14234 CXXMoveAssignment, 14235 false); 14236 14237 // An implicitly-declared move assignment operator is an inline public 14238 // member of its class. 14239 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14240 SourceLocation ClassLoc = ClassDecl->getLocation(); 14241 DeclarationNameInfo NameInfo(Name, ClassLoc); 14242 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 14243 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14244 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14245 /*isInline=*/true, 14246 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14247 SourceLocation()); 14248 MoveAssignment->setAccess(AS_public); 14249 MoveAssignment->setDefaulted(); 14250 MoveAssignment->setImplicit(); 14251 14252 if (getLangOpts().CUDA) { 14253 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 14254 MoveAssignment, 14255 /* ConstRHS */ false, 14256 /* Diagnose */ false); 14257 } 14258 14259 // Build an exception specification pointing back at this member. 14260 FunctionProtoType::ExtProtoInfo EPI = 14261 getImplicitMethodEPI(*this, MoveAssignment); 14262 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 14263 14264 // Add the parameter to the operator. 14265 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 14266 ClassLoc, ClassLoc, 14267 /*Id=*/nullptr, ArgType, 14268 /*TInfo=*/nullptr, SC_None, 14269 nullptr); 14270 MoveAssignment->setParams(FromParam); 14271 14272 MoveAssignment->setTrivial( 14273 ClassDecl->needsOverloadResolutionForMoveAssignment() 14274 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 14275 : ClassDecl->hasTrivialMoveAssignment()); 14276 14277 // Note that we have added this copy-assignment operator. 14278 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 14279 14280 Scope *S = getScopeForContext(ClassDecl); 14281 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 14282 14283 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 14284 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 14285 SetDeclDeleted(MoveAssignment, ClassLoc); 14286 } 14287 14288 if (S) 14289 PushOnScopeChains(MoveAssignment, S, false); 14290 ClassDecl->addDecl(MoveAssignment); 14291 14292 return MoveAssignment; 14293 } 14294 14295 /// Check if we're implicitly defining a move assignment operator for a class 14296 /// with virtual bases. Such a move assignment might move-assign the virtual 14297 /// base multiple times. 14298 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 14299 SourceLocation CurrentLocation) { 14300 assert(!Class->isDependentContext() && "should not define dependent move"); 14301 14302 // Only a virtual base could get implicitly move-assigned multiple times. 14303 // Only a non-trivial move assignment can observe this. We only want to 14304 // diagnose if we implicitly define an assignment operator that assigns 14305 // two base classes, both of which move-assign the same virtual base. 14306 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 14307 Class->getNumBases() < 2) 14308 return; 14309 14310 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 14311 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 14312 VBaseMap VBases; 14313 14314 for (auto &BI : Class->bases()) { 14315 Worklist.push_back(&BI); 14316 while (!Worklist.empty()) { 14317 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 14318 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 14319 14320 // If the base has no non-trivial move assignment operators, 14321 // we don't care about moves from it. 14322 if (!Base->hasNonTrivialMoveAssignment()) 14323 continue; 14324 14325 // If there's nothing virtual here, skip it. 14326 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 14327 continue; 14328 14329 // If we're not actually going to call a move assignment for this base, 14330 // or the selected move assignment is trivial, skip it. 14331 Sema::SpecialMemberOverloadResult SMOR = 14332 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 14333 /*ConstArg*/false, /*VolatileArg*/false, 14334 /*RValueThis*/true, /*ConstThis*/false, 14335 /*VolatileThis*/false); 14336 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 14337 !SMOR.getMethod()->isMoveAssignmentOperator()) 14338 continue; 14339 14340 if (BaseSpec->isVirtual()) { 14341 // We're going to move-assign this virtual base, and its move 14342 // assignment operator is not trivial. If this can happen for 14343 // multiple distinct direct bases of Class, diagnose it. (If it 14344 // only happens in one base, we'll diagnose it when synthesizing 14345 // that base class's move assignment operator.) 14346 CXXBaseSpecifier *&Existing = 14347 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 14348 .first->second; 14349 if (Existing && Existing != &BI) { 14350 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 14351 << Class << Base; 14352 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 14353 << (Base->getCanonicalDecl() == 14354 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14355 << Base << Existing->getType() << Existing->getSourceRange(); 14356 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 14357 << (Base->getCanonicalDecl() == 14358 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14359 << Base << BI.getType() << BaseSpec->getSourceRange(); 14360 14361 // Only diagnose each vbase once. 14362 Existing = nullptr; 14363 } 14364 } else { 14365 // Only walk over bases that have defaulted move assignment operators. 14366 // We assume that any user-provided move assignment operator handles 14367 // the multiple-moves-of-vbase case itself somehow. 14368 if (!SMOR.getMethod()->isDefaulted()) 14369 continue; 14370 14371 // We're going to move the base classes of Base. Add them to the list. 14372 for (auto &BI : Base->bases()) 14373 Worklist.push_back(&BI); 14374 } 14375 } 14376 } 14377 } 14378 14379 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 14380 CXXMethodDecl *MoveAssignOperator) { 14381 assert((MoveAssignOperator->isDefaulted() && 14382 MoveAssignOperator->isOverloadedOperator() && 14383 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 14384 !MoveAssignOperator->doesThisDeclarationHaveABody() && 14385 !MoveAssignOperator->isDeleted()) && 14386 "DefineImplicitMoveAssignment called for wrong function"); 14387 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 14388 return; 14389 14390 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 14391 if (ClassDecl->isInvalidDecl()) { 14392 MoveAssignOperator->setInvalidDecl(); 14393 return; 14394 } 14395 14396 // C++0x [class.copy]p28: 14397 // The implicitly-defined or move assignment operator for a non-union class 14398 // X performs memberwise move assignment of its subobjects. The direct base 14399 // classes of X are assigned first, in the order of their declaration in the 14400 // base-specifier-list, and then the immediate non-static data members of X 14401 // are assigned, in the order in which they were declared in the class 14402 // definition. 14403 14404 // Issue a warning if our implicit move assignment operator will move 14405 // from a virtual base more than once. 14406 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 14407 14408 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 14409 14410 // The exception specification is needed because we are defining the 14411 // function. 14412 ResolveExceptionSpec(CurrentLocation, 14413 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 14414 14415 // Add a context note for diagnostics produced after this point. 14416 Scope.addContextNote(CurrentLocation); 14417 14418 // The statements that form the synthesized function body. 14419 SmallVector<Stmt*, 8> Statements; 14420 14421 // The parameter for the "other" object, which we are move from. 14422 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 14423 QualType OtherRefType = 14424 Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); 14425 14426 // Our location for everything implicitly-generated. 14427 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 14428 ? MoveAssignOperator->getEndLoc() 14429 : MoveAssignOperator->getLocation(); 14430 14431 // Builds a reference to the "other" object. 14432 RefBuilder OtherRef(Other, OtherRefType); 14433 // Cast to rvalue. 14434 MoveCastBuilder MoveOther(OtherRef); 14435 14436 // Builds the "this" pointer. 14437 ThisBuilder This; 14438 14439 // Assign base classes. 14440 bool Invalid = false; 14441 for (auto &Base : ClassDecl->bases()) { 14442 // C++11 [class.copy]p28: 14443 // It is unspecified whether subobjects representing virtual base classes 14444 // are assigned more than once by the implicitly-defined copy assignment 14445 // operator. 14446 // FIXME: Do not assign to a vbase that will be assigned by some other base 14447 // class. For a move-assignment, this can result in the vbase being moved 14448 // multiple times. 14449 14450 // Form the assignment: 14451 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 14452 QualType BaseType = Base.getType().getUnqualifiedType(); 14453 if (!BaseType->isRecordType()) { 14454 Invalid = true; 14455 continue; 14456 } 14457 14458 CXXCastPath BasePath; 14459 BasePath.push_back(&Base); 14460 14461 // Construct the "from" expression, which is an implicit cast to the 14462 // appropriately-qualified base type. 14463 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 14464 14465 // Dereference "this". 14466 DerefBuilder DerefThis(This); 14467 14468 // Implicitly cast "this" to the appropriately-qualified base type. 14469 CastBuilder To(DerefThis, 14470 Context.getQualifiedType( 14471 BaseType, MoveAssignOperator->getMethodQualifiers()), 14472 VK_LValue, BasePath); 14473 14474 // Build the move. 14475 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 14476 To, From, 14477 /*CopyingBaseSubobject=*/true, 14478 /*Copying=*/false); 14479 if (Move.isInvalid()) { 14480 MoveAssignOperator->setInvalidDecl(); 14481 return; 14482 } 14483 14484 // Success! Record the move. 14485 Statements.push_back(Move.getAs<Expr>()); 14486 } 14487 14488 // Assign non-static members. 14489 for (auto *Field : ClassDecl->fields()) { 14490 // FIXME: We should form some kind of AST representation for the implied 14491 // memcpy in a union copy operation. 14492 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14493 continue; 14494 14495 if (Field->isInvalidDecl()) { 14496 Invalid = true; 14497 continue; 14498 } 14499 14500 // Check for members of reference type; we can't move those. 14501 if (Field->getType()->isReferenceType()) { 14502 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14503 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14504 Diag(Field->getLocation(), diag::note_declared_at); 14505 Invalid = true; 14506 continue; 14507 } 14508 14509 // Check for members of const-qualified, non-class type. 14510 QualType BaseType = Context.getBaseElementType(Field->getType()); 14511 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14512 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14513 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14514 Diag(Field->getLocation(), diag::note_declared_at); 14515 Invalid = true; 14516 continue; 14517 } 14518 14519 // Suppress assigning zero-width bitfields. 14520 if (Field->isZeroLengthBitField(Context)) 14521 continue; 14522 14523 QualType FieldType = Field->getType().getNonReferenceType(); 14524 if (FieldType->isIncompleteArrayType()) { 14525 assert(ClassDecl->hasFlexibleArrayMember() && 14526 "Incomplete array type is not valid"); 14527 continue; 14528 } 14529 14530 // Build references to the field in the object we're copying from and to. 14531 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14532 LookupMemberName); 14533 MemberLookup.addDecl(Field); 14534 MemberLookup.resolveKind(); 14535 MemberBuilder From(MoveOther, OtherRefType, 14536 /*IsArrow=*/false, MemberLookup); 14537 MemberBuilder To(This, getCurrentThisType(), 14538 /*IsArrow=*/true, MemberLookup); 14539 14540 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 14541 "Member reference with rvalue base must be rvalue except for reference " 14542 "members, which aren't allowed for move assignment."); 14543 14544 // Build the move of this field. 14545 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 14546 To, From, 14547 /*CopyingBaseSubobject=*/false, 14548 /*Copying=*/false); 14549 if (Move.isInvalid()) { 14550 MoveAssignOperator->setInvalidDecl(); 14551 return; 14552 } 14553 14554 // Success! Record the copy. 14555 Statements.push_back(Move.getAs<Stmt>()); 14556 } 14557 14558 if (!Invalid) { 14559 // Add a "return *this;" 14560 ExprResult ThisObj = 14561 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14562 14563 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14564 if (Return.isInvalid()) 14565 Invalid = true; 14566 else 14567 Statements.push_back(Return.getAs<Stmt>()); 14568 } 14569 14570 if (Invalid) { 14571 MoveAssignOperator->setInvalidDecl(); 14572 return; 14573 } 14574 14575 StmtResult Body; 14576 { 14577 CompoundScopeRAII CompoundScope(*this); 14578 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14579 /*isStmtExpr=*/false); 14580 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14581 } 14582 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 14583 MoveAssignOperator->markUsed(Context); 14584 14585 if (ASTMutationListener *L = getASTMutationListener()) { 14586 L->CompletedImplicitDefinition(MoveAssignOperator); 14587 } 14588 } 14589 14590 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 14591 CXXRecordDecl *ClassDecl) { 14592 // C++ [class.copy]p4: 14593 // If the class definition does not explicitly declare a copy 14594 // constructor, one is declared implicitly. 14595 assert(ClassDecl->needsImplicitCopyConstructor()); 14596 14597 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 14598 if (DSM.isAlreadyBeingDeclared()) 14599 return nullptr; 14600 14601 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14602 QualType ArgType = ClassType; 14603 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 14604 if (Const) 14605 ArgType = ArgType.withConst(); 14606 14607 LangAS AS = getDefaultCXXMethodAddrSpace(); 14608 if (AS != LangAS::Default) 14609 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14610 14611 ArgType = Context.getLValueReferenceType(ArgType); 14612 14613 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14614 CXXCopyConstructor, 14615 Const); 14616 14617 DeclarationName Name 14618 = Context.DeclarationNames.getCXXConstructorName( 14619 Context.getCanonicalType(ClassType)); 14620 SourceLocation ClassLoc = ClassDecl->getLocation(); 14621 DeclarationNameInfo NameInfo(Name, ClassLoc); 14622 14623 // An implicitly-declared copy constructor is an inline public 14624 // member of its class. 14625 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 14626 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14627 ExplicitSpecifier(), 14628 /*isInline=*/true, 14629 /*isImplicitlyDeclared=*/true, 14630 Constexpr ? ConstexprSpecKind::Constexpr 14631 : ConstexprSpecKind::Unspecified); 14632 CopyConstructor->setAccess(AS_public); 14633 CopyConstructor->setDefaulted(); 14634 14635 if (getLangOpts().CUDA) { 14636 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 14637 CopyConstructor, 14638 /* ConstRHS */ Const, 14639 /* Diagnose */ false); 14640 } 14641 14642 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 14643 14644 // Add the parameter to the constructor. 14645 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 14646 ClassLoc, ClassLoc, 14647 /*IdentifierInfo=*/nullptr, 14648 ArgType, /*TInfo=*/nullptr, 14649 SC_None, nullptr); 14650 CopyConstructor->setParams(FromParam); 14651 14652 CopyConstructor->setTrivial( 14653 ClassDecl->needsOverloadResolutionForCopyConstructor() 14654 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 14655 : ClassDecl->hasTrivialCopyConstructor()); 14656 14657 CopyConstructor->setTrivialForCall( 14658 ClassDecl->hasAttr<TrivialABIAttr>() || 14659 (ClassDecl->needsOverloadResolutionForCopyConstructor() 14660 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 14661 TAH_ConsiderTrivialABI) 14662 : ClassDecl->hasTrivialCopyConstructorForCall())); 14663 14664 // Note that we have declared this constructor. 14665 ++getASTContext().NumImplicitCopyConstructorsDeclared; 14666 14667 Scope *S = getScopeForContext(ClassDecl); 14668 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 14669 14670 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 14671 ClassDecl->setImplicitCopyConstructorIsDeleted(); 14672 SetDeclDeleted(CopyConstructor, ClassLoc); 14673 } 14674 14675 if (S) 14676 PushOnScopeChains(CopyConstructor, S, false); 14677 ClassDecl->addDecl(CopyConstructor); 14678 14679 return CopyConstructor; 14680 } 14681 14682 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 14683 CXXConstructorDecl *CopyConstructor) { 14684 assert((CopyConstructor->isDefaulted() && 14685 CopyConstructor->isCopyConstructor() && 14686 !CopyConstructor->doesThisDeclarationHaveABody() && 14687 !CopyConstructor->isDeleted()) && 14688 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 14689 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 14690 return; 14691 14692 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 14693 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 14694 14695 SynthesizedFunctionScope Scope(*this, CopyConstructor); 14696 14697 // The exception specification is needed because we are defining the 14698 // function. 14699 ResolveExceptionSpec(CurrentLocation, 14700 CopyConstructor->getType()->castAs<FunctionProtoType>()); 14701 MarkVTableUsed(CurrentLocation, ClassDecl); 14702 14703 // Add a context note for diagnostics produced after this point. 14704 Scope.addContextNote(CurrentLocation); 14705 14706 // C++11 [class.copy]p7: 14707 // The [definition of an implicitly declared copy constructor] is 14708 // deprecated if the class has a user-declared copy assignment operator 14709 // or a user-declared destructor. 14710 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 14711 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 14712 14713 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 14714 CopyConstructor->setInvalidDecl(); 14715 } else { 14716 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 14717 ? CopyConstructor->getEndLoc() 14718 : CopyConstructor->getLocation(); 14719 Sema::CompoundScopeRAII CompoundScope(*this); 14720 CopyConstructor->setBody( 14721 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 14722 CopyConstructor->markUsed(Context); 14723 } 14724 14725 if (ASTMutationListener *L = getASTMutationListener()) { 14726 L->CompletedImplicitDefinition(CopyConstructor); 14727 } 14728 } 14729 14730 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 14731 CXXRecordDecl *ClassDecl) { 14732 assert(ClassDecl->needsImplicitMoveConstructor()); 14733 14734 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 14735 if (DSM.isAlreadyBeingDeclared()) 14736 return nullptr; 14737 14738 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14739 14740 QualType ArgType = ClassType; 14741 LangAS AS = getDefaultCXXMethodAddrSpace(); 14742 if (AS != LangAS::Default) 14743 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 14744 ArgType = Context.getRValueReferenceType(ArgType); 14745 14746 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14747 CXXMoveConstructor, 14748 false); 14749 14750 DeclarationName Name 14751 = Context.DeclarationNames.getCXXConstructorName( 14752 Context.getCanonicalType(ClassType)); 14753 SourceLocation ClassLoc = ClassDecl->getLocation(); 14754 DeclarationNameInfo NameInfo(Name, ClassLoc); 14755 14756 // C++11 [class.copy]p11: 14757 // An implicitly-declared copy/move constructor is an inline public 14758 // member of its class. 14759 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 14760 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14761 ExplicitSpecifier(), 14762 /*isInline=*/true, 14763 /*isImplicitlyDeclared=*/true, 14764 Constexpr ? ConstexprSpecKind::Constexpr 14765 : ConstexprSpecKind::Unspecified); 14766 MoveConstructor->setAccess(AS_public); 14767 MoveConstructor->setDefaulted(); 14768 14769 if (getLangOpts().CUDA) { 14770 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 14771 MoveConstructor, 14772 /* ConstRHS */ false, 14773 /* Diagnose */ false); 14774 } 14775 14776 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 14777 14778 // Add the parameter to the constructor. 14779 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 14780 ClassLoc, ClassLoc, 14781 /*IdentifierInfo=*/nullptr, 14782 ArgType, /*TInfo=*/nullptr, 14783 SC_None, nullptr); 14784 MoveConstructor->setParams(FromParam); 14785 14786 MoveConstructor->setTrivial( 14787 ClassDecl->needsOverloadResolutionForMoveConstructor() 14788 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 14789 : ClassDecl->hasTrivialMoveConstructor()); 14790 14791 MoveConstructor->setTrivialForCall( 14792 ClassDecl->hasAttr<TrivialABIAttr>() || 14793 (ClassDecl->needsOverloadResolutionForMoveConstructor() 14794 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 14795 TAH_ConsiderTrivialABI) 14796 : ClassDecl->hasTrivialMoveConstructorForCall())); 14797 14798 // Note that we have declared this constructor. 14799 ++getASTContext().NumImplicitMoveConstructorsDeclared; 14800 14801 Scope *S = getScopeForContext(ClassDecl); 14802 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 14803 14804 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 14805 ClassDecl->setImplicitMoveConstructorIsDeleted(); 14806 SetDeclDeleted(MoveConstructor, ClassLoc); 14807 } 14808 14809 if (S) 14810 PushOnScopeChains(MoveConstructor, S, false); 14811 ClassDecl->addDecl(MoveConstructor); 14812 14813 return MoveConstructor; 14814 } 14815 14816 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 14817 CXXConstructorDecl *MoveConstructor) { 14818 assert((MoveConstructor->isDefaulted() && 14819 MoveConstructor->isMoveConstructor() && 14820 !MoveConstructor->doesThisDeclarationHaveABody() && 14821 !MoveConstructor->isDeleted()) && 14822 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 14823 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 14824 return; 14825 14826 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 14827 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 14828 14829 SynthesizedFunctionScope Scope(*this, MoveConstructor); 14830 14831 // The exception specification is needed because we are defining the 14832 // function. 14833 ResolveExceptionSpec(CurrentLocation, 14834 MoveConstructor->getType()->castAs<FunctionProtoType>()); 14835 MarkVTableUsed(CurrentLocation, ClassDecl); 14836 14837 // Add a context note for diagnostics produced after this point. 14838 Scope.addContextNote(CurrentLocation); 14839 14840 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 14841 MoveConstructor->setInvalidDecl(); 14842 } else { 14843 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 14844 ? MoveConstructor->getEndLoc() 14845 : MoveConstructor->getLocation(); 14846 Sema::CompoundScopeRAII CompoundScope(*this); 14847 MoveConstructor->setBody(ActOnCompoundStmt( 14848 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 14849 MoveConstructor->markUsed(Context); 14850 } 14851 14852 if (ASTMutationListener *L = getASTMutationListener()) { 14853 L->CompletedImplicitDefinition(MoveConstructor); 14854 } 14855 } 14856 14857 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 14858 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 14859 } 14860 14861 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 14862 SourceLocation CurrentLocation, 14863 CXXConversionDecl *Conv) { 14864 SynthesizedFunctionScope Scope(*this, Conv); 14865 assert(!Conv->getReturnType()->isUndeducedType()); 14866 14867 QualType ConvRT = Conv->getType()->getAs<FunctionType>()->getReturnType(); 14868 CallingConv CC = 14869 ConvRT->getPointeeType()->getAs<FunctionType>()->getCallConv(); 14870 14871 CXXRecordDecl *Lambda = Conv->getParent(); 14872 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 14873 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC); 14874 14875 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 14876 CallOp = InstantiateFunctionDeclaration( 14877 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14878 if (!CallOp) 14879 return; 14880 14881 Invoker = InstantiateFunctionDeclaration( 14882 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14883 if (!Invoker) 14884 return; 14885 } 14886 14887 if (CallOp->isInvalidDecl()) 14888 return; 14889 14890 // Mark the call operator referenced (and add to pending instantiations 14891 // if necessary). 14892 // For both the conversion and static-invoker template specializations 14893 // we construct their body's in this function, so no need to add them 14894 // to the PendingInstantiations. 14895 MarkFunctionReferenced(CurrentLocation, CallOp); 14896 14897 // Fill in the __invoke function with a dummy implementation. IR generation 14898 // will fill in the actual details. Update its type in case it contained 14899 // an 'auto'. 14900 Invoker->markUsed(Context); 14901 Invoker->setReferenced(); 14902 Invoker->setType(Conv->getReturnType()->getPointeeType()); 14903 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 14904 14905 // Construct the body of the conversion function { return __invoke; }. 14906 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 14907 VK_LValue, Conv->getLocation()); 14908 assert(FunctionRef && "Can't refer to __invoke function?"); 14909 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 14910 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 14911 Conv->getLocation())); 14912 Conv->markUsed(Context); 14913 Conv->setReferenced(); 14914 14915 if (ASTMutationListener *L = getASTMutationListener()) { 14916 L->CompletedImplicitDefinition(Conv); 14917 L->CompletedImplicitDefinition(Invoker); 14918 } 14919 } 14920 14921 14922 14923 void Sema::DefineImplicitLambdaToBlockPointerConversion( 14924 SourceLocation CurrentLocation, 14925 CXXConversionDecl *Conv) 14926 { 14927 assert(!Conv->getParent()->isGenericLambda()); 14928 14929 SynthesizedFunctionScope Scope(*this, Conv); 14930 14931 // Copy-initialize the lambda object as needed to capture it. 14932 Expr *This = ActOnCXXThis(CurrentLocation).get(); 14933 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 14934 14935 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 14936 Conv->getLocation(), 14937 Conv, DerefThis); 14938 14939 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 14940 // behavior. Note that only the general conversion function does this 14941 // (since it's unusable otherwise); in the case where we inline the 14942 // block literal, it has block literal lifetime semantics. 14943 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 14944 BuildBlock = ImplicitCastExpr::Create( 14945 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject, 14946 BuildBlock.get(), nullptr, VK_RValue, FPOptionsOverride()); 14947 14948 if (BuildBlock.isInvalid()) { 14949 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14950 Conv->setInvalidDecl(); 14951 return; 14952 } 14953 14954 // Create the return statement that returns the block from the conversion 14955 // function. 14956 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 14957 if (Return.isInvalid()) { 14958 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14959 Conv->setInvalidDecl(); 14960 return; 14961 } 14962 14963 // Set the body of the conversion function. 14964 Stmt *ReturnS = Return.get(); 14965 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 14966 Conv->getLocation())); 14967 Conv->markUsed(Context); 14968 14969 // We're done; notify the mutation listener, if any. 14970 if (ASTMutationListener *L = getASTMutationListener()) { 14971 L->CompletedImplicitDefinition(Conv); 14972 } 14973 } 14974 14975 /// Determine whether the given list arguments contains exactly one 14976 /// "real" (non-default) argument. 14977 static bool hasOneRealArgument(MultiExprArg Args) { 14978 switch (Args.size()) { 14979 case 0: 14980 return false; 14981 14982 default: 14983 if (!Args[1]->isDefaultArgument()) 14984 return false; 14985 14986 LLVM_FALLTHROUGH; 14987 case 1: 14988 return !Args[0]->isDefaultArgument(); 14989 } 14990 14991 return false; 14992 } 14993 14994 ExprResult 14995 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14996 NamedDecl *FoundDecl, 14997 CXXConstructorDecl *Constructor, 14998 MultiExprArg ExprArgs, 14999 bool HadMultipleCandidates, 15000 bool IsListInitialization, 15001 bool IsStdInitListInitialization, 15002 bool RequiresZeroInit, 15003 unsigned ConstructKind, 15004 SourceRange ParenRange) { 15005 bool Elidable = false; 15006 15007 // C++0x [class.copy]p34: 15008 // When certain criteria are met, an implementation is allowed to 15009 // omit the copy/move construction of a class object, even if the 15010 // copy/move constructor and/or destructor for the object have 15011 // side effects. [...] 15012 // - when a temporary class object that has not been bound to a 15013 // reference (12.2) would be copied/moved to a class object 15014 // with the same cv-unqualified type, the copy/move operation 15015 // can be omitted by constructing the temporary object 15016 // directly into the target of the omitted copy/move 15017 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 15018 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 15019 Expr *SubExpr = ExprArgs[0]; 15020 Elidable = SubExpr->isTemporaryObject( 15021 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 15022 } 15023 15024 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 15025 FoundDecl, Constructor, 15026 Elidable, ExprArgs, HadMultipleCandidates, 15027 IsListInitialization, 15028 IsStdInitListInitialization, RequiresZeroInit, 15029 ConstructKind, ParenRange); 15030 } 15031 15032 ExprResult 15033 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15034 NamedDecl *FoundDecl, 15035 CXXConstructorDecl *Constructor, 15036 bool Elidable, 15037 MultiExprArg ExprArgs, 15038 bool HadMultipleCandidates, 15039 bool IsListInitialization, 15040 bool IsStdInitListInitialization, 15041 bool RequiresZeroInit, 15042 unsigned ConstructKind, 15043 SourceRange ParenRange) { 15044 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 15045 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 15046 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 15047 return ExprError(); 15048 } 15049 15050 return BuildCXXConstructExpr( 15051 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 15052 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 15053 RequiresZeroInit, ConstructKind, ParenRange); 15054 } 15055 15056 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 15057 /// including handling of its default argument expressions. 15058 ExprResult 15059 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15060 CXXConstructorDecl *Constructor, 15061 bool Elidable, 15062 MultiExprArg ExprArgs, 15063 bool HadMultipleCandidates, 15064 bool IsListInitialization, 15065 bool IsStdInitListInitialization, 15066 bool RequiresZeroInit, 15067 unsigned ConstructKind, 15068 SourceRange ParenRange) { 15069 assert(declaresSameEntity( 15070 Constructor->getParent(), 15071 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 15072 "given constructor for wrong type"); 15073 MarkFunctionReferenced(ConstructLoc, Constructor); 15074 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 15075 return ExprError(); 15076 if (getLangOpts().SYCLIsDevice && 15077 !checkSYCLDeviceFunction(ConstructLoc, Constructor)) 15078 return ExprError(); 15079 15080 return CheckForImmediateInvocation( 15081 CXXConstructExpr::Create( 15082 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 15083 HadMultipleCandidates, IsListInitialization, 15084 IsStdInitListInitialization, RequiresZeroInit, 15085 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 15086 ParenRange), 15087 Constructor); 15088 } 15089 15090 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 15091 assert(Field->hasInClassInitializer()); 15092 15093 // If we already have the in-class initializer nothing needs to be done. 15094 if (Field->getInClassInitializer()) 15095 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15096 15097 // If we might have already tried and failed to instantiate, don't try again. 15098 if (Field->isInvalidDecl()) 15099 return ExprError(); 15100 15101 // Maybe we haven't instantiated the in-class initializer. Go check the 15102 // pattern FieldDecl to see if it has one. 15103 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 15104 15105 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 15106 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 15107 DeclContext::lookup_result Lookup = 15108 ClassPattern->lookup(Field->getDeclName()); 15109 15110 FieldDecl *Pattern = nullptr; 15111 for (auto L : Lookup) { 15112 if (isa<FieldDecl>(L)) { 15113 Pattern = cast<FieldDecl>(L); 15114 break; 15115 } 15116 } 15117 assert(Pattern && "We must have set the Pattern!"); 15118 15119 if (!Pattern->hasInClassInitializer() || 15120 InstantiateInClassInitializer(Loc, Field, Pattern, 15121 getTemplateInstantiationArgs(Field))) { 15122 // Don't diagnose this again. 15123 Field->setInvalidDecl(); 15124 return ExprError(); 15125 } 15126 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15127 } 15128 15129 // DR1351: 15130 // If the brace-or-equal-initializer of a non-static data member 15131 // invokes a defaulted default constructor of its class or of an 15132 // enclosing class in a potentially evaluated subexpression, the 15133 // program is ill-formed. 15134 // 15135 // This resolution is unworkable: the exception specification of the 15136 // default constructor can be needed in an unevaluated context, in 15137 // particular, in the operand of a noexcept-expression, and we can be 15138 // unable to compute an exception specification for an enclosed class. 15139 // 15140 // Any attempt to resolve the exception specification of a defaulted default 15141 // constructor before the initializer is lexically complete will ultimately 15142 // come here at which point we can diagnose it. 15143 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 15144 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed) 15145 << OutermostClass << Field; 15146 Diag(Field->getEndLoc(), 15147 diag::note_default_member_initializer_not_yet_parsed); 15148 // Recover by marking the field invalid, unless we're in a SFINAE context. 15149 if (!isSFINAEContext()) 15150 Field->setInvalidDecl(); 15151 return ExprError(); 15152 } 15153 15154 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 15155 if (VD->isInvalidDecl()) return; 15156 // If initializing the variable failed, don't also diagnose problems with 15157 // the desctructor, they're likely related. 15158 if (VD->getInit() && VD->getInit()->containsErrors()) 15159 return; 15160 15161 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 15162 if (ClassDecl->isInvalidDecl()) return; 15163 if (ClassDecl->hasIrrelevantDestructor()) return; 15164 if (ClassDecl->isDependentContext()) return; 15165 15166 if (VD->isNoDestroy(getASTContext())) 15167 return; 15168 15169 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15170 15171 // If this is an array, we'll require the destructor during initialization, so 15172 // we can skip over this. We still want to emit exit-time destructor warnings 15173 // though. 15174 if (!VD->getType()->isArrayType()) { 15175 MarkFunctionReferenced(VD->getLocation(), Destructor); 15176 CheckDestructorAccess(VD->getLocation(), Destructor, 15177 PDiag(diag::err_access_dtor_var) 15178 << VD->getDeclName() << VD->getType()); 15179 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 15180 } 15181 15182 if (Destructor->isTrivial()) return; 15183 15184 // If the destructor is constexpr, check whether the variable has constant 15185 // destruction now. 15186 if (Destructor->isConstexpr()) { 15187 bool HasConstantInit = false; 15188 if (VD->getInit() && !VD->getInit()->isValueDependent()) 15189 HasConstantInit = VD->evaluateValue(); 15190 SmallVector<PartialDiagnosticAt, 8> Notes; 15191 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && 15192 HasConstantInit) { 15193 Diag(VD->getLocation(), 15194 diag::err_constexpr_var_requires_const_destruction) << VD; 15195 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 15196 Diag(Notes[I].first, Notes[I].second); 15197 } 15198 } 15199 15200 if (!VD->hasGlobalStorage()) return; 15201 15202 // Emit warning for non-trivial dtor in global scope (a real global, 15203 // class-static, function-static). 15204 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 15205 15206 // TODO: this should be re-enabled for static locals by !CXAAtExit 15207 if (!VD->isStaticLocal()) 15208 Diag(VD->getLocation(), diag::warn_global_destructor); 15209 } 15210 15211 /// Given a constructor and the set of arguments provided for the 15212 /// constructor, convert the arguments and add any required default arguments 15213 /// to form a proper call to this constructor. 15214 /// 15215 /// \returns true if an error occurred, false otherwise. 15216 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 15217 QualType DeclInitType, MultiExprArg ArgsPtr, 15218 SourceLocation Loc, 15219 SmallVectorImpl<Expr *> &ConvertedArgs, 15220 bool AllowExplicit, 15221 bool IsListInitialization) { 15222 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 15223 unsigned NumArgs = ArgsPtr.size(); 15224 Expr **Args = ArgsPtr.data(); 15225 15226 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); 15227 unsigned NumParams = Proto->getNumParams(); 15228 15229 // If too few arguments are available, we'll fill in the rest with defaults. 15230 if (NumArgs < NumParams) 15231 ConvertedArgs.reserve(NumParams); 15232 else 15233 ConvertedArgs.reserve(NumArgs); 15234 15235 VariadicCallType CallType = 15236 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 15237 SmallVector<Expr *, 8> AllArgs; 15238 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 15239 Proto, 0, 15240 llvm::makeArrayRef(Args, NumArgs), 15241 AllArgs, 15242 CallType, AllowExplicit, 15243 IsListInitialization); 15244 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 15245 15246 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 15247 15248 CheckConstructorCall(Constructor, DeclInitType, 15249 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 15250 Proto, Loc); 15251 15252 return Invalid; 15253 } 15254 15255 static inline bool 15256 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 15257 const FunctionDecl *FnDecl) { 15258 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 15259 if (isa<NamespaceDecl>(DC)) { 15260 return SemaRef.Diag(FnDecl->getLocation(), 15261 diag::err_operator_new_delete_declared_in_namespace) 15262 << FnDecl->getDeclName(); 15263 } 15264 15265 if (isa<TranslationUnitDecl>(DC) && 15266 FnDecl->getStorageClass() == SC_Static) { 15267 return SemaRef.Diag(FnDecl->getLocation(), 15268 diag::err_operator_new_delete_declared_static) 15269 << FnDecl->getDeclName(); 15270 } 15271 15272 return false; 15273 } 15274 15275 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, 15276 const PointerType *PtrTy) { 15277 auto &Ctx = SemaRef.Context; 15278 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers(); 15279 PtrQuals.removeAddressSpace(); 15280 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType( 15281 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals))); 15282 } 15283 15284 static inline bool 15285 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 15286 CanQualType ExpectedResultType, 15287 CanQualType ExpectedFirstParamType, 15288 unsigned DependentParamTypeDiag, 15289 unsigned InvalidParamTypeDiag) { 15290 QualType ResultType = 15291 FnDecl->getType()->castAs<FunctionType>()->getReturnType(); 15292 15293 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15294 // The operator is valid on any address space for OpenCL. 15295 // Drop address space from actual and expected result types. 15296 if (const auto *PtrTy = ResultType->getAs<PointerType>()) 15297 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15298 15299 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>()) 15300 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15301 } 15302 15303 // Check that the result type is what we expect. 15304 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) { 15305 // Reject even if the type is dependent; an operator delete function is 15306 // required to have a non-dependent result type. 15307 return SemaRef.Diag( 15308 FnDecl->getLocation(), 15309 ResultType->isDependentType() 15310 ? diag::err_operator_new_delete_dependent_result_type 15311 : diag::err_operator_new_delete_invalid_result_type) 15312 << FnDecl->getDeclName() << ExpectedResultType; 15313 } 15314 15315 // A function template must have at least 2 parameters. 15316 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 15317 return SemaRef.Diag(FnDecl->getLocation(), 15318 diag::err_operator_new_delete_template_too_few_parameters) 15319 << FnDecl->getDeclName(); 15320 15321 // The function decl must have at least 1 parameter. 15322 if (FnDecl->getNumParams() == 0) 15323 return SemaRef.Diag(FnDecl->getLocation(), 15324 diag::err_operator_new_delete_too_few_parameters) 15325 << FnDecl->getDeclName(); 15326 15327 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 15328 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15329 // The operator is valid on any address space for OpenCL. 15330 // Drop address space from actual and expected first parameter types. 15331 if (const auto *PtrTy = 15332 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) 15333 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15334 15335 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>()) 15336 ExpectedFirstParamType = 15337 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15338 } 15339 15340 // Check that the first parameter type is what we expect. 15341 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 15342 ExpectedFirstParamType) { 15343 // The first parameter type is not allowed to be dependent. As a tentative 15344 // DR resolution, we allow a dependent parameter type if it is the right 15345 // type anyway, to allow destroying operator delete in class templates. 15346 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType() 15347 ? DependentParamTypeDiag 15348 : InvalidParamTypeDiag) 15349 << FnDecl->getDeclName() << ExpectedFirstParamType; 15350 } 15351 15352 return false; 15353 } 15354 15355 static bool 15356 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 15357 // C++ [basic.stc.dynamic.allocation]p1: 15358 // A program is ill-formed if an allocation function is declared in a 15359 // namespace scope other than global scope or declared static in global 15360 // scope. 15361 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15362 return true; 15363 15364 CanQualType SizeTy = 15365 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 15366 15367 // C++ [basic.stc.dynamic.allocation]p1: 15368 // The return type shall be void*. The first parameter shall have type 15369 // std::size_t. 15370 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 15371 SizeTy, 15372 diag::err_operator_new_dependent_param_type, 15373 diag::err_operator_new_param_type)) 15374 return true; 15375 15376 // C++ [basic.stc.dynamic.allocation]p1: 15377 // The first parameter shall not have an associated default argument. 15378 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 15379 return SemaRef.Diag(FnDecl->getLocation(), 15380 diag::err_operator_new_default_arg) 15381 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 15382 15383 return false; 15384 } 15385 15386 static bool 15387 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 15388 // C++ [basic.stc.dynamic.deallocation]p1: 15389 // A program is ill-formed if deallocation functions are declared in a 15390 // namespace scope other than global scope or declared static in global 15391 // scope. 15392 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15393 return true; 15394 15395 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 15396 15397 // C++ P0722: 15398 // Within a class C, the first parameter of a destroying operator delete 15399 // shall be of type C *. The first parameter of any other deallocation 15400 // function shall be of type void *. 15401 CanQualType ExpectedFirstParamType = 15402 MD && MD->isDestroyingOperatorDelete() 15403 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 15404 SemaRef.Context.getRecordType(MD->getParent()))) 15405 : SemaRef.Context.VoidPtrTy; 15406 15407 // C++ [basic.stc.dynamic.deallocation]p2: 15408 // Each deallocation function shall return void 15409 if (CheckOperatorNewDeleteTypes( 15410 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 15411 diag::err_operator_delete_dependent_param_type, 15412 diag::err_operator_delete_param_type)) 15413 return true; 15414 15415 // C++ P0722: 15416 // A destroying operator delete shall be a usual deallocation function. 15417 if (MD && !MD->getParent()->isDependentContext() && 15418 MD->isDestroyingOperatorDelete() && 15419 !SemaRef.isUsualDeallocationFunction(MD)) { 15420 SemaRef.Diag(MD->getLocation(), 15421 diag::err_destroying_operator_delete_not_usual); 15422 return true; 15423 } 15424 15425 return false; 15426 } 15427 15428 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 15429 /// of this overloaded operator is well-formed. If so, returns false; 15430 /// otherwise, emits appropriate diagnostics and returns true. 15431 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 15432 assert(FnDecl && FnDecl->isOverloadedOperator() && 15433 "Expected an overloaded operator declaration"); 15434 15435 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 15436 15437 // C++ [over.oper]p5: 15438 // The allocation and deallocation functions, operator new, 15439 // operator new[], operator delete and operator delete[], are 15440 // described completely in 3.7.3. The attributes and restrictions 15441 // found in the rest of this subclause do not apply to them unless 15442 // explicitly stated in 3.7.3. 15443 if (Op == OO_Delete || Op == OO_Array_Delete) 15444 return CheckOperatorDeleteDeclaration(*this, FnDecl); 15445 15446 if (Op == OO_New || Op == OO_Array_New) 15447 return CheckOperatorNewDeclaration(*this, FnDecl); 15448 15449 // C++ [over.oper]p6: 15450 // An operator function shall either be a non-static member 15451 // function or be a non-member function and have at least one 15452 // parameter whose type is a class, a reference to a class, an 15453 // enumeration, or a reference to an enumeration. 15454 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 15455 if (MethodDecl->isStatic()) 15456 return Diag(FnDecl->getLocation(), 15457 diag::err_operator_overload_static) << FnDecl->getDeclName(); 15458 } else { 15459 bool ClassOrEnumParam = false; 15460 for (auto Param : FnDecl->parameters()) { 15461 QualType ParamType = Param->getType().getNonReferenceType(); 15462 if (ParamType->isDependentType() || ParamType->isRecordType() || 15463 ParamType->isEnumeralType()) { 15464 ClassOrEnumParam = true; 15465 break; 15466 } 15467 } 15468 15469 if (!ClassOrEnumParam) 15470 return Diag(FnDecl->getLocation(), 15471 diag::err_operator_overload_needs_class_or_enum) 15472 << FnDecl->getDeclName(); 15473 } 15474 15475 // C++ [over.oper]p8: 15476 // An operator function cannot have default arguments (8.3.6), 15477 // except where explicitly stated below. 15478 // 15479 // Only the function-call operator allows default arguments 15480 // (C++ [over.call]p1). 15481 if (Op != OO_Call) { 15482 for (auto Param : FnDecl->parameters()) { 15483 if (Param->hasDefaultArg()) 15484 return Diag(Param->getLocation(), 15485 diag::err_operator_overload_default_arg) 15486 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 15487 } 15488 } 15489 15490 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 15491 { false, false, false } 15492 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 15493 , { Unary, Binary, MemberOnly } 15494 #include "clang/Basic/OperatorKinds.def" 15495 }; 15496 15497 bool CanBeUnaryOperator = OperatorUses[Op][0]; 15498 bool CanBeBinaryOperator = OperatorUses[Op][1]; 15499 bool MustBeMemberOperator = OperatorUses[Op][2]; 15500 15501 // C++ [over.oper]p8: 15502 // [...] Operator functions cannot have more or fewer parameters 15503 // than the number required for the corresponding operator, as 15504 // described in the rest of this subclause. 15505 unsigned NumParams = FnDecl->getNumParams() 15506 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 15507 if (Op != OO_Call && 15508 ((NumParams == 1 && !CanBeUnaryOperator) || 15509 (NumParams == 2 && !CanBeBinaryOperator) || 15510 (NumParams < 1) || (NumParams > 2))) { 15511 // We have the wrong number of parameters. 15512 unsigned ErrorKind; 15513 if (CanBeUnaryOperator && CanBeBinaryOperator) { 15514 ErrorKind = 2; // 2 -> unary or binary. 15515 } else if (CanBeUnaryOperator) { 15516 ErrorKind = 0; // 0 -> unary 15517 } else { 15518 assert(CanBeBinaryOperator && 15519 "All non-call overloaded operators are unary or binary!"); 15520 ErrorKind = 1; // 1 -> binary 15521 } 15522 15523 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 15524 << FnDecl->getDeclName() << NumParams << ErrorKind; 15525 } 15526 15527 // Overloaded operators other than operator() cannot be variadic. 15528 if (Op != OO_Call && 15529 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { 15530 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 15531 << FnDecl->getDeclName(); 15532 } 15533 15534 // Some operators must be non-static member functions. 15535 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 15536 return Diag(FnDecl->getLocation(), 15537 diag::err_operator_overload_must_be_member) 15538 << FnDecl->getDeclName(); 15539 } 15540 15541 // C++ [over.inc]p1: 15542 // The user-defined function called operator++ implements the 15543 // prefix and postfix ++ operator. If this function is a member 15544 // function with no parameters, or a non-member function with one 15545 // parameter of class or enumeration type, it defines the prefix 15546 // increment operator ++ for objects of that type. If the function 15547 // is a member function with one parameter (which shall be of type 15548 // int) or a non-member function with two parameters (the second 15549 // of which shall be of type int), it defines the postfix 15550 // increment operator ++ for objects of that type. 15551 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 15552 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 15553 QualType ParamType = LastParam->getType(); 15554 15555 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 15556 !ParamType->isDependentType()) 15557 return Diag(LastParam->getLocation(), 15558 diag::err_operator_overload_post_incdec_must_be_int) 15559 << LastParam->getType() << (Op == OO_MinusMinus); 15560 } 15561 15562 return false; 15563 } 15564 15565 static bool 15566 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 15567 FunctionTemplateDecl *TpDecl) { 15568 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 15569 15570 // Must have one or two template parameters. 15571 if (TemplateParams->size() == 1) { 15572 NonTypeTemplateParmDecl *PmDecl = 15573 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 15574 15575 // The template parameter must be a char parameter pack. 15576 if (PmDecl && PmDecl->isTemplateParameterPack() && 15577 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 15578 return false; 15579 15580 // C++20 [over.literal]p5: 15581 // A string literal operator template is a literal operator template 15582 // whose template-parameter-list comprises a single non-type 15583 // template-parameter of class type. 15584 // 15585 // As a DR resolution, we also allow placeholders for deduced class 15586 // template specializations. 15587 if (SemaRef.getLangOpts().CPlusPlus20 && 15588 !PmDecl->isTemplateParameterPack() && 15589 (PmDecl->getType()->isRecordType() || 15590 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>())) 15591 return false; 15592 } else if (TemplateParams->size() == 2) { 15593 TemplateTypeParmDecl *PmType = 15594 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 15595 NonTypeTemplateParmDecl *PmArgs = 15596 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 15597 15598 // The second template parameter must be a parameter pack with the 15599 // first template parameter as its type. 15600 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 15601 PmArgs->isTemplateParameterPack()) { 15602 const TemplateTypeParmType *TArgs = 15603 PmArgs->getType()->getAs<TemplateTypeParmType>(); 15604 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 15605 TArgs->getIndex() == PmType->getIndex()) { 15606 if (!SemaRef.inTemplateInstantiation()) 15607 SemaRef.Diag(TpDecl->getLocation(), 15608 diag::ext_string_literal_operator_template); 15609 return false; 15610 } 15611 } 15612 } 15613 15614 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 15615 diag::err_literal_operator_template) 15616 << TpDecl->getTemplateParameters()->getSourceRange(); 15617 return true; 15618 } 15619 15620 /// CheckLiteralOperatorDeclaration - Check whether the declaration 15621 /// of this literal operator function is well-formed. If so, returns 15622 /// false; otherwise, emits appropriate diagnostics and returns true. 15623 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 15624 if (isa<CXXMethodDecl>(FnDecl)) { 15625 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 15626 << FnDecl->getDeclName(); 15627 return true; 15628 } 15629 15630 if (FnDecl->isExternC()) { 15631 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 15632 if (const LinkageSpecDecl *LSD = 15633 FnDecl->getDeclContext()->getExternCContext()) 15634 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 15635 return true; 15636 } 15637 15638 // This might be the definition of a literal operator template. 15639 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 15640 15641 // This might be a specialization of a literal operator template. 15642 if (!TpDecl) 15643 TpDecl = FnDecl->getPrimaryTemplate(); 15644 15645 // template <char...> type operator "" name() and 15646 // template <class T, T...> type operator "" name() are the only valid 15647 // template signatures, and the only valid signatures with no parameters. 15648 // 15649 // C++20 also allows template <SomeClass T> type operator "" name(). 15650 if (TpDecl) { 15651 if (FnDecl->param_size() != 0) { 15652 Diag(FnDecl->getLocation(), 15653 diag::err_literal_operator_template_with_params); 15654 return true; 15655 } 15656 15657 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 15658 return true; 15659 15660 } else if (FnDecl->param_size() == 1) { 15661 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 15662 15663 QualType ParamType = Param->getType().getUnqualifiedType(); 15664 15665 // Only unsigned long long int, long double, any character type, and const 15666 // char * are allowed as the only parameters. 15667 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 15668 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 15669 Context.hasSameType(ParamType, Context.CharTy) || 15670 Context.hasSameType(ParamType, Context.WideCharTy) || 15671 Context.hasSameType(ParamType, Context.Char8Ty) || 15672 Context.hasSameType(ParamType, Context.Char16Ty) || 15673 Context.hasSameType(ParamType, Context.Char32Ty)) { 15674 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 15675 QualType InnerType = Ptr->getPointeeType(); 15676 15677 // Pointer parameter must be a const char *. 15678 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 15679 Context.CharTy) && 15680 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 15681 Diag(Param->getSourceRange().getBegin(), 15682 diag::err_literal_operator_param) 15683 << ParamType << "'const char *'" << Param->getSourceRange(); 15684 return true; 15685 } 15686 15687 } else if (ParamType->isRealFloatingType()) { 15688 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15689 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 15690 return true; 15691 15692 } else if (ParamType->isIntegerType()) { 15693 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15694 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 15695 return true; 15696 15697 } else { 15698 Diag(Param->getSourceRange().getBegin(), 15699 diag::err_literal_operator_invalid_param) 15700 << ParamType << Param->getSourceRange(); 15701 return true; 15702 } 15703 15704 } else if (FnDecl->param_size() == 2) { 15705 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 15706 15707 // First, verify that the first parameter is correct. 15708 15709 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 15710 15711 // Two parameter function must have a pointer to const as a 15712 // first parameter; let's strip those qualifiers. 15713 const PointerType *PT = FirstParamType->getAs<PointerType>(); 15714 15715 if (!PT) { 15716 Diag((*Param)->getSourceRange().getBegin(), 15717 diag::err_literal_operator_param) 15718 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15719 return true; 15720 } 15721 15722 QualType PointeeType = PT->getPointeeType(); 15723 // First parameter must be const 15724 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 15725 Diag((*Param)->getSourceRange().getBegin(), 15726 diag::err_literal_operator_param) 15727 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15728 return true; 15729 } 15730 15731 QualType InnerType = PointeeType.getUnqualifiedType(); 15732 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 15733 // const char32_t* are allowed as the first parameter to a two-parameter 15734 // function 15735 if (!(Context.hasSameType(InnerType, Context.CharTy) || 15736 Context.hasSameType(InnerType, Context.WideCharTy) || 15737 Context.hasSameType(InnerType, Context.Char8Ty) || 15738 Context.hasSameType(InnerType, Context.Char16Ty) || 15739 Context.hasSameType(InnerType, Context.Char32Ty))) { 15740 Diag((*Param)->getSourceRange().getBegin(), 15741 diag::err_literal_operator_param) 15742 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15743 return true; 15744 } 15745 15746 // Move on to the second and final parameter. 15747 ++Param; 15748 15749 // The second parameter must be a std::size_t. 15750 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 15751 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 15752 Diag((*Param)->getSourceRange().getBegin(), 15753 diag::err_literal_operator_param) 15754 << SecondParamType << Context.getSizeType() 15755 << (*Param)->getSourceRange(); 15756 return true; 15757 } 15758 } else { 15759 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 15760 return true; 15761 } 15762 15763 // Parameters are good. 15764 15765 // A parameter-declaration-clause containing a default argument is not 15766 // equivalent to any of the permitted forms. 15767 for (auto Param : FnDecl->parameters()) { 15768 if (Param->hasDefaultArg()) { 15769 Diag(Param->getDefaultArgRange().getBegin(), 15770 diag::err_literal_operator_default_argument) 15771 << Param->getDefaultArgRange(); 15772 break; 15773 } 15774 } 15775 15776 StringRef LiteralName 15777 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 15778 if (LiteralName[0] != '_' && 15779 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 15780 // C++11 [usrlit.suffix]p1: 15781 // Literal suffix identifiers that do not start with an underscore 15782 // are reserved for future standardization. 15783 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 15784 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 15785 } 15786 15787 return false; 15788 } 15789 15790 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 15791 /// linkage specification, including the language and (if present) 15792 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 15793 /// language string literal. LBraceLoc, if valid, provides the location of 15794 /// the '{' brace. Otherwise, this linkage specification does not 15795 /// have any braces. 15796 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 15797 Expr *LangStr, 15798 SourceLocation LBraceLoc) { 15799 StringLiteral *Lit = cast<StringLiteral>(LangStr); 15800 if (!Lit->isAscii()) { 15801 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 15802 << LangStr->getSourceRange(); 15803 return nullptr; 15804 } 15805 15806 StringRef Lang = Lit->getString(); 15807 LinkageSpecDecl::LanguageIDs Language; 15808 if (Lang == "C") 15809 Language = LinkageSpecDecl::lang_c; 15810 else if (Lang == "C++") 15811 Language = LinkageSpecDecl::lang_cxx; 15812 else { 15813 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 15814 << LangStr->getSourceRange(); 15815 return nullptr; 15816 } 15817 15818 // FIXME: Add all the various semantics of linkage specifications 15819 15820 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 15821 LangStr->getExprLoc(), Language, 15822 LBraceLoc.isValid()); 15823 CurContext->addDecl(D); 15824 PushDeclContext(S, D); 15825 return D; 15826 } 15827 15828 /// ActOnFinishLinkageSpecification - Complete the definition of 15829 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 15830 /// valid, it's the position of the closing '}' brace in a linkage 15831 /// specification that uses braces. 15832 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 15833 Decl *LinkageSpec, 15834 SourceLocation RBraceLoc) { 15835 if (RBraceLoc.isValid()) { 15836 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 15837 LSDecl->setRBraceLoc(RBraceLoc); 15838 } 15839 PopDeclContext(); 15840 return LinkageSpec; 15841 } 15842 15843 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 15844 const ParsedAttributesView &AttrList, 15845 SourceLocation SemiLoc) { 15846 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 15847 // Attribute declarations appertain to empty declaration so we handle 15848 // them here. 15849 ProcessDeclAttributeList(S, ED, AttrList); 15850 15851 CurContext->addDecl(ED); 15852 return ED; 15853 } 15854 15855 /// Perform semantic analysis for the variable declaration that 15856 /// occurs within a C++ catch clause, returning the newly-created 15857 /// variable. 15858 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 15859 TypeSourceInfo *TInfo, 15860 SourceLocation StartLoc, 15861 SourceLocation Loc, 15862 IdentifierInfo *Name) { 15863 bool Invalid = false; 15864 QualType ExDeclType = TInfo->getType(); 15865 15866 // Arrays and functions decay. 15867 if (ExDeclType->isArrayType()) 15868 ExDeclType = Context.getArrayDecayedType(ExDeclType); 15869 else if (ExDeclType->isFunctionType()) 15870 ExDeclType = Context.getPointerType(ExDeclType); 15871 15872 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 15873 // The exception-declaration shall not denote a pointer or reference to an 15874 // incomplete type, other than [cv] void*. 15875 // N2844 forbids rvalue references. 15876 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 15877 Diag(Loc, diag::err_catch_rvalue_ref); 15878 Invalid = true; 15879 } 15880 15881 if (ExDeclType->isVariablyModifiedType()) { 15882 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 15883 Invalid = true; 15884 } 15885 15886 QualType BaseType = ExDeclType; 15887 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 15888 unsigned DK = diag::err_catch_incomplete; 15889 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 15890 BaseType = Ptr->getPointeeType(); 15891 Mode = 1; 15892 DK = diag::err_catch_incomplete_ptr; 15893 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 15894 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 15895 BaseType = Ref->getPointeeType(); 15896 Mode = 2; 15897 DK = diag::err_catch_incomplete_ref; 15898 } 15899 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 15900 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 15901 Invalid = true; 15902 15903 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) { 15904 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType; 15905 Invalid = true; 15906 } 15907 15908 if (!Invalid && !ExDeclType->isDependentType() && 15909 RequireNonAbstractType(Loc, ExDeclType, 15910 diag::err_abstract_type_in_decl, 15911 AbstractVariableType)) 15912 Invalid = true; 15913 15914 // Only the non-fragile NeXT runtime currently supports C++ catches 15915 // of ObjC types, and no runtime supports catching ObjC types by value. 15916 if (!Invalid && getLangOpts().ObjC) { 15917 QualType T = ExDeclType; 15918 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 15919 T = RT->getPointeeType(); 15920 15921 if (T->isObjCObjectType()) { 15922 Diag(Loc, diag::err_objc_object_catch); 15923 Invalid = true; 15924 } else if (T->isObjCObjectPointerType()) { 15925 // FIXME: should this be a test for macosx-fragile specifically? 15926 if (getLangOpts().ObjCRuntime.isFragile()) 15927 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 15928 } 15929 } 15930 15931 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 15932 ExDeclType, TInfo, SC_None); 15933 ExDecl->setExceptionVariable(true); 15934 15935 // In ARC, infer 'retaining' for variables of retainable type. 15936 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 15937 Invalid = true; 15938 15939 if (!Invalid && !ExDeclType->isDependentType()) { 15940 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 15941 // Insulate this from anything else we might currently be parsing. 15942 EnterExpressionEvaluationContext scope( 15943 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15944 15945 // C++ [except.handle]p16: 15946 // The object declared in an exception-declaration or, if the 15947 // exception-declaration does not specify a name, a temporary (12.2) is 15948 // copy-initialized (8.5) from the exception object. [...] 15949 // The object is destroyed when the handler exits, after the destruction 15950 // of any automatic objects initialized within the handler. 15951 // 15952 // We just pretend to initialize the object with itself, then make sure 15953 // it can be destroyed later. 15954 QualType initType = Context.getExceptionObjectType(ExDeclType); 15955 15956 InitializedEntity entity = 15957 InitializedEntity::InitializeVariable(ExDecl); 15958 InitializationKind initKind = 15959 InitializationKind::CreateCopy(Loc, SourceLocation()); 15960 15961 Expr *opaqueValue = 15962 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 15963 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 15964 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 15965 if (result.isInvalid()) 15966 Invalid = true; 15967 else { 15968 // If the constructor used was non-trivial, set this as the 15969 // "initializer". 15970 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 15971 if (!construct->getConstructor()->isTrivial()) { 15972 Expr *init = MaybeCreateExprWithCleanups(construct); 15973 ExDecl->setInit(init); 15974 } 15975 15976 // And make sure it's destructable. 15977 FinalizeVarWithDestructor(ExDecl, recordType); 15978 } 15979 } 15980 } 15981 15982 if (Invalid) 15983 ExDecl->setInvalidDecl(); 15984 15985 return ExDecl; 15986 } 15987 15988 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 15989 /// handler. 15990 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 15991 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15992 bool Invalid = D.isInvalidType(); 15993 15994 // Check for unexpanded parameter packs. 15995 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15996 UPPC_ExceptionType)) { 15997 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 15998 D.getIdentifierLoc()); 15999 Invalid = true; 16000 } 16001 16002 IdentifierInfo *II = D.getIdentifier(); 16003 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 16004 LookupOrdinaryName, 16005 ForVisibleRedeclaration)) { 16006 // The scope should be freshly made just for us. There is just no way 16007 // it contains any previous declaration, except for function parameters in 16008 // a function-try-block's catch statement. 16009 assert(!S->isDeclScope(PrevDecl)); 16010 if (isDeclInScope(PrevDecl, CurContext, S)) { 16011 Diag(D.getIdentifierLoc(), diag::err_redefinition) 16012 << D.getIdentifier(); 16013 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 16014 Invalid = true; 16015 } else if (PrevDecl->isTemplateParameter()) 16016 // Maybe we will complain about the shadowed template parameter. 16017 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16018 } 16019 16020 if (D.getCXXScopeSpec().isSet() && !Invalid) { 16021 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 16022 << D.getCXXScopeSpec().getRange(); 16023 Invalid = true; 16024 } 16025 16026 VarDecl *ExDecl = BuildExceptionDeclaration( 16027 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 16028 if (Invalid) 16029 ExDecl->setInvalidDecl(); 16030 16031 // Add the exception declaration into this scope. 16032 if (II) 16033 PushOnScopeChains(ExDecl, S); 16034 else 16035 CurContext->addDecl(ExDecl); 16036 16037 ProcessDeclAttributes(S, ExDecl, D); 16038 return ExDecl; 16039 } 16040 16041 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16042 Expr *AssertExpr, 16043 Expr *AssertMessageExpr, 16044 SourceLocation RParenLoc) { 16045 StringLiteral *AssertMessage = 16046 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 16047 16048 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 16049 return nullptr; 16050 16051 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 16052 AssertMessage, RParenLoc, false); 16053 } 16054 16055 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16056 Expr *AssertExpr, 16057 StringLiteral *AssertMessage, 16058 SourceLocation RParenLoc, 16059 bool Failed) { 16060 assert(AssertExpr != nullptr && "Expected non-null condition"); 16061 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 16062 !Failed) { 16063 // In a static_assert-declaration, the constant-expression shall be a 16064 // constant expression that can be contextually converted to bool. 16065 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 16066 if (Converted.isInvalid()) 16067 Failed = true; 16068 16069 ExprResult FullAssertExpr = 16070 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 16071 /*DiscardedValue*/ false, 16072 /*IsConstexpr*/ true); 16073 if (FullAssertExpr.isInvalid()) 16074 Failed = true; 16075 else 16076 AssertExpr = FullAssertExpr.get(); 16077 16078 llvm::APSInt Cond; 16079 if (!Failed && VerifyIntegerConstantExpression( 16080 AssertExpr, &Cond, 16081 diag::err_static_assert_expression_is_not_constant) 16082 .isInvalid()) 16083 Failed = true; 16084 16085 if (!Failed && !Cond) { 16086 SmallString<256> MsgBuffer; 16087 llvm::raw_svector_ostream Msg(MsgBuffer); 16088 if (AssertMessage) 16089 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 16090 16091 Expr *InnerCond = nullptr; 16092 std::string InnerCondDescription; 16093 std::tie(InnerCond, InnerCondDescription) = 16094 findFailedBooleanCondition(Converted.get()); 16095 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 16096 // Drill down into concept specialization expressions to see why they 16097 // weren't satisfied. 16098 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16099 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16100 ConstraintSatisfaction Satisfaction; 16101 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 16102 DiagnoseUnsatisfiedConstraint(Satisfaction); 16103 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 16104 && !isa<IntegerLiteral>(InnerCond)) { 16105 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 16106 << InnerCondDescription << !AssertMessage 16107 << Msg.str() << InnerCond->getSourceRange(); 16108 } else { 16109 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16110 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16111 } 16112 Failed = true; 16113 } 16114 } else { 16115 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 16116 /*DiscardedValue*/false, 16117 /*IsConstexpr*/true); 16118 if (FullAssertExpr.isInvalid()) 16119 Failed = true; 16120 else 16121 AssertExpr = FullAssertExpr.get(); 16122 } 16123 16124 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 16125 AssertExpr, AssertMessage, RParenLoc, 16126 Failed); 16127 16128 CurContext->addDecl(Decl); 16129 return Decl; 16130 } 16131 16132 /// Perform semantic analysis of the given friend type declaration. 16133 /// 16134 /// \returns A friend declaration that. 16135 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 16136 SourceLocation FriendLoc, 16137 TypeSourceInfo *TSInfo) { 16138 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 16139 16140 QualType T = TSInfo->getType(); 16141 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 16142 16143 // C++03 [class.friend]p2: 16144 // An elaborated-type-specifier shall be used in a friend declaration 16145 // for a class.* 16146 // 16147 // * The class-key of the elaborated-type-specifier is required. 16148 if (!CodeSynthesisContexts.empty()) { 16149 // Do not complain about the form of friend template types during any kind 16150 // of code synthesis. For template instantiation, we will have complained 16151 // when the template was defined. 16152 } else { 16153 if (!T->isElaboratedTypeSpecifier()) { 16154 // If we evaluated the type to a record type, suggest putting 16155 // a tag in front. 16156 if (const RecordType *RT = T->getAs<RecordType>()) { 16157 RecordDecl *RD = RT->getDecl(); 16158 16159 SmallString<16> InsertionText(" "); 16160 InsertionText += RD->getKindName(); 16161 16162 Diag(TypeRange.getBegin(), 16163 getLangOpts().CPlusPlus11 ? 16164 diag::warn_cxx98_compat_unelaborated_friend_type : 16165 diag::ext_unelaborated_friend_type) 16166 << (unsigned) RD->getTagKind() 16167 << T 16168 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 16169 InsertionText); 16170 } else { 16171 Diag(FriendLoc, 16172 getLangOpts().CPlusPlus11 ? 16173 diag::warn_cxx98_compat_nonclass_type_friend : 16174 diag::ext_nonclass_type_friend) 16175 << T 16176 << TypeRange; 16177 } 16178 } else if (T->getAs<EnumType>()) { 16179 Diag(FriendLoc, 16180 getLangOpts().CPlusPlus11 ? 16181 diag::warn_cxx98_compat_enum_friend : 16182 diag::ext_enum_friend) 16183 << T 16184 << TypeRange; 16185 } 16186 16187 // C++11 [class.friend]p3: 16188 // A friend declaration that does not declare a function shall have one 16189 // of the following forms: 16190 // friend elaborated-type-specifier ; 16191 // friend simple-type-specifier ; 16192 // friend typename-specifier ; 16193 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 16194 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 16195 } 16196 16197 // If the type specifier in a friend declaration designates a (possibly 16198 // cv-qualified) class type, that class is declared as a friend; otherwise, 16199 // the friend declaration is ignored. 16200 return FriendDecl::Create(Context, CurContext, 16201 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 16202 FriendLoc); 16203 } 16204 16205 /// Handle a friend tag declaration where the scope specifier was 16206 /// templated. 16207 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 16208 unsigned TagSpec, SourceLocation TagLoc, 16209 CXXScopeSpec &SS, IdentifierInfo *Name, 16210 SourceLocation NameLoc, 16211 const ParsedAttributesView &Attr, 16212 MultiTemplateParamsArg TempParamLists) { 16213 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16214 16215 bool IsMemberSpecialization = false; 16216 bool Invalid = false; 16217 16218 if (TemplateParameterList *TemplateParams = 16219 MatchTemplateParametersToScopeSpecifier( 16220 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 16221 IsMemberSpecialization, Invalid)) { 16222 if (TemplateParams->size() > 0) { 16223 // This is a declaration of a class template. 16224 if (Invalid) 16225 return nullptr; 16226 16227 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 16228 NameLoc, Attr, TemplateParams, AS_public, 16229 /*ModulePrivateLoc=*/SourceLocation(), 16230 FriendLoc, TempParamLists.size() - 1, 16231 TempParamLists.data()).get(); 16232 } else { 16233 // The "template<>" header is extraneous. 16234 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16235 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16236 IsMemberSpecialization = true; 16237 } 16238 } 16239 16240 if (Invalid) return nullptr; 16241 16242 bool isAllExplicitSpecializations = true; 16243 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 16244 if (TempParamLists[I]->size()) { 16245 isAllExplicitSpecializations = false; 16246 break; 16247 } 16248 } 16249 16250 // FIXME: don't ignore attributes. 16251 16252 // If it's explicit specializations all the way down, just forget 16253 // about the template header and build an appropriate non-templated 16254 // friend. TODO: for source fidelity, remember the headers. 16255 if (isAllExplicitSpecializations) { 16256 if (SS.isEmpty()) { 16257 bool Owned = false; 16258 bool IsDependent = false; 16259 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 16260 Attr, AS_public, 16261 /*ModulePrivateLoc=*/SourceLocation(), 16262 MultiTemplateParamsArg(), Owned, IsDependent, 16263 /*ScopedEnumKWLoc=*/SourceLocation(), 16264 /*ScopedEnumUsesClassTag=*/false, 16265 /*UnderlyingType=*/TypeResult(), 16266 /*IsTypeSpecifier=*/false, 16267 /*IsTemplateParamOrArg=*/false); 16268 } 16269 16270 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 16271 ElaboratedTypeKeyword Keyword 16272 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16273 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 16274 *Name, NameLoc); 16275 if (T.isNull()) 16276 return nullptr; 16277 16278 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16279 if (isa<DependentNameType>(T)) { 16280 DependentNameTypeLoc TL = 16281 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16282 TL.setElaboratedKeywordLoc(TagLoc); 16283 TL.setQualifierLoc(QualifierLoc); 16284 TL.setNameLoc(NameLoc); 16285 } else { 16286 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 16287 TL.setElaboratedKeywordLoc(TagLoc); 16288 TL.setQualifierLoc(QualifierLoc); 16289 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 16290 } 16291 16292 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16293 TSI, FriendLoc, TempParamLists); 16294 Friend->setAccess(AS_public); 16295 CurContext->addDecl(Friend); 16296 return Friend; 16297 } 16298 16299 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 16300 16301 16302 16303 // Handle the case of a templated-scope friend class. e.g. 16304 // template <class T> class A<T>::B; 16305 // FIXME: we don't support these right now. 16306 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 16307 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 16308 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16309 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 16310 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16311 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16312 TL.setElaboratedKeywordLoc(TagLoc); 16313 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 16314 TL.setNameLoc(NameLoc); 16315 16316 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16317 TSI, FriendLoc, TempParamLists); 16318 Friend->setAccess(AS_public); 16319 Friend->setUnsupportedFriend(true); 16320 CurContext->addDecl(Friend); 16321 return Friend; 16322 } 16323 16324 /// Handle a friend type declaration. This works in tandem with 16325 /// ActOnTag. 16326 /// 16327 /// Notes on friend class templates: 16328 /// 16329 /// We generally treat friend class declarations as if they were 16330 /// declaring a class. So, for example, the elaborated type specifier 16331 /// in a friend declaration is required to obey the restrictions of a 16332 /// class-head (i.e. no typedefs in the scope chain), template 16333 /// parameters are required to match up with simple template-ids, &c. 16334 /// However, unlike when declaring a template specialization, it's 16335 /// okay to refer to a template specialization without an empty 16336 /// template parameter declaration, e.g. 16337 /// friend class A<T>::B<unsigned>; 16338 /// We permit this as a special case; if there are any template 16339 /// parameters present at all, require proper matching, i.e. 16340 /// template <> template \<class T> friend class A<int>::B; 16341 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 16342 MultiTemplateParamsArg TempParams) { 16343 SourceLocation Loc = DS.getBeginLoc(); 16344 16345 assert(DS.isFriendSpecified()); 16346 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16347 16348 // C++ [class.friend]p3: 16349 // A friend declaration that does not declare a function shall have one of 16350 // the following forms: 16351 // friend elaborated-type-specifier ; 16352 // friend simple-type-specifier ; 16353 // friend typename-specifier ; 16354 // 16355 // Any declaration with a type qualifier does not have that form. (It's 16356 // legal to specify a qualified type as a friend, you just can't write the 16357 // keywords.) 16358 if (DS.getTypeQualifiers()) { 16359 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 16360 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 16361 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 16362 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 16363 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 16364 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 16365 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 16366 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 16367 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 16368 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 16369 } 16370 16371 // Try to convert the decl specifier to a type. This works for 16372 // friend templates because ActOnTag never produces a ClassTemplateDecl 16373 // for a TUK_Friend. 16374 Declarator TheDeclarator(DS, DeclaratorContext::Member); 16375 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 16376 QualType T = TSI->getType(); 16377 if (TheDeclarator.isInvalidType()) 16378 return nullptr; 16379 16380 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 16381 return nullptr; 16382 16383 // This is definitely an error in C++98. It's probably meant to 16384 // be forbidden in C++0x, too, but the specification is just 16385 // poorly written. 16386 // 16387 // The problem is with declarations like the following: 16388 // template <T> friend A<T>::foo; 16389 // where deciding whether a class C is a friend or not now hinges 16390 // on whether there exists an instantiation of A that causes 16391 // 'foo' to equal C. There are restrictions on class-heads 16392 // (which we declare (by fiat) elaborated friend declarations to 16393 // be) that makes this tractable. 16394 // 16395 // FIXME: handle "template <> friend class A<T>;", which 16396 // is possibly well-formed? Who even knows? 16397 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 16398 Diag(Loc, diag::err_tagless_friend_type_template) 16399 << DS.getSourceRange(); 16400 return nullptr; 16401 } 16402 16403 // C++98 [class.friend]p1: A friend of a class is a function 16404 // or class that is not a member of the class . . . 16405 // This is fixed in DR77, which just barely didn't make the C++03 16406 // deadline. It's also a very silly restriction that seriously 16407 // affects inner classes and which nobody else seems to implement; 16408 // thus we never diagnose it, not even in -pedantic. 16409 // 16410 // But note that we could warn about it: it's always useless to 16411 // friend one of your own members (it's not, however, worthless to 16412 // friend a member of an arbitrary specialization of your template). 16413 16414 Decl *D; 16415 if (!TempParams.empty()) 16416 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 16417 TempParams, 16418 TSI, 16419 DS.getFriendSpecLoc()); 16420 else 16421 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 16422 16423 if (!D) 16424 return nullptr; 16425 16426 D->setAccess(AS_public); 16427 CurContext->addDecl(D); 16428 16429 return D; 16430 } 16431 16432 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 16433 MultiTemplateParamsArg TemplateParams) { 16434 const DeclSpec &DS = D.getDeclSpec(); 16435 16436 assert(DS.isFriendSpecified()); 16437 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16438 16439 SourceLocation Loc = D.getIdentifierLoc(); 16440 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16441 16442 // C++ [class.friend]p1 16443 // A friend of a class is a function or class.... 16444 // Note that this sees through typedefs, which is intended. 16445 // It *doesn't* see through dependent types, which is correct 16446 // according to [temp.arg.type]p3: 16447 // If a declaration acquires a function type through a 16448 // type dependent on a template-parameter and this causes 16449 // a declaration that does not use the syntactic form of a 16450 // function declarator to have a function type, the program 16451 // is ill-formed. 16452 if (!TInfo->getType()->isFunctionType()) { 16453 Diag(Loc, diag::err_unexpected_friend); 16454 16455 // It might be worthwhile to try to recover by creating an 16456 // appropriate declaration. 16457 return nullptr; 16458 } 16459 16460 // C++ [namespace.memdef]p3 16461 // - If a friend declaration in a non-local class first declares a 16462 // class or function, the friend class or function is a member 16463 // of the innermost enclosing namespace. 16464 // - The name of the friend is not found by simple name lookup 16465 // until a matching declaration is provided in that namespace 16466 // scope (either before or after the class declaration granting 16467 // friendship). 16468 // - If a friend function is called, its name may be found by the 16469 // name lookup that considers functions from namespaces and 16470 // classes associated with the types of the function arguments. 16471 // - When looking for a prior declaration of a class or a function 16472 // declared as a friend, scopes outside the innermost enclosing 16473 // namespace scope are not considered. 16474 16475 CXXScopeSpec &SS = D.getCXXScopeSpec(); 16476 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 16477 assert(NameInfo.getName()); 16478 16479 // Check for unexpanded parameter packs. 16480 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 16481 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 16482 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 16483 return nullptr; 16484 16485 // The context we found the declaration in, or in which we should 16486 // create the declaration. 16487 DeclContext *DC; 16488 Scope *DCScope = S; 16489 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 16490 ForExternalRedeclaration); 16491 16492 // There are five cases here. 16493 // - There's no scope specifier and we're in a local class. Only look 16494 // for functions declared in the immediately-enclosing block scope. 16495 // We recover from invalid scope qualifiers as if they just weren't there. 16496 FunctionDecl *FunctionContainingLocalClass = nullptr; 16497 if ((SS.isInvalid() || !SS.isSet()) && 16498 (FunctionContainingLocalClass = 16499 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 16500 // C++11 [class.friend]p11: 16501 // If a friend declaration appears in a local class and the name 16502 // specified is an unqualified name, a prior declaration is 16503 // looked up without considering scopes that are outside the 16504 // innermost enclosing non-class scope. For a friend function 16505 // declaration, if there is no prior declaration, the program is 16506 // ill-formed. 16507 16508 // Find the innermost enclosing non-class scope. This is the block 16509 // scope containing the local class definition (or for a nested class, 16510 // the outer local class). 16511 DCScope = S->getFnParent(); 16512 16513 // Look up the function name in the scope. 16514 Previous.clear(LookupLocalFriendName); 16515 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 16516 16517 if (!Previous.empty()) { 16518 // All possible previous declarations must have the same context: 16519 // either they were declared at block scope or they are members of 16520 // one of the enclosing local classes. 16521 DC = Previous.getRepresentativeDecl()->getDeclContext(); 16522 } else { 16523 // This is ill-formed, but provide the context that we would have 16524 // declared the function in, if we were permitted to, for error recovery. 16525 DC = FunctionContainingLocalClass; 16526 } 16527 adjustContextForLocalExternDecl(DC); 16528 16529 // C++ [class.friend]p6: 16530 // A function can be defined in a friend declaration of a class if and 16531 // only if the class is a non-local class (9.8), the function name is 16532 // unqualified, and the function has namespace scope. 16533 if (D.isFunctionDefinition()) { 16534 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 16535 } 16536 16537 // - There's no scope specifier, in which case we just go to the 16538 // appropriate scope and look for a function or function template 16539 // there as appropriate. 16540 } else if (SS.isInvalid() || !SS.isSet()) { 16541 // C++11 [namespace.memdef]p3: 16542 // If the name in a friend declaration is neither qualified nor 16543 // a template-id and the declaration is a function or an 16544 // elaborated-type-specifier, the lookup to determine whether 16545 // the entity has been previously declared shall not consider 16546 // any scopes outside the innermost enclosing namespace. 16547 bool isTemplateId = 16548 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 16549 16550 // Find the appropriate context according to the above. 16551 DC = CurContext; 16552 16553 // Skip class contexts. If someone can cite chapter and verse 16554 // for this behavior, that would be nice --- it's what GCC and 16555 // EDG do, and it seems like a reasonable intent, but the spec 16556 // really only says that checks for unqualified existing 16557 // declarations should stop at the nearest enclosing namespace, 16558 // not that they should only consider the nearest enclosing 16559 // namespace. 16560 while (DC->isRecord()) 16561 DC = DC->getParent(); 16562 16563 DeclContext *LookupDC = DC; 16564 while (LookupDC->isTransparentContext()) 16565 LookupDC = LookupDC->getParent(); 16566 16567 while (true) { 16568 LookupQualifiedName(Previous, LookupDC); 16569 16570 if (!Previous.empty()) { 16571 DC = LookupDC; 16572 break; 16573 } 16574 16575 if (isTemplateId) { 16576 if (isa<TranslationUnitDecl>(LookupDC)) break; 16577 } else { 16578 if (LookupDC->isFileContext()) break; 16579 } 16580 LookupDC = LookupDC->getParent(); 16581 } 16582 16583 DCScope = getScopeForDeclContext(S, DC); 16584 16585 // - There's a non-dependent scope specifier, in which case we 16586 // compute it and do a previous lookup there for a function 16587 // or function template. 16588 } else if (!SS.getScopeRep()->isDependent()) { 16589 DC = computeDeclContext(SS); 16590 if (!DC) return nullptr; 16591 16592 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 16593 16594 LookupQualifiedName(Previous, DC); 16595 16596 // C++ [class.friend]p1: A friend of a class is a function or 16597 // class that is not a member of the class . . . 16598 if (DC->Equals(CurContext)) 16599 Diag(DS.getFriendSpecLoc(), 16600 getLangOpts().CPlusPlus11 ? 16601 diag::warn_cxx98_compat_friend_is_member : 16602 diag::err_friend_is_member); 16603 16604 if (D.isFunctionDefinition()) { 16605 // C++ [class.friend]p6: 16606 // A function can be defined in a friend declaration of a class if and 16607 // only if the class is a non-local class (9.8), the function name is 16608 // unqualified, and the function has namespace scope. 16609 // 16610 // FIXME: We should only do this if the scope specifier names the 16611 // innermost enclosing namespace; otherwise the fixit changes the 16612 // meaning of the code. 16613 SemaDiagnosticBuilder DB 16614 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 16615 16616 DB << SS.getScopeRep(); 16617 if (DC->isFileContext()) 16618 DB << FixItHint::CreateRemoval(SS.getRange()); 16619 SS.clear(); 16620 } 16621 16622 // - There's a scope specifier that does not match any template 16623 // parameter lists, in which case we use some arbitrary context, 16624 // create a method or method template, and wait for instantiation. 16625 // - There's a scope specifier that does match some template 16626 // parameter lists, which we don't handle right now. 16627 } else { 16628 if (D.isFunctionDefinition()) { 16629 // C++ [class.friend]p6: 16630 // A function can be defined in a friend declaration of a class if and 16631 // only if the class is a non-local class (9.8), the function name is 16632 // unqualified, and the function has namespace scope. 16633 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 16634 << SS.getScopeRep(); 16635 } 16636 16637 DC = CurContext; 16638 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 16639 } 16640 16641 if (!DC->isRecord()) { 16642 int DiagArg = -1; 16643 switch (D.getName().getKind()) { 16644 case UnqualifiedIdKind::IK_ConstructorTemplateId: 16645 case UnqualifiedIdKind::IK_ConstructorName: 16646 DiagArg = 0; 16647 break; 16648 case UnqualifiedIdKind::IK_DestructorName: 16649 DiagArg = 1; 16650 break; 16651 case UnqualifiedIdKind::IK_ConversionFunctionId: 16652 DiagArg = 2; 16653 break; 16654 case UnqualifiedIdKind::IK_DeductionGuideName: 16655 DiagArg = 3; 16656 break; 16657 case UnqualifiedIdKind::IK_Identifier: 16658 case UnqualifiedIdKind::IK_ImplicitSelfParam: 16659 case UnqualifiedIdKind::IK_LiteralOperatorId: 16660 case UnqualifiedIdKind::IK_OperatorFunctionId: 16661 case UnqualifiedIdKind::IK_TemplateId: 16662 break; 16663 } 16664 // This implies that it has to be an operator or function. 16665 if (DiagArg >= 0) { 16666 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 16667 return nullptr; 16668 } 16669 } 16670 16671 // FIXME: This is an egregious hack to cope with cases where the scope stack 16672 // does not contain the declaration context, i.e., in an out-of-line 16673 // definition of a class. 16674 Scope FakeDCScope(S, Scope::DeclScope, Diags); 16675 if (!DCScope) { 16676 FakeDCScope.setEntity(DC); 16677 DCScope = &FakeDCScope; 16678 } 16679 16680 bool AddToScope = true; 16681 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 16682 TemplateParams, AddToScope); 16683 if (!ND) return nullptr; 16684 16685 assert(ND->getLexicalDeclContext() == CurContext); 16686 16687 // If we performed typo correction, we might have added a scope specifier 16688 // and changed the decl context. 16689 DC = ND->getDeclContext(); 16690 16691 // Add the function declaration to the appropriate lookup tables, 16692 // adjusting the redeclarations list as necessary. We don't 16693 // want to do this yet if the friending class is dependent. 16694 // 16695 // Also update the scope-based lookup if the target context's 16696 // lookup context is in lexical scope. 16697 if (!CurContext->isDependentContext()) { 16698 DC = DC->getRedeclContext(); 16699 DC->makeDeclVisibleInContext(ND); 16700 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16701 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 16702 } 16703 16704 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 16705 D.getIdentifierLoc(), ND, 16706 DS.getFriendSpecLoc()); 16707 FrD->setAccess(AS_public); 16708 CurContext->addDecl(FrD); 16709 16710 if (ND->isInvalidDecl()) { 16711 FrD->setInvalidDecl(); 16712 } else { 16713 if (DC->isRecord()) CheckFriendAccess(ND); 16714 16715 FunctionDecl *FD; 16716 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 16717 FD = FTD->getTemplatedDecl(); 16718 else 16719 FD = cast<FunctionDecl>(ND); 16720 16721 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 16722 // default argument expression, that declaration shall be a definition 16723 // and shall be the only declaration of the function or function 16724 // template in the translation unit. 16725 if (functionDeclHasDefaultArgument(FD)) { 16726 // We can't look at FD->getPreviousDecl() because it may not have been set 16727 // if we're in a dependent context. If the function is known to be a 16728 // redeclaration, we will have narrowed Previous down to the right decl. 16729 if (D.isRedeclaration()) { 16730 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 16731 Diag(Previous.getRepresentativeDecl()->getLocation(), 16732 diag::note_previous_declaration); 16733 } else if (!D.isFunctionDefinition()) 16734 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 16735 } 16736 16737 // Mark templated-scope function declarations as unsupported. 16738 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 16739 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 16740 << SS.getScopeRep() << SS.getRange() 16741 << cast<CXXRecordDecl>(CurContext); 16742 FrD->setUnsupportedFriend(true); 16743 } 16744 } 16745 16746 return ND; 16747 } 16748 16749 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 16750 AdjustDeclIfTemplate(Dcl); 16751 16752 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 16753 if (!Fn) { 16754 Diag(DelLoc, diag::err_deleted_non_function); 16755 return; 16756 } 16757 16758 // Deleted function does not have a body. 16759 Fn->setWillHaveBody(false); 16760 16761 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 16762 // Don't consider the implicit declaration we generate for explicit 16763 // specializations. FIXME: Do not generate these implicit declarations. 16764 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 16765 Prev->getPreviousDecl()) && 16766 !Prev->isDefined()) { 16767 Diag(DelLoc, diag::err_deleted_decl_not_first); 16768 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 16769 Prev->isImplicit() ? diag::note_previous_implicit_declaration 16770 : diag::note_previous_declaration); 16771 // We can't recover from this; the declaration might have already 16772 // been used. 16773 Fn->setInvalidDecl(); 16774 return; 16775 } 16776 16777 // To maintain the invariant that functions are only deleted on their first 16778 // declaration, mark the implicitly-instantiated declaration of the 16779 // explicitly-specialized function as deleted instead of marking the 16780 // instantiated redeclaration. 16781 Fn = Fn->getCanonicalDecl(); 16782 } 16783 16784 // dllimport/dllexport cannot be deleted. 16785 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 16786 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 16787 Fn->setInvalidDecl(); 16788 } 16789 16790 // C++11 [basic.start.main]p3: 16791 // A program that defines main as deleted [...] is ill-formed. 16792 if (Fn->isMain()) 16793 Diag(DelLoc, diag::err_deleted_main); 16794 16795 // C++11 [dcl.fct.def.delete]p4: 16796 // A deleted function is implicitly inline. 16797 Fn->setImplicitlyInline(); 16798 Fn->setDeletedAsWritten(); 16799 } 16800 16801 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 16802 if (!Dcl || Dcl->isInvalidDecl()) 16803 return; 16804 16805 auto *FD = dyn_cast<FunctionDecl>(Dcl); 16806 if (!FD) { 16807 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 16808 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 16809 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 16810 return; 16811 } 16812 } 16813 16814 Diag(DefaultLoc, diag::err_default_special_members) 16815 << getLangOpts().CPlusPlus20; 16816 return; 16817 } 16818 16819 // Reject if this can't possibly be a defaultable function. 16820 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 16821 if (!DefKind && 16822 // A dependent function that doesn't locally look defaultable can 16823 // still instantiate to a defaultable function if it's a constructor 16824 // or assignment operator. 16825 (!FD->isDependentContext() || 16826 (!isa<CXXConstructorDecl>(FD) && 16827 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 16828 Diag(DefaultLoc, diag::err_default_special_members) 16829 << getLangOpts().CPlusPlus20; 16830 return; 16831 } 16832 16833 if (DefKind.isComparison() && 16834 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 16835 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class) 16836 << (int)DefKind.asComparison(); 16837 return; 16838 } 16839 16840 // Issue compatibility warning. We already warned if the operator is 16841 // 'operator<=>' when parsing the '<=>' token. 16842 if (DefKind.isComparison() && 16843 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 16844 Diag(DefaultLoc, getLangOpts().CPlusPlus20 16845 ? diag::warn_cxx17_compat_defaulted_comparison 16846 : diag::ext_defaulted_comparison); 16847 } 16848 16849 FD->setDefaulted(); 16850 FD->setExplicitlyDefaulted(); 16851 16852 // Defer checking functions that are defaulted in a dependent context. 16853 if (FD->isDependentContext()) 16854 return; 16855 16856 // Unset that we will have a body for this function. We might not, 16857 // if it turns out to be trivial, and we don't need this marking now 16858 // that we've marked it as defaulted. 16859 FD->setWillHaveBody(false); 16860 16861 // If this definition appears within the record, do the checking when 16862 // the record is complete. This is always the case for a defaulted 16863 // comparison. 16864 if (DefKind.isComparison()) 16865 return; 16866 auto *MD = cast<CXXMethodDecl>(FD); 16867 16868 const FunctionDecl *Primary = FD; 16869 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 16870 // Ask the template instantiation pattern that actually had the 16871 // '= default' on it. 16872 Primary = Pattern; 16873 16874 // If the method was defaulted on its first declaration, we will have 16875 // already performed the checking in CheckCompletedCXXClass. Such a 16876 // declaration doesn't trigger an implicit definition. 16877 if (Primary->getCanonicalDecl()->isDefaulted()) 16878 return; 16879 16880 // FIXME: Once we support defining comparisons out of class, check for a 16881 // defaulted comparison here. 16882 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 16883 MD->setInvalidDecl(); 16884 else 16885 DefineDefaultedFunction(*this, MD, DefaultLoc); 16886 } 16887 16888 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 16889 for (Stmt *SubStmt : S->children()) { 16890 if (!SubStmt) 16891 continue; 16892 if (isa<ReturnStmt>(SubStmt)) 16893 Self.Diag(SubStmt->getBeginLoc(), 16894 diag::err_return_in_constructor_handler); 16895 if (!isa<Expr>(SubStmt)) 16896 SearchForReturnInStmt(Self, SubStmt); 16897 } 16898 } 16899 16900 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 16901 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 16902 CXXCatchStmt *Handler = TryBlock->getHandler(I); 16903 SearchForReturnInStmt(*this, Handler); 16904 } 16905 } 16906 16907 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 16908 const CXXMethodDecl *Old) { 16909 const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); 16910 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); 16911 16912 if (OldFT->hasExtParameterInfos()) { 16913 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 16914 // A parameter of the overriding method should be annotated with noescape 16915 // if the corresponding parameter of the overridden method is annotated. 16916 if (OldFT->getExtParameterInfo(I).isNoEscape() && 16917 !NewFT->getExtParameterInfo(I).isNoEscape()) { 16918 Diag(New->getParamDecl(I)->getLocation(), 16919 diag::warn_overriding_method_missing_noescape); 16920 Diag(Old->getParamDecl(I)->getLocation(), 16921 diag::note_overridden_marked_noescape); 16922 } 16923 } 16924 16925 // Virtual overrides must have the same code_seg. 16926 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 16927 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 16928 if ((NewCSA || OldCSA) && 16929 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 16930 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 16931 Diag(Old->getLocation(), diag::note_previous_declaration); 16932 return true; 16933 } 16934 16935 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 16936 16937 // If the calling conventions match, everything is fine 16938 if (NewCC == OldCC) 16939 return false; 16940 16941 // If the calling conventions mismatch because the new function is static, 16942 // suppress the calling convention mismatch error; the error about static 16943 // function override (err_static_overrides_virtual from 16944 // Sema::CheckFunctionDeclaration) is more clear. 16945 if (New->getStorageClass() == SC_Static) 16946 return false; 16947 16948 Diag(New->getLocation(), 16949 diag::err_conflicting_overriding_cc_attributes) 16950 << New->getDeclName() << New->getType() << Old->getType(); 16951 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 16952 return true; 16953 } 16954 16955 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 16956 const CXXMethodDecl *Old) { 16957 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); 16958 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); 16959 16960 if (Context.hasSameType(NewTy, OldTy) || 16961 NewTy->isDependentType() || OldTy->isDependentType()) 16962 return false; 16963 16964 // Check if the return types are covariant 16965 QualType NewClassTy, OldClassTy; 16966 16967 /// Both types must be pointers or references to classes. 16968 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 16969 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 16970 NewClassTy = NewPT->getPointeeType(); 16971 OldClassTy = OldPT->getPointeeType(); 16972 } 16973 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 16974 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 16975 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 16976 NewClassTy = NewRT->getPointeeType(); 16977 OldClassTy = OldRT->getPointeeType(); 16978 } 16979 } 16980 } 16981 16982 // The return types aren't either both pointers or references to a class type. 16983 if (NewClassTy.isNull()) { 16984 Diag(New->getLocation(), 16985 diag::err_different_return_type_for_overriding_virtual_function) 16986 << New->getDeclName() << NewTy << OldTy 16987 << New->getReturnTypeSourceRange(); 16988 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16989 << Old->getReturnTypeSourceRange(); 16990 16991 return true; 16992 } 16993 16994 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 16995 // C++14 [class.virtual]p8: 16996 // If the class type in the covariant return type of D::f differs from 16997 // that of B::f, the class type in the return type of D::f shall be 16998 // complete at the point of declaration of D::f or shall be the class 16999 // type D. 17000 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 17001 if (!RT->isBeingDefined() && 17002 RequireCompleteType(New->getLocation(), NewClassTy, 17003 diag::err_covariant_return_incomplete, 17004 New->getDeclName())) 17005 return true; 17006 } 17007 17008 // Check if the new class derives from the old class. 17009 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 17010 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 17011 << New->getDeclName() << NewTy << OldTy 17012 << New->getReturnTypeSourceRange(); 17013 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17014 << Old->getReturnTypeSourceRange(); 17015 return true; 17016 } 17017 17018 // Check if we the conversion from derived to base is valid. 17019 if (CheckDerivedToBaseConversion( 17020 NewClassTy, OldClassTy, 17021 diag::err_covariant_return_inaccessible_base, 17022 diag::err_covariant_return_ambiguous_derived_to_base_conv, 17023 New->getLocation(), New->getReturnTypeSourceRange(), 17024 New->getDeclName(), nullptr)) { 17025 // FIXME: this note won't trigger for delayed access control 17026 // diagnostics, and it's impossible to get an undelayed error 17027 // here from access control during the original parse because 17028 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 17029 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17030 << Old->getReturnTypeSourceRange(); 17031 return true; 17032 } 17033 } 17034 17035 // The qualifiers of the return types must be the same. 17036 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 17037 Diag(New->getLocation(), 17038 diag::err_covariant_return_type_different_qualifications) 17039 << New->getDeclName() << NewTy << OldTy 17040 << New->getReturnTypeSourceRange(); 17041 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17042 << Old->getReturnTypeSourceRange(); 17043 return true; 17044 } 17045 17046 17047 // The new class type must have the same or less qualifiers as the old type. 17048 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 17049 Diag(New->getLocation(), 17050 diag::err_covariant_return_type_class_type_more_qualified) 17051 << New->getDeclName() << NewTy << OldTy 17052 << New->getReturnTypeSourceRange(); 17053 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17054 << Old->getReturnTypeSourceRange(); 17055 return true; 17056 } 17057 17058 return false; 17059 } 17060 17061 /// Mark the given method pure. 17062 /// 17063 /// \param Method the method to be marked pure. 17064 /// 17065 /// \param InitRange the source range that covers the "0" initializer. 17066 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 17067 SourceLocation EndLoc = InitRange.getEnd(); 17068 if (EndLoc.isValid()) 17069 Method->setRangeEnd(EndLoc); 17070 17071 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 17072 Method->setPure(); 17073 return false; 17074 } 17075 17076 if (!Method->isInvalidDecl()) 17077 Diag(Method->getLocation(), diag::err_non_virtual_pure) 17078 << Method->getDeclName() << InitRange; 17079 return true; 17080 } 17081 17082 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 17083 if (D->getFriendObjectKind()) 17084 Diag(D->getLocation(), diag::err_pure_friend); 17085 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 17086 CheckPureMethod(M, ZeroLoc); 17087 else 17088 Diag(D->getLocation(), diag::err_illegal_initializer); 17089 } 17090 17091 /// Determine whether the given declaration is a global variable or 17092 /// static data member. 17093 static bool isNonlocalVariable(const Decl *D) { 17094 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 17095 return Var->hasGlobalStorage(); 17096 17097 return false; 17098 } 17099 17100 /// Invoked when we are about to parse an initializer for the declaration 17101 /// 'Dcl'. 17102 /// 17103 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 17104 /// static data member of class X, names should be looked up in the scope of 17105 /// class X. If the declaration had a scope specifier, a scope will have 17106 /// been created and passed in for this purpose. Otherwise, S will be null. 17107 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 17108 // If there is no declaration, there was an error parsing it. 17109 if (!D || D->isInvalidDecl()) 17110 return; 17111 17112 // We will always have a nested name specifier here, but this declaration 17113 // might not be out of line if the specifier names the current namespace: 17114 // extern int n; 17115 // int ::n = 0; 17116 if (S && D->isOutOfLine()) 17117 EnterDeclaratorContext(S, D->getDeclContext()); 17118 17119 // If we are parsing the initializer for a static data member, push a 17120 // new expression evaluation context that is associated with this static 17121 // data member. 17122 if (isNonlocalVariable(D)) 17123 PushExpressionEvaluationContext( 17124 ExpressionEvaluationContext::PotentiallyEvaluated, D); 17125 } 17126 17127 /// Invoked after we are finished parsing an initializer for the declaration D. 17128 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 17129 // If there is no declaration, there was an error parsing it. 17130 if (!D || D->isInvalidDecl()) 17131 return; 17132 17133 if (isNonlocalVariable(D)) 17134 PopExpressionEvaluationContext(); 17135 17136 if (S && D->isOutOfLine()) 17137 ExitDeclaratorContext(S); 17138 } 17139 17140 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 17141 /// C++ if/switch/while/for statement. 17142 /// e.g: "if (int x = f()) {...}" 17143 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 17144 // C++ 6.4p2: 17145 // The declarator shall not specify a function or an array. 17146 // The type-specifier-seq shall not contain typedef and shall not declare a 17147 // new class or enumeration. 17148 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 17149 "Parser allowed 'typedef' as storage class of condition decl."); 17150 17151 Decl *Dcl = ActOnDeclarator(S, D); 17152 if (!Dcl) 17153 return true; 17154 17155 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 17156 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 17157 << D.getSourceRange(); 17158 return true; 17159 } 17160 17161 return Dcl; 17162 } 17163 17164 void Sema::LoadExternalVTableUses() { 17165 if (!ExternalSource) 17166 return; 17167 17168 SmallVector<ExternalVTableUse, 4> VTables; 17169 ExternalSource->ReadUsedVTables(VTables); 17170 SmallVector<VTableUse, 4> NewUses; 17171 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 17172 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 17173 = VTablesUsed.find(VTables[I].Record); 17174 // Even if a definition wasn't required before, it may be required now. 17175 if (Pos != VTablesUsed.end()) { 17176 if (!Pos->second && VTables[I].DefinitionRequired) 17177 Pos->second = true; 17178 continue; 17179 } 17180 17181 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 17182 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 17183 } 17184 17185 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 17186 } 17187 17188 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 17189 bool DefinitionRequired) { 17190 // Ignore any vtable uses in unevaluated operands or for classes that do 17191 // not have a vtable. 17192 if (!Class->isDynamicClass() || Class->isDependentContext() || 17193 CurContext->isDependentContext() || isUnevaluatedContext()) 17194 return; 17195 // Do not mark as used if compiling for the device outside of the target 17196 // region. 17197 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 17198 !isInOpenMPDeclareTargetContext() && 17199 !isInOpenMPTargetExecutionDirective()) { 17200 if (!DefinitionRequired) 17201 MarkVirtualMembersReferenced(Loc, Class); 17202 return; 17203 } 17204 17205 // Try to insert this class into the map. 17206 LoadExternalVTableUses(); 17207 Class = Class->getCanonicalDecl(); 17208 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 17209 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 17210 if (!Pos.second) { 17211 // If we already had an entry, check to see if we are promoting this vtable 17212 // to require a definition. If so, we need to reappend to the VTableUses 17213 // list, since we may have already processed the first entry. 17214 if (DefinitionRequired && !Pos.first->second) { 17215 Pos.first->second = true; 17216 } else { 17217 // Otherwise, we can early exit. 17218 return; 17219 } 17220 } else { 17221 // The Microsoft ABI requires that we perform the destructor body 17222 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 17223 // the deleting destructor is emitted with the vtable, not with the 17224 // destructor definition as in the Itanium ABI. 17225 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17226 CXXDestructorDecl *DD = Class->getDestructor(); 17227 if (DD && DD->isVirtual() && !DD->isDeleted()) { 17228 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 17229 // If this is an out-of-line declaration, marking it referenced will 17230 // not do anything. Manually call CheckDestructor to look up operator 17231 // delete(). 17232 ContextRAII SavedContext(*this, DD); 17233 CheckDestructor(DD); 17234 } else { 17235 MarkFunctionReferenced(Loc, Class->getDestructor()); 17236 } 17237 } 17238 } 17239 } 17240 17241 // Local classes need to have their virtual members marked 17242 // immediately. For all other classes, we mark their virtual members 17243 // at the end of the translation unit. 17244 if (Class->isLocalClass()) 17245 MarkVirtualMembersReferenced(Loc, Class); 17246 else 17247 VTableUses.push_back(std::make_pair(Class, Loc)); 17248 } 17249 17250 bool Sema::DefineUsedVTables() { 17251 LoadExternalVTableUses(); 17252 if (VTableUses.empty()) 17253 return false; 17254 17255 // Note: The VTableUses vector could grow as a result of marking 17256 // the members of a class as "used", so we check the size each 17257 // time through the loop and prefer indices (which are stable) to 17258 // iterators (which are not). 17259 bool DefinedAnything = false; 17260 for (unsigned I = 0; I != VTableUses.size(); ++I) { 17261 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 17262 if (!Class) 17263 continue; 17264 TemplateSpecializationKind ClassTSK = 17265 Class->getTemplateSpecializationKind(); 17266 17267 SourceLocation Loc = VTableUses[I].second; 17268 17269 bool DefineVTable = true; 17270 17271 // If this class has a key function, but that key function is 17272 // defined in another translation unit, we don't need to emit the 17273 // vtable even though we're using it. 17274 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 17275 if (KeyFunction && !KeyFunction->hasBody()) { 17276 // The key function is in another translation unit. 17277 DefineVTable = false; 17278 TemplateSpecializationKind TSK = 17279 KeyFunction->getTemplateSpecializationKind(); 17280 assert(TSK != TSK_ExplicitInstantiationDefinition && 17281 TSK != TSK_ImplicitInstantiation && 17282 "Instantiations don't have key functions"); 17283 (void)TSK; 17284 } else if (!KeyFunction) { 17285 // If we have a class with no key function that is the subject 17286 // of an explicit instantiation declaration, suppress the 17287 // vtable; it will live with the explicit instantiation 17288 // definition. 17289 bool IsExplicitInstantiationDeclaration = 17290 ClassTSK == TSK_ExplicitInstantiationDeclaration; 17291 for (auto R : Class->redecls()) { 17292 TemplateSpecializationKind TSK 17293 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 17294 if (TSK == TSK_ExplicitInstantiationDeclaration) 17295 IsExplicitInstantiationDeclaration = true; 17296 else if (TSK == TSK_ExplicitInstantiationDefinition) { 17297 IsExplicitInstantiationDeclaration = false; 17298 break; 17299 } 17300 } 17301 17302 if (IsExplicitInstantiationDeclaration) 17303 DefineVTable = false; 17304 } 17305 17306 // The exception specifications for all virtual members may be needed even 17307 // if we are not providing an authoritative form of the vtable in this TU. 17308 // We may choose to emit it available_externally anyway. 17309 if (!DefineVTable) { 17310 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 17311 continue; 17312 } 17313 17314 // Mark all of the virtual members of this class as referenced, so 17315 // that we can build a vtable. Then, tell the AST consumer that a 17316 // vtable for this class is required. 17317 DefinedAnything = true; 17318 MarkVirtualMembersReferenced(Loc, Class); 17319 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 17320 if (VTablesUsed[Canonical]) 17321 Consumer.HandleVTable(Class); 17322 17323 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 17324 // no key function or the key function is inlined. Don't warn in C++ ABIs 17325 // that lack key functions, since the user won't be able to make one. 17326 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 17327 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 17328 const FunctionDecl *KeyFunctionDef = nullptr; 17329 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 17330 KeyFunctionDef->isInlined())) { 17331 Diag(Class->getLocation(), 17332 ClassTSK == TSK_ExplicitInstantiationDefinition 17333 ? diag::warn_weak_template_vtable 17334 : diag::warn_weak_vtable) 17335 << Class; 17336 } 17337 } 17338 } 17339 VTableUses.clear(); 17340 17341 return DefinedAnything; 17342 } 17343 17344 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 17345 const CXXRecordDecl *RD) { 17346 for (const auto *I : RD->methods()) 17347 if (I->isVirtual() && !I->isPure()) 17348 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 17349 } 17350 17351 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 17352 const CXXRecordDecl *RD, 17353 bool ConstexprOnly) { 17354 // Mark all functions which will appear in RD's vtable as used. 17355 CXXFinalOverriderMap FinalOverriders; 17356 RD->getFinalOverriders(FinalOverriders); 17357 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 17358 E = FinalOverriders.end(); 17359 I != E; ++I) { 17360 for (OverridingMethods::const_iterator OI = I->second.begin(), 17361 OE = I->second.end(); 17362 OI != OE; ++OI) { 17363 assert(OI->second.size() > 0 && "no final overrider"); 17364 CXXMethodDecl *Overrider = OI->second.front().Method; 17365 17366 // C++ [basic.def.odr]p2: 17367 // [...] A virtual member function is used if it is not pure. [...] 17368 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 17369 MarkFunctionReferenced(Loc, Overrider); 17370 } 17371 } 17372 17373 // Only classes that have virtual bases need a VTT. 17374 if (RD->getNumVBases() == 0) 17375 return; 17376 17377 for (const auto &I : RD->bases()) { 17378 const auto *Base = 17379 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 17380 if (Base->getNumVBases() == 0) 17381 continue; 17382 MarkVirtualMembersReferenced(Loc, Base); 17383 } 17384 } 17385 17386 /// SetIvarInitializers - This routine builds initialization ASTs for the 17387 /// Objective-C implementation whose ivars need be initialized. 17388 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 17389 if (!getLangOpts().CPlusPlus) 17390 return; 17391 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 17392 SmallVector<ObjCIvarDecl*, 8> ivars; 17393 CollectIvarsToConstructOrDestruct(OID, ivars); 17394 if (ivars.empty()) 17395 return; 17396 SmallVector<CXXCtorInitializer*, 32> AllToInit; 17397 for (unsigned i = 0; i < ivars.size(); i++) { 17398 FieldDecl *Field = ivars[i]; 17399 if (Field->isInvalidDecl()) 17400 continue; 17401 17402 CXXCtorInitializer *Member; 17403 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 17404 InitializationKind InitKind = 17405 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 17406 17407 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 17408 ExprResult MemberInit = 17409 InitSeq.Perform(*this, InitEntity, InitKind, None); 17410 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 17411 // Note, MemberInit could actually come back empty if no initialization 17412 // is required (e.g., because it would call a trivial default constructor) 17413 if (!MemberInit.get() || MemberInit.isInvalid()) 17414 continue; 17415 17416 Member = 17417 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 17418 SourceLocation(), 17419 MemberInit.getAs<Expr>(), 17420 SourceLocation()); 17421 AllToInit.push_back(Member); 17422 17423 // Be sure that the destructor is accessible and is marked as referenced. 17424 if (const RecordType *RecordTy = 17425 Context.getBaseElementType(Field->getType()) 17426 ->getAs<RecordType>()) { 17427 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 17428 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 17429 MarkFunctionReferenced(Field->getLocation(), Destructor); 17430 CheckDestructorAccess(Field->getLocation(), Destructor, 17431 PDiag(diag::err_access_dtor_ivar) 17432 << Context.getBaseElementType(Field->getType())); 17433 } 17434 } 17435 } 17436 ObjCImplementation->setIvarInitializers(Context, 17437 AllToInit.data(), AllToInit.size()); 17438 } 17439 } 17440 17441 static 17442 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 17443 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 17444 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 17445 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 17446 Sema &S) { 17447 if (Ctor->isInvalidDecl()) 17448 return; 17449 17450 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 17451 17452 // Target may not be determinable yet, for instance if this is a dependent 17453 // call in an uninstantiated template. 17454 if (Target) { 17455 const FunctionDecl *FNTarget = nullptr; 17456 (void)Target->hasBody(FNTarget); 17457 Target = const_cast<CXXConstructorDecl*>( 17458 cast_or_null<CXXConstructorDecl>(FNTarget)); 17459 } 17460 17461 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 17462 // Avoid dereferencing a null pointer here. 17463 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 17464 17465 if (!Current.insert(Canonical).second) 17466 return; 17467 17468 // We know that beyond here, we aren't chaining into a cycle. 17469 if (!Target || !Target->isDelegatingConstructor() || 17470 Target->isInvalidDecl() || Valid.count(TCanonical)) { 17471 Valid.insert(Current.begin(), Current.end()); 17472 Current.clear(); 17473 // We've hit a cycle. 17474 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 17475 Current.count(TCanonical)) { 17476 // If we haven't diagnosed this cycle yet, do so now. 17477 if (!Invalid.count(TCanonical)) { 17478 S.Diag((*Ctor->init_begin())->getSourceLocation(), 17479 diag::warn_delegating_ctor_cycle) 17480 << Ctor; 17481 17482 // Don't add a note for a function delegating directly to itself. 17483 if (TCanonical != Canonical) 17484 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 17485 17486 CXXConstructorDecl *C = Target; 17487 while (C->getCanonicalDecl() != Canonical) { 17488 const FunctionDecl *FNTarget = nullptr; 17489 (void)C->getTargetConstructor()->hasBody(FNTarget); 17490 assert(FNTarget && "Ctor cycle through bodiless function"); 17491 17492 C = const_cast<CXXConstructorDecl*>( 17493 cast<CXXConstructorDecl>(FNTarget)); 17494 S.Diag(C->getLocation(), diag::note_which_delegates_to); 17495 } 17496 } 17497 17498 Invalid.insert(Current.begin(), Current.end()); 17499 Current.clear(); 17500 } else { 17501 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 17502 } 17503 } 17504 17505 17506 void Sema::CheckDelegatingCtorCycles() { 17507 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 17508 17509 for (DelegatingCtorDeclsType::iterator 17510 I = DelegatingCtorDecls.begin(ExternalSource), 17511 E = DelegatingCtorDecls.end(); 17512 I != E; ++I) 17513 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 17514 17515 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 17516 (*CI)->setInvalidDecl(); 17517 } 17518 17519 namespace { 17520 /// AST visitor that finds references to the 'this' expression. 17521 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 17522 Sema &S; 17523 17524 public: 17525 explicit FindCXXThisExpr(Sema &S) : S(S) { } 17526 17527 bool VisitCXXThisExpr(CXXThisExpr *E) { 17528 S.Diag(E->getLocation(), diag::err_this_static_member_func) 17529 << E->isImplicit(); 17530 return false; 17531 } 17532 }; 17533 } 17534 17535 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 17536 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17537 if (!TSInfo) 17538 return false; 17539 17540 TypeLoc TL = TSInfo->getTypeLoc(); 17541 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17542 if (!ProtoTL) 17543 return false; 17544 17545 // C++11 [expr.prim.general]p3: 17546 // [The expression this] shall not appear before the optional 17547 // cv-qualifier-seq and it shall not appear within the declaration of a 17548 // static member function (although its type and value category are defined 17549 // within a static member function as they are within a non-static member 17550 // function). [ Note: this is because declaration matching does not occur 17551 // until the complete declarator is known. - end note ] 17552 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17553 FindCXXThisExpr Finder(*this); 17554 17555 // If the return type came after the cv-qualifier-seq, check it now. 17556 if (Proto->hasTrailingReturn() && 17557 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 17558 return true; 17559 17560 // Check the exception specification. 17561 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 17562 return true; 17563 17564 // Check the trailing requires clause 17565 if (Expr *E = Method->getTrailingRequiresClause()) 17566 if (!Finder.TraverseStmt(E)) 17567 return true; 17568 17569 return checkThisInStaticMemberFunctionAttributes(Method); 17570 } 17571 17572 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 17573 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17574 if (!TSInfo) 17575 return false; 17576 17577 TypeLoc TL = TSInfo->getTypeLoc(); 17578 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17579 if (!ProtoTL) 17580 return false; 17581 17582 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17583 FindCXXThisExpr Finder(*this); 17584 17585 switch (Proto->getExceptionSpecType()) { 17586 case EST_Unparsed: 17587 case EST_Uninstantiated: 17588 case EST_Unevaluated: 17589 case EST_BasicNoexcept: 17590 case EST_NoThrow: 17591 case EST_DynamicNone: 17592 case EST_MSAny: 17593 case EST_None: 17594 break; 17595 17596 case EST_DependentNoexcept: 17597 case EST_NoexceptFalse: 17598 case EST_NoexceptTrue: 17599 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 17600 return true; 17601 LLVM_FALLTHROUGH; 17602 17603 case EST_Dynamic: 17604 for (const auto &E : Proto->exceptions()) { 17605 if (!Finder.TraverseType(E)) 17606 return true; 17607 } 17608 break; 17609 } 17610 17611 return false; 17612 } 17613 17614 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 17615 FindCXXThisExpr Finder(*this); 17616 17617 // Check attributes. 17618 for (const auto *A : Method->attrs()) { 17619 // FIXME: This should be emitted by tblgen. 17620 Expr *Arg = nullptr; 17621 ArrayRef<Expr *> Args; 17622 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 17623 Arg = G->getArg(); 17624 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 17625 Arg = G->getArg(); 17626 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 17627 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 17628 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 17629 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 17630 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 17631 Arg = ETLF->getSuccessValue(); 17632 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 17633 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 17634 Arg = STLF->getSuccessValue(); 17635 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 17636 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 17637 Arg = LR->getArg(); 17638 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 17639 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 17640 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 17641 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17642 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 17643 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17644 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 17645 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17646 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 17647 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17648 17649 if (Arg && !Finder.TraverseStmt(Arg)) 17650 return true; 17651 17652 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 17653 if (!Finder.TraverseStmt(Args[I])) 17654 return true; 17655 } 17656 } 17657 17658 return false; 17659 } 17660 17661 void Sema::checkExceptionSpecification( 17662 bool IsTopLevel, ExceptionSpecificationType EST, 17663 ArrayRef<ParsedType> DynamicExceptions, 17664 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 17665 SmallVectorImpl<QualType> &Exceptions, 17666 FunctionProtoType::ExceptionSpecInfo &ESI) { 17667 Exceptions.clear(); 17668 ESI.Type = EST; 17669 if (EST == EST_Dynamic) { 17670 Exceptions.reserve(DynamicExceptions.size()); 17671 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 17672 // FIXME: Preserve type source info. 17673 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 17674 17675 if (IsTopLevel) { 17676 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 17677 collectUnexpandedParameterPacks(ET, Unexpanded); 17678 if (!Unexpanded.empty()) { 17679 DiagnoseUnexpandedParameterPacks( 17680 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 17681 Unexpanded); 17682 continue; 17683 } 17684 } 17685 17686 // Check that the type is valid for an exception spec, and 17687 // drop it if not. 17688 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 17689 Exceptions.push_back(ET); 17690 } 17691 ESI.Exceptions = Exceptions; 17692 return; 17693 } 17694 17695 if (isComputedNoexcept(EST)) { 17696 assert((NoexceptExpr->isTypeDependent() || 17697 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 17698 Context.BoolTy) && 17699 "Parser should have made sure that the expression is boolean"); 17700 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 17701 ESI.Type = EST_BasicNoexcept; 17702 return; 17703 } 17704 17705 ESI.NoexceptExpr = NoexceptExpr; 17706 return; 17707 } 17708 } 17709 17710 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 17711 ExceptionSpecificationType EST, 17712 SourceRange SpecificationRange, 17713 ArrayRef<ParsedType> DynamicExceptions, 17714 ArrayRef<SourceRange> DynamicExceptionRanges, 17715 Expr *NoexceptExpr) { 17716 if (!MethodD) 17717 return; 17718 17719 // Dig out the method we're referring to. 17720 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 17721 MethodD = FunTmpl->getTemplatedDecl(); 17722 17723 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 17724 if (!Method) 17725 return; 17726 17727 // Check the exception specification. 17728 llvm::SmallVector<QualType, 4> Exceptions; 17729 FunctionProtoType::ExceptionSpecInfo ESI; 17730 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 17731 DynamicExceptionRanges, NoexceptExpr, Exceptions, 17732 ESI); 17733 17734 // Update the exception specification on the function type. 17735 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 17736 17737 if (Method->isStatic()) 17738 checkThisInStaticMemberFunctionExceptionSpec(Method); 17739 17740 if (Method->isVirtual()) { 17741 // Check overrides, which we previously had to delay. 17742 for (const CXXMethodDecl *O : Method->overridden_methods()) 17743 CheckOverridingFunctionExceptionSpec(Method, O); 17744 } 17745 } 17746 17747 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 17748 /// 17749 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 17750 SourceLocation DeclStart, Declarator &D, 17751 Expr *BitWidth, 17752 InClassInitStyle InitStyle, 17753 AccessSpecifier AS, 17754 const ParsedAttr &MSPropertyAttr) { 17755 IdentifierInfo *II = D.getIdentifier(); 17756 if (!II) { 17757 Diag(DeclStart, diag::err_anonymous_property); 17758 return nullptr; 17759 } 17760 SourceLocation Loc = D.getIdentifierLoc(); 17761 17762 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17763 QualType T = TInfo->getType(); 17764 if (getLangOpts().CPlusPlus) { 17765 CheckExtraCXXDefaultArguments(D); 17766 17767 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 17768 UPPC_DataMemberType)) { 17769 D.setInvalidType(); 17770 T = Context.IntTy; 17771 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 17772 } 17773 } 17774 17775 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 17776 17777 if (D.getDeclSpec().isInlineSpecified()) 17778 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 17779 << getLangOpts().CPlusPlus17; 17780 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 17781 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 17782 diag::err_invalid_thread) 17783 << DeclSpec::getSpecifierName(TSCS); 17784 17785 // Check to see if this name was declared as a member previously 17786 NamedDecl *PrevDecl = nullptr; 17787 LookupResult Previous(*this, II, Loc, LookupMemberName, 17788 ForVisibleRedeclaration); 17789 LookupName(Previous, S); 17790 switch (Previous.getResultKind()) { 17791 case LookupResult::Found: 17792 case LookupResult::FoundUnresolvedValue: 17793 PrevDecl = Previous.getAsSingle<NamedDecl>(); 17794 break; 17795 17796 case LookupResult::FoundOverloaded: 17797 PrevDecl = Previous.getRepresentativeDecl(); 17798 break; 17799 17800 case LookupResult::NotFound: 17801 case LookupResult::NotFoundInCurrentInstantiation: 17802 case LookupResult::Ambiguous: 17803 break; 17804 } 17805 17806 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17807 // Maybe we will complain about the shadowed template parameter. 17808 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 17809 // Just pretend that we didn't see the previous declaration. 17810 PrevDecl = nullptr; 17811 } 17812 17813 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 17814 PrevDecl = nullptr; 17815 17816 SourceLocation TSSL = D.getBeginLoc(); 17817 MSPropertyDecl *NewPD = 17818 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 17819 MSPropertyAttr.getPropertyDataGetter(), 17820 MSPropertyAttr.getPropertyDataSetter()); 17821 ProcessDeclAttributes(TUScope, NewPD, D); 17822 NewPD->setAccess(AS); 17823 17824 if (NewPD->isInvalidDecl()) 17825 Record->setInvalidDecl(); 17826 17827 if (D.getDeclSpec().isModulePrivateSpecified()) 17828 NewPD->setModulePrivate(); 17829 17830 if (NewPD->isInvalidDecl() && PrevDecl) { 17831 // Don't introduce NewFD into scope; there's already something 17832 // with the same name in the same scope. 17833 } else if (II) { 17834 PushOnScopeChains(NewPD, S); 17835 } else 17836 Record->addDecl(NewPD); 17837 17838 return NewPD; 17839 } 17840 17841 void Sema::ActOnStartFunctionDeclarationDeclarator( 17842 Declarator &Declarator, unsigned TemplateParameterDepth) { 17843 auto &Info = InventedParameterInfos.emplace_back(); 17844 TemplateParameterList *ExplicitParams = nullptr; 17845 ArrayRef<TemplateParameterList *> ExplicitLists = 17846 Declarator.getTemplateParameterLists(); 17847 if (!ExplicitLists.empty()) { 17848 bool IsMemberSpecialization, IsInvalid; 17849 ExplicitParams = MatchTemplateParametersToScopeSpecifier( 17850 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), 17851 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, 17852 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, 17853 /*SuppressDiagnostic=*/true); 17854 } 17855 if (ExplicitParams) { 17856 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); 17857 for (NamedDecl *Param : *ExplicitParams) 17858 Info.TemplateParams.push_back(Param); 17859 Info.NumExplicitTemplateParams = ExplicitParams->size(); 17860 } else { 17861 Info.AutoTemplateParameterDepth = TemplateParameterDepth; 17862 Info.NumExplicitTemplateParams = 0; 17863 } 17864 } 17865 17866 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { 17867 auto &FSI = InventedParameterInfos.back(); 17868 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { 17869 if (FSI.NumExplicitTemplateParams != 0) { 17870 TemplateParameterList *ExplicitParams = 17871 Declarator.getTemplateParameterLists().back(); 17872 Declarator.setInventedTemplateParameterList( 17873 TemplateParameterList::Create( 17874 Context, ExplicitParams->getTemplateLoc(), 17875 ExplicitParams->getLAngleLoc(), FSI.TemplateParams, 17876 ExplicitParams->getRAngleLoc(), 17877 ExplicitParams->getRequiresClause())); 17878 } else { 17879 Declarator.setInventedTemplateParameterList( 17880 TemplateParameterList::Create( 17881 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, 17882 SourceLocation(), /*RequiresClause=*/nullptr)); 17883 } 17884 } 17885 InventedParameterInfos.pop_back(); 17886 } 17887