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(ParmVarDecl *Param, Expr *Arg, 258 SourceLocation EqualLoc) { 259 if (RequireCompleteType(Param->getLocation(), Param->getType(), 260 diag::err_typecheck_decl_incomplete_type)) 261 return true; 262 263 // C++ [dcl.fct.default]p5 264 // A default argument expression is implicitly converted (clause 265 // 4) to the parameter type. The default argument expression has 266 // the same semantic constraints as the initializer expression in 267 // a declaration of a variable of the parameter type, using the 268 // copy-initialization semantics (8.5). 269 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 270 Param); 271 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 272 EqualLoc); 273 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 274 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 275 if (Result.isInvalid()) 276 return true; 277 Arg = Result.getAs<Expr>(); 278 279 CheckCompletedExpr(Arg, EqualLoc); 280 Arg = MaybeCreateExprWithCleanups(Arg); 281 282 return Arg; 283 } 284 285 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 286 SourceLocation EqualLoc) { 287 // Add the default argument to the parameter 288 Param->setDefaultArg(Arg); 289 290 // We have already instantiated this parameter; provide each of the 291 // instantiations with the uninstantiated default argument. 292 UnparsedDefaultArgInstantiationsMap::iterator InstPos 293 = UnparsedDefaultArgInstantiations.find(Param); 294 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 295 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 296 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 297 298 // We're done tracking this parameter's instantiations. 299 UnparsedDefaultArgInstantiations.erase(InstPos); 300 } 301 } 302 303 /// ActOnParamDefaultArgument - Check whether the default argument 304 /// provided for a function parameter is well-formed. If so, attach it 305 /// to the parameter declaration. 306 void 307 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 308 Expr *DefaultArg) { 309 if (!param || !DefaultArg) 310 return; 311 312 ParmVarDecl *Param = cast<ParmVarDecl>(param); 313 UnparsedDefaultArgLocs.erase(Param); 314 315 auto Fail = [&] { 316 Param->setInvalidDecl(); 317 Param->setDefaultArg(new (Context) OpaqueValueExpr( 318 EqualLoc, Param->getType().getNonReferenceType(), VK_RValue)); 319 }; 320 321 // Default arguments are only permitted in C++ 322 if (!getLangOpts().CPlusPlus) { 323 Diag(EqualLoc, diag::err_param_default_argument) 324 << DefaultArg->getSourceRange(); 325 return Fail(); 326 } 327 328 // Check for unexpanded parameter packs. 329 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 330 return Fail(); 331 } 332 333 // C++11 [dcl.fct.default]p3 334 // A default argument expression [...] shall not be specified for a 335 // parameter pack. 336 if (Param->isParameterPack()) { 337 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 338 << DefaultArg->getSourceRange(); 339 // Recover by discarding the default argument. 340 Param->setDefaultArg(nullptr); 341 return; 342 } 343 344 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc); 345 if (Result.isInvalid()) 346 return Fail(); 347 348 DefaultArg = Result.getAs<Expr>(); 349 350 // Check that the default argument is well-formed 351 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg); 352 if (DefaultArgChecker.Visit(DefaultArg)) 353 return Fail(); 354 355 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 356 } 357 358 /// ActOnParamUnparsedDefaultArgument - We've seen a default 359 /// argument for a function parameter, but we can't parse it yet 360 /// because we're inside a class definition. Note that this default 361 /// argument will be parsed later. 362 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 363 SourceLocation EqualLoc, 364 SourceLocation ArgLoc) { 365 if (!param) 366 return; 367 368 ParmVarDecl *Param = cast<ParmVarDecl>(param); 369 Param->setUnparsedDefaultArg(); 370 UnparsedDefaultArgLocs[Param] = ArgLoc; 371 } 372 373 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 374 /// the default argument for the parameter param failed. 375 void Sema::ActOnParamDefaultArgumentError(Decl *param, 376 SourceLocation EqualLoc) { 377 if (!param) 378 return; 379 380 ParmVarDecl *Param = cast<ParmVarDecl>(param); 381 Param->setInvalidDecl(); 382 UnparsedDefaultArgLocs.erase(Param); 383 Param->setDefaultArg(new(Context) 384 OpaqueValueExpr(EqualLoc, 385 Param->getType().getNonReferenceType(), 386 VK_RValue)); 387 } 388 389 /// CheckExtraCXXDefaultArguments - Check for any extra default 390 /// arguments in the declarator, which is not a function declaration 391 /// or definition and therefore is not permitted to have default 392 /// arguments. This routine should be invoked for every declarator 393 /// that is not a function declaration or definition. 394 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 395 // C++ [dcl.fct.default]p3 396 // A default argument expression shall be specified only in the 397 // parameter-declaration-clause of a function declaration or in a 398 // template-parameter (14.1). It shall not be specified for a 399 // parameter pack. If it is specified in a 400 // parameter-declaration-clause, it shall not occur within a 401 // declarator or abstract-declarator of a parameter-declaration. 402 bool MightBeFunction = D.isFunctionDeclarationContext(); 403 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 404 DeclaratorChunk &chunk = D.getTypeObject(i); 405 if (chunk.Kind == DeclaratorChunk::Function) { 406 if (MightBeFunction) { 407 // This is a function declaration. It can have default arguments, but 408 // keep looking in case its return type is a function type with default 409 // arguments. 410 MightBeFunction = false; 411 continue; 412 } 413 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 414 ++argIdx) { 415 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 416 if (Param->hasUnparsedDefaultArg()) { 417 std::unique_ptr<CachedTokens> Toks = 418 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 419 SourceRange SR; 420 if (Toks->size() > 1) 421 SR = SourceRange((*Toks)[1].getLocation(), 422 Toks->back().getLocation()); 423 else 424 SR = UnparsedDefaultArgLocs[Param]; 425 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 426 << SR; 427 } else if (Param->getDefaultArg()) { 428 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 429 << Param->getDefaultArg()->getSourceRange(); 430 Param->setDefaultArg(nullptr); 431 } 432 } 433 } else if (chunk.Kind != DeclaratorChunk::Paren) { 434 MightBeFunction = false; 435 } 436 } 437 } 438 439 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 440 return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) { 441 return P->hasDefaultArg() && !P->hasInheritedDefaultArg(); 442 }); 443 } 444 445 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 446 /// function, once we already know that they have the same 447 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 448 /// error, false otherwise. 449 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 450 Scope *S) { 451 bool Invalid = false; 452 453 // The declaration context corresponding to the scope is the semantic 454 // parent, unless this is a local function declaration, in which case 455 // it is that surrounding function. 456 DeclContext *ScopeDC = New->isLocalExternDecl() 457 ? New->getLexicalDeclContext() 458 : New->getDeclContext(); 459 460 // Find the previous declaration for the purpose of default arguments. 461 FunctionDecl *PrevForDefaultArgs = Old; 462 for (/**/; PrevForDefaultArgs; 463 // Don't bother looking back past the latest decl if this is a local 464 // extern declaration; nothing else could work. 465 PrevForDefaultArgs = New->isLocalExternDecl() 466 ? nullptr 467 : PrevForDefaultArgs->getPreviousDecl()) { 468 // Ignore hidden declarations. 469 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 470 continue; 471 472 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 473 !New->isCXXClassMember()) { 474 // Ignore default arguments of old decl if they are not in 475 // the same scope and this is not an out-of-line definition of 476 // a member function. 477 continue; 478 } 479 480 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 481 // If only one of these is a local function declaration, then they are 482 // declared in different scopes, even though isDeclInScope may think 483 // they're in the same scope. (If both are local, the scope check is 484 // sufficient, and if neither is local, then they are in the same scope.) 485 continue; 486 } 487 488 // We found the right previous declaration. 489 break; 490 } 491 492 // C++ [dcl.fct.default]p4: 493 // For non-template functions, default arguments can be added in 494 // later declarations of a function in the same 495 // scope. Declarations in different scopes have completely 496 // distinct sets of default arguments. That is, declarations in 497 // inner scopes do not acquire default arguments from 498 // declarations in outer scopes, and vice versa. In a given 499 // function declaration, all parameters subsequent to a 500 // parameter with a default argument shall have default 501 // arguments supplied in this or previous declarations. A 502 // default argument shall not be redefined by a later 503 // declaration (not even to the same value). 504 // 505 // C++ [dcl.fct.default]p6: 506 // Except for member functions of class templates, the default arguments 507 // in a member function definition that appears outside of the class 508 // definition are added to the set of default arguments provided by the 509 // member function declaration in the class definition. 510 for (unsigned p = 0, NumParams = PrevForDefaultArgs 511 ? PrevForDefaultArgs->getNumParams() 512 : 0; 513 p < NumParams; ++p) { 514 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 515 ParmVarDecl *NewParam = New->getParamDecl(p); 516 517 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 518 bool NewParamHasDfl = NewParam->hasDefaultArg(); 519 520 if (OldParamHasDfl && NewParamHasDfl) { 521 unsigned DiagDefaultParamID = 522 diag::err_param_default_argument_redefinition; 523 524 // MSVC accepts that default parameters be redefined for member functions 525 // of template class. The new default parameter's value is ignored. 526 Invalid = true; 527 if (getLangOpts().MicrosoftExt) { 528 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 529 if (MD && MD->getParent()->getDescribedClassTemplate()) { 530 // Merge the old default argument into the new parameter. 531 NewParam->setHasInheritedDefaultArg(); 532 if (OldParam->hasUninstantiatedDefaultArg()) 533 NewParam->setUninstantiatedDefaultArg( 534 OldParam->getUninstantiatedDefaultArg()); 535 else 536 NewParam->setDefaultArg(OldParam->getInit()); 537 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 538 Invalid = false; 539 } 540 } 541 542 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 543 // hint here. Alternatively, we could walk the type-source information 544 // for NewParam to find the last source location in the type... but it 545 // isn't worth the effort right now. This is the kind of test case that 546 // is hard to get right: 547 // int f(int); 548 // void g(int (*fp)(int) = f); 549 // void g(int (*fp)(int) = &f); 550 Diag(NewParam->getLocation(), DiagDefaultParamID) 551 << NewParam->getDefaultArgRange(); 552 553 // Look for the function declaration where the default argument was 554 // actually written, which may be a declaration prior to Old. 555 for (auto Older = PrevForDefaultArgs; 556 OldParam->hasInheritedDefaultArg(); /**/) { 557 Older = Older->getPreviousDecl(); 558 OldParam = Older->getParamDecl(p); 559 } 560 561 Diag(OldParam->getLocation(), diag::note_previous_definition) 562 << OldParam->getDefaultArgRange(); 563 } else if (OldParamHasDfl) { 564 // Merge the old default argument into the new parameter unless the new 565 // function is a friend declaration in a template class. In the latter 566 // case the default arguments will be inherited when the friend 567 // declaration will be instantiated. 568 if (New->getFriendObjectKind() == Decl::FOK_None || 569 !New->getLexicalDeclContext()->isDependentContext()) { 570 // It's important to use getInit() here; getDefaultArg() 571 // strips off any top-level ExprWithCleanups. 572 NewParam->setHasInheritedDefaultArg(); 573 if (OldParam->hasUnparsedDefaultArg()) 574 NewParam->setUnparsedDefaultArg(); 575 else if (OldParam->hasUninstantiatedDefaultArg()) 576 NewParam->setUninstantiatedDefaultArg( 577 OldParam->getUninstantiatedDefaultArg()); 578 else 579 NewParam->setDefaultArg(OldParam->getInit()); 580 } 581 } else if (NewParamHasDfl) { 582 if (New->getDescribedFunctionTemplate()) { 583 // Paragraph 4, quoted above, only applies to non-template functions. 584 Diag(NewParam->getLocation(), 585 diag::err_param_default_argument_template_redecl) 586 << NewParam->getDefaultArgRange(); 587 Diag(PrevForDefaultArgs->getLocation(), 588 diag::note_template_prev_declaration) 589 << false; 590 } else if (New->getTemplateSpecializationKind() 591 != TSK_ImplicitInstantiation && 592 New->getTemplateSpecializationKind() != TSK_Undeclared) { 593 // C++ [temp.expr.spec]p21: 594 // Default function arguments shall not be specified in a declaration 595 // or a definition for one of the following explicit specializations: 596 // - the explicit specialization of a function template; 597 // - the explicit specialization of a member function template; 598 // - the explicit specialization of a member function of a class 599 // template where the class template specialization to which the 600 // member function specialization belongs is implicitly 601 // instantiated. 602 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 603 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 604 << New->getDeclName() 605 << NewParam->getDefaultArgRange(); 606 } else if (New->getDeclContext()->isDependentContext()) { 607 // C++ [dcl.fct.default]p6 (DR217): 608 // Default arguments for a member function of a class template shall 609 // be specified on the initial declaration of the member function 610 // within the class template. 611 // 612 // Reading the tea leaves a bit in DR217 and its reference to DR205 613 // leads me to the conclusion that one cannot add default function 614 // arguments for an out-of-line definition of a member function of a 615 // dependent type. 616 int WhichKind = 2; 617 if (CXXRecordDecl *Record 618 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 619 if (Record->getDescribedClassTemplate()) 620 WhichKind = 0; 621 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 622 WhichKind = 1; 623 else 624 WhichKind = 2; 625 } 626 627 Diag(NewParam->getLocation(), 628 diag::err_param_default_argument_member_template_redecl) 629 << WhichKind 630 << NewParam->getDefaultArgRange(); 631 } 632 } 633 } 634 635 // DR1344: If a default argument is added outside a class definition and that 636 // default argument makes the function a special member function, the program 637 // is ill-formed. This can only happen for constructors. 638 if (isa<CXXConstructorDecl>(New) && 639 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 640 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 641 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 642 if (NewSM != OldSM) { 643 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 644 assert(NewParam->hasDefaultArg()); 645 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 646 << NewParam->getDefaultArgRange() << NewSM; 647 Diag(Old->getLocation(), diag::note_previous_declaration); 648 } 649 } 650 651 const FunctionDecl *Def; 652 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 653 // template has a constexpr specifier then all its declarations shall 654 // contain the constexpr specifier. 655 if (New->getConstexprKind() != Old->getConstexprKind()) { 656 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 657 << New << static_cast<int>(New->getConstexprKind()) 658 << static_cast<int>(Old->getConstexprKind()); 659 Diag(Old->getLocation(), diag::note_previous_declaration); 660 Invalid = true; 661 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 662 Old->isDefined(Def) && 663 // If a friend function is inlined but does not have 'inline' 664 // specifier, it is a definition. Do not report attribute conflict 665 // in this case, redefinition will be diagnosed later. 666 (New->isInlineSpecified() || 667 New->getFriendObjectKind() == Decl::FOK_None)) { 668 // C++11 [dcl.fcn.spec]p4: 669 // If the definition of a function appears in a translation unit before its 670 // first declaration as inline, the program is ill-formed. 671 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 672 Diag(Def->getLocation(), diag::note_previous_definition); 673 Invalid = true; 674 } 675 676 // C++17 [temp.deduct.guide]p3: 677 // Two deduction guide declarations in the same translation unit 678 // for the same class template shall not have equivalent 679 // parameter-declaration-clauses. 680 if (isa<CXXDeductionGuideDecl>(New) && 681 !New->isFunctionTemplateSpecialization() && isVisible(Old)) { 682 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 683 Diag(Old->getLocation(), diag::note_previous_declaration); 684 } 685 686 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 687 // argument expression, that declaration shall be a definition and shall be 688 // the only declaration of the function or function template in the 689 // translation unit. 690 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 691 functionDeclHasDefaultArgument(Old)) { 692 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 693 Diag(Old->getLocation(), diag::note_previous_declaration); 694 Invalid = true; 695 } 696 697 // C++11 [temp.friend]p4 (DR329): 698 // When a function is defined in a friend function declaration in a class 699 // template, the function is instantiated when the function is odr-used. 700 // The same restrictions on multiple declarations and definitions that 701 // apply to non-template function declarations and definitions also apply 702 // to these implicit definitions. 703 const FunctionDecl *OldDefinition = nullptr; 704 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() && 705 Old->isDefined(OldDefinition, true)) 706 CheckForFunctionRedefinition(New, OldDefinition); 707 708 return Invalid; 709 } 710 711 NamedDecl * 712 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 713 MultiTemplateParamsArg TemplateParamLists) { 714 assert(D.isDecompositionDeclarator()); 715 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 716 717 // The syntax only allows a decomposition declarator as a simple-declaration, 718 // a for-range-declaration, or a condition in Clang, but we parse it in more 719 // cases than that. 720 if (!D.mayHaveDecompositionDeclarator()) { 721 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 722 << Decomp.getSourceRange(); 723 return nullptr; 724 } 725 726 if (!TemplateParamLists.empty()) { 727 // FIXME: There's no rule against this, but there are also no rules that 728 // would actually make it usable, so we reject it for now. 729 Diag(TemplateParamLists.front()->getTemplateLoc(), 730 diag::err_decomp_decl_template); 731 return nullptr; 732 } 733 734 Diag(Decomp.getLSquareLoc(), 735 !getLangOpts().CPlusPlus17 736 ? diag::ext_decomp_decl 737 : D.getContext() == DeclaratorContext::Condition 738 ? diag::ext_decomp_decl_cond 739 : diag::warn_cxx14_compat_decomp_decl) 740 << Decomp.getSourceRange(); 741 742 // The semantic context is always just the current context. 743 DeclContext *const DC = CurContext; 744 745 // C++17 [dcl.dcl]/8: 746 // The decl-specifier-seq shall contain only the type-specifier auto 747 // and cv-qualifiers. 748 // C++2a [dcl.dcl]/8: 749 // If decl-specifier-seq contains any decl-specifier other than static, 750 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 751 auto &DS = D.getDeclSpec(); 752 { 753 SmallVector<StringRef, 8> BadSpecifiers; 754 SmallVector<SourceLocation, 8> BadSpecifierLocs; 755 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 756 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 757 if (auto SCS = DS.getStorageClassSpec()) { 758 if (SCS == DeclSpec::SCS_static) { 759 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 760 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 761 } else { 762 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 763 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 764 } 765 } 766 if (auto TSCS = DS.getThreadStorageClassSpec()) { 767 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 768 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 769 } 770 if (DS.hasConstexprSpecifier()) { 771 BadSpecifiers.push_back( 772 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 773 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 774 } 775 if (DS.isInlineSpecified()) { 776 BadSpecifiers.push_back("inline"); 777 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 778 } 779 if (!BadSpecifiers.empty()) { 780 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 781 Err << (int)BadSpecifiers.size() 782 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 783 // Don't add FixItHints to remove the specifiers; we do still respect 784 // them when building the underlying variable. 785 for (auto Loc : BadSpecifierLocs) 786 Err << SourceRange(Loc, Loc); 787 } else if (!CPlusPlus20Specifiers.empty()) { 788 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 789 getLangOpts().CPlusPlus20 790 ? diag::warn_cxx17_compat_decomp_decl_spec 791 : diag::ext_decomp_decl_spec); 792 Warn << (int)CPlusPlus20Specifiers.size() 793 << llvm::join(CPlusPlus20Specifiers.begin(), 794 CPlusPlus20Specifiers.end(), " "); 795 for (auto Loc : CPlusPlus20SpecifierLocs) 796 Warn << SourceRange(Loc, Loc); 797 } 798 // We can't recover from it being declared as a typedef. 799 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 800 return nullptr; 801 } 802 803 // C++2a [dcl.struct.bind]p1: 804 // A cv that includes volatile is deprecated 805 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && 806 getLangOpts().CPlusPlus20) 807 Diag(DS.getVolatileSpecLoc(), 808 diag::warn_deprecated_volatile_structured_binding); 809 810 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 811 QualType R = TInfo->getType(); 812 813 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 814 UPPC_DeclarationType)) 815 D.setInvalidType(); 816 817 // The syntax only allows a single ref-qualifier prior to the decomposition 818 // declarator. No other declarator chunks are permitted. Also check the type 819 // specifier here. 820 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 821 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 822 (D.getNumTypeObjects() == 1 && 823 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 824 Diag(Decomp.getLSquareLoc(), 825 (D.hasGroupingParens() || 826 (D.getNumTypeObjects() && 827 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 828 ? diag::err_decomp_decl_parens 829 : diag::err_decomp_decl_type) 830 << R; 831 832 // In most cases, there's no actual problem with an explicitly-specified 833 // type, but a function type won't work here, and ActOnVariableDeclarator 834 // shouldn't be called for such a type. 835 if (R->isFunctionType()) 836 D.setInvalidType(); 837 } 838 839 // Build the BindingDecls. 840 SmallVector<BindingDecl*, 8> Bindings; 841 842 // Build the BindingDecls. 843 for (auto &B : D.getDecompositionDeclarator().bindings()) { 844 // Check for name conflicts. 845 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 846 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 847 ForVisibleRedeclaration); 848 LookupName(Previous, S, 849 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 850 851 // It's not permitted to shadow a template parameter name. 852 if (Previous.isSingleResult() && 853 Previous.getFoundDecl()->isTemplateParameter()) { 854 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 855 Previous.getFoundDecl()); 856 Previous.clear(); 857 } 858 859 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 860 861 // Find the shadowed declaration before filtering for scope. 862 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 863 ? getShadowedDeclaration(BD, Previous) 864 : nullptr; 865 866 bool ConsiderLinkage = DC->isFunctionOrMethod() && 867 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 868 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 869 /*AllowInlineNamespace*/false); 870 871 if (!Previous.empty()) { 872 auto *Old = Previous.getRepresentativeDecl(); 873 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 874 Diag(Old->getLocation(), diag::note_previous_definition); 875 } else if (ShadowedDecl && !D.isRedeclaration()) { 876 CheckShadow(BD, ShadowedDecl, Previous); 877 } 878 PushOnScopeChains(BD, S, true); 879 Bindings.push_back(BD); 880 ParsingInitForAutoVars.insert(BD); 881 } 882 883 // There are no prior lookup results for the variable itself, because it 884 // is unnamed. 885 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 886 Decomp.getLSquareLoc()); 887 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 888 ForVisibleRedeclaration); 889 890 // Build the variable that holds the non-decomposed object. 891 bool AddToScope = true; 892 NamedDecl *New = 893 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 894 MultiTemplateParamsArg(), AddToScope, Bindings); 895 if (AddToScope) { 896 S->AddDecl(New); 897 CurContext->addHiddenDecl(New); 898 } 899 900 if (isInOpenMPDeclareTargetContext()) 901 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 902 903 return New; 904 } 905 906 static bool checkSimpleDecomposition( 907 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 908 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 909 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 910 if ((int64_t)Bindings.size() != NumElems) { 911 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 912 << DecompType << (unsigned)Bindings.size() 913 << (unsigned)NumElems.getLimitedValue(UINT_MAX) << NumElems.toString(10) 914 << (NumElems < Bindings.size()); 915 return true; 916 } 917 918 unsigned I = 0; 919 for (auto *B : Bindings) { 920 SourceLocation Loc = B->getLocation(); 921 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 922 if (E.isInvalid()) 923 return true; 924 E = GetInit(Loc, E.get(), I++); 925 if (E.isInvalid()) 926 return true; 927 B->setBinding(ElemType, E.get()); 928 } 929 930 return false; 931 } 932 933 static bool checkArrayLikeDecomposition(Sema &S, 934 ArrayRef<BindingDecl *> Bindings, 935 ValueDecl *Src, QualType DecompType, 936 const llvm::APSInt &NumElems, 937 QualType ElemType) { 938 return checkSimpleDecomposition( 939 S, Bindings, Src, DecompType, NumElems, ElemType, 940 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 941 ExprResult E = S.ActOnIntegerConstant(Loc, I); 942 if (E.isInvalid()) 943 return ExprError(); 944 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 945 }); 946 } 947 948 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 949 ValueDecl *Src, QualType DecompType, 950 const ConstantArrayType *CAT) { 951 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 952 llvm::APSInt(CAT->getSize()), 953 CAT->getElementType()); 954 } 955 956 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 957 ValueDecl *Src, QualType DecompType, 958 const VectorType *VT) { 959 return checkArrayLikeDecomposition( 960 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 961 S.Context.getQualifiedType(VT->getElementType(), 962 DecompType.getQualifiers())); 963 } 964 965 static bool checkComplexDecomposition(Sema &S, 966 ArrayRef<BindingDecl *> Bindings, 967 ValueDecl *Src, QualType DecompType, 968 const ComplexType *CT) { 969 return checkSimpleDecomposition( 970 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 971 S.Context.getQualifiedType(CT->getElementType(), 972 DecompType.getQualifiers()), 973 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 974 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 975 }); 976 } 977 978 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 979 TemplateArgumentListInfo &Args, 980 const TemplateParameterList *Params) { 981 SmallString<128> SS; 982 llvm::raw_svector_ostream OS(SS); 983 bool First = true; 984 unsigned I = 0; 985 for (auto &Arg : Args.arguments()) { 986 if (!First) 987 OS << ", "; 988 Arg.getArgument().print( 989 PrintingPolicy, OS, 990 TemplateParameterList::shouldIncludeTypeForArgument(Params, I)); 991 First = false; 992 I++; 993 } 994 return std::string(OS.str()); 995 } 996 997 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 998 SourceLocation Loc, StringRef Trait, 999 TemplateArgumentListInfo &Args, 1000 unsigned DiagID) { 1001 auto DiagnoseMissing = [&] { 1002 if (DiagID) 1003 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 1004 Args, /*Params*/ nullptr); 1005 return true; 1006 }; 1007 1008 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 1009 NamespaceDecl *Std = S.getStdNamespace(); 1010 if (!Std) 1011 return DiagnoseMissing(); 1012 1013 // Look up the trait itself, within namespace std. We can diagnose various 1014 // problems with this lookup even if we've been asked to not diagnose a 1015 // missing specialization, because this can only fail if the user has been 1016 // declaring their own names in namespace std or we don't support the 1017 // standard library implementation in use. 1018 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 1019 Loc, Sema::LookupOrdinaryName); 1020 if (!S.LookupQualifiedName(Result, Std)) 1021 return DiagnoseMissing(); 1022 if (Result.isAmbiguous()) 1023 return true; 1024 1025 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 1026 if (!TraitTD) { 1027 Result.suppressDiagnostics(); 1028 NamedDecl *Found = *Result.begin(); 1029 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 1030 S.Diag(Found->getLocation(), diag::note_declared_at); 1031 return true; 1032 } 1033 1034 // Build the template-id. 1035 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 1036 if (TraitTy.isNull()) 1037 return true; 1038 if (!S.isCompleteType(Loc, TraitTy)) { 1039 if (DiagID) 1040 S.RequireCompleteType( 1041 Loc, TraitTy, DiagID, 1042 printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1043 TraitTD->getTemplateParameters())); 1044 return true; 1045 } 1046 1047 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1048 assert(RD && "specialization of class template is not a class?"); 1049 1050 // Look up the member of the trait type. 1051 S.LookupQualifiedName(TraitMemberLookup, RD); 1052 return TraitMemberLookup.isAmbiguous(); 1053 } 1054 1055 static TemplateArgumentLoc 1056 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1057 uint64_t I) { 1058 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1059 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1060 } 1061 1062 static TemplateArgumentLoc 1063 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1064 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1065 } 1066 1067 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1068 1069 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1070 llvm::APSInt &Size) { 1071 EnterExpressionEvaluationContext ContextRAII( 1072 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1073 1074 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1075 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1076 1077 // Form template argument list for tuple_size<T>. 1078 TemplateArgumentListInfo Args(Loc, Loc); 1079 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1080 1081 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1082 // it's not tuple-like. 1083 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1084 R.empty()) 1085 return IsTupleLike::NotTupleLike; 1086 1087 // If we get this far, we've committed to the tuple interpretation, but 1088 // we can still fail if there actually isn't a usable ::value. 1089 1090 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1091 LookupResult &R; 1092 TemplateArgumentListInfo &Args; 1093 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1094 : R(R), Args(Args) {} 1095 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 1096 SourceLocation Loc) override { 1097 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1098 << printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1099 /*Params*/ nullptr); 1100 } 1101 } Diagnoser(R, Args); 1102 1103 ExprResult E = 1104 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1105 if (E.isInvalid()) 1106 return IsTupleLike::Error; 1107 1108 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser); 1109 if (E.isInvalid()) 1110 return IsTupleLike::Error; 1111 1112 return IsTupleLike::TupleLike; 1113 } 1114 1115 /// \return std::tuple_element<I, T>::type. 1116 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1117 unsigned I, QualType T) { 1118 // Form template argument list for tuple_element<I, T>. 1119 TemplateArgumentListInfo Args(Loc, Loc); 1120 Args.addArgument( 1121 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1122 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1123 1124 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1125 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1126 if (lookupStdTypeTraitMember( 1127 S, R, Loc, "tuple_element", Args, 1128 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1129 return QualType(); 1130 1131 auto *TD = R.getAsSingle<TypeDecl>(); 1132 if (!TD) { 1133 R.suppressDiagnostics(); 1134 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1135 << printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1136 /*Params*/ nullptr); 1137 if (!R.empty()) 1138 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1139 return QualType(); 1140 } 1141 1142 return S.Context.getTypeDeclType(TD); 1143 } 1144 1145 namespace { 1146 struct InitializingBinding { 1147 Sema &S; 1148 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) { 1149 Sema::CodeSynthesisContext Ctx; 1150 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding; 1151 Ctx.PointOfInstantiation = BD->getLocation(); 1152 Ctx.Entity = BD; 1153 S.pushCodeSynthesisContext(Ctx); 1154 } 1155 ~InitializingBinding() { 1156 S.popCodeSynthesisContext(); 1157 } 1158 }; 1159 } 1160 1161 static bool checkTupleLikeDecomposition(Sema &S, 1162 ArrayRef<BindingDecl *> Bindings, 1163 VarDecl *Src, QualType DecompType, 1164 const llvm::APSInt &TupleSize) { 1165 if ((int64_t)Bindings.size() != TupleSize) { 1166 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1167 << DecompType << (unsigned)Bindings.size() 1168 << (unsigned)TupleSize.getLimitedValue(UINT_MAX) 1169 << TupleSize.toString(10) << (TupleSize < Bindings.size()); 1170 return true; 1171 } 1172 1173 if (Bindings.empty()) 1174 return false; 1175 1176 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1177 1178 // [dcl.decomp]p3: 1179 // The unqualified-id get is looked up in the scope of E by class member 1180 // access lookup ... 1181 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1182 bool UseMemberGet = false; 1183 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1184 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1185 S.LookupQualifiedName(MemberGet, RD); 1186 if (MemberGet.isAmbiguous()) 1187 return true; 1188 // ... and if that finds at least one declaration that is a function 1189 // template whose first template parameter is a non-type parameter ... 1190 for (NamedDecl *D : MemberGet) { 1191 if (FunctionTemplateDecl *FTD = 1192 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1193 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1194 if (TPL->size() != 0 && 1195 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1196 // ... the initializer is e.get<i>(). 1197 UseMemberGet = true; 1198 break; 1199 } 1200 } 1201 } 1202 } 1203 1204 unsigned I = 0; 1205 for (auto *B : Bindings) { 1206 InitializingBinding InitContext(S, B); 1207 SourceLocation Loc = B->getLocation(); 1208 1209 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1210 if (E.isInvalid()) 1211 return true; 1212 1213 // e is an lvalue if the type of the entity is an lvalue reference and 1214 // an xvalue otherwise 1215 if (!Src->getType()->isLValueReferenceType()) 1216 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1217 E.get(), nullptr, VK_XValue, 1218 FPOptionsOverride()); 1219 1220 TemplateArgumentListInfo Args(Loc, Loc); 1221 Args.addArgument( 1222 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1223 1224 if (UseMemberGet) { 1225 // if [lookup of member get] finds at least one declaration, the 1226 // initializer is e.get<i-1>(). 1227 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1228 CXXScopeSpec(), SourceLocation(), nullptr, 1229 MemberGet, &Args, nullptr); 1230 if (E.isInvalid()) 1231 return true; 1232 1233 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1234 } else { 1235 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1236 // in the associated namespaces. 1237 Expr *Get = UnresolvedLookupExpr::Create( 1238 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1239 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1240 UnresolvedSetIterator(), UnresolvedSetIterator()); 1241 1242 Expr *Arg = E.get(); 1243 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1244 } 1245 if (E.isInvalid()) 1246 return true; 1247 Expr *Init = E.get(); 1248 1249 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1250 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1251 if (T.isNull()) 1252 return true; 1253 1254 // each vi is a variable of type "reference to T" initialized with the 1255 // initializer, where the reference is an lvalue reference if the 1256 // initializer is an lvalue and an rvalue reference otherwise 1257 QualType RefType = 1258 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1259 if (RefType.isNull()) 1260 return true; 1261 auto *RefVD = VarDecl::Create( 1262 S.Context, Src->getDeclContext(), Loc, Loc, 1263 B->getDeclName().getAsIdentifierInfo(), RefType, 1264 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1265 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1266 RefVD->setTSCSpec(Src->getTSCSpec()); 1267 RefVD->setImplicit(); 1268 if (Src->isInlineSpecified()) 1269 RefVD->setInlineSpecified(); 1270 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1271 1272 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1273 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1274 InitializationSequence Seq(S, Entity, Kind, Init); 1275 E = Seq.Perform(S, Entity, Kind, Init); 1276 if (E.isInvalid()) 1277 return true; 1278 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1279 if (E.isInvalid()) 1280 return true; 1281 RefVD->setInit(E.get()); 1282 S.CheckCompleteVariableDeclaration(RefVD); 1283 1284 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1285 DeclarationNameInfo(B->getDeclName(), Loc), 1286 RefVD); 1287 if (E.isInvalid()) 1288 return true; 1289 1290 B->setBinding(T, E.get()); 1291 I++; 1292 } 1293 1294 return false; 1295 } 1296 1297 /// Find the base class to decompose in a built-in decomposition of a class type. 1298 /// This base class search is, unfortunately, not quite like any other that we 1299 /// perform anywhere else in C++. 1300 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1301 const CXXRecordDecl *RD, 1302 CXXCastPath &BasePath) { 1303 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1304 CXXBasePath &Path) { 1305 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1306 }; 1307 1308 const CXXRecordDecl *ClassWithFields = nullptr; 1309 AccessSpecifier AS = AS_public; 1310 if (RD->hasDirectFields()) 1311 // [dcl.decomp]p4: 1312 // Otherwise, all of E's non-static data members shall be public direct 1313 // members of E ... 1314 ClassWithFields = RD; 1315 else { 1316 // ... or of ... 1317 CXXBasePaths Paths; 1318 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1319 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1320 // If no classes have fields, just decompose RD itself. (This will work 1321 // if and only if zero bindings were provided.) 1322 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1323 } 1324 1325 CXXBasePath *BestPath = nullptr; 1326 for (auto &P : Paths) { 1327 if (!BestPath) 1328 BestPath = &P; 1329 else if (!S.Context.hasSameType(P.back().Base->getType(), 1330 BestPath->back().Base->getType())) { 1331 // ... the same ... 1332 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1333 << false << RD << BestPath->back().Base->getType() 1334 << P.back().Base->getType(); 1335 return DeclAccessPair(); 1336 } else if (P.Access < BestPath->Access) { 1337 BestPath = &P; 1338 } 1339 } 1340 1341 // ... unambiguous ... 1342 QualType BaseType = BestPath->back().Base->getType(); 1343 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1344 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1345 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1346 return DeclAccessPair(); 1347 } 1348 1349 // ... [accessible, implied by other rules] base class of E. 1350 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1351 *BestPath, diag::err_decomp_decl_inaccessible_base); 1352 AS = BestPath->Access; 1353 1354 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1355 S.BuildBasePathArray(Paths, BasePath); 1356 } 1357 1358 // The above search did not check whether the selected class itself has base 1359 // classes with fields, so check that now. 1360 CXXBasePaths Paths; 1361 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1362 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1363 << (ClassWithFields == RD) << RD << ClassWithFields 1364 << Paths.front().back().Base->getType(); 1365 return DeclAccessPair(); 1366 } 1367 1368 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1369 } 1370 1371 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1372 ValueDecl *Src, QualType DecompType, 1373 const CXXRecordDecl *OrigRD) { 1374 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1375 diag::err_incomplete_type)) 1376 return true; 1377 1378 CXXCastPath BasePath; 1379 DeclAccessPair BasePair = 1380 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1381 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1382 if (!RD) 1383 return true; 1384 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1385 DecompType.getQualifiers()); 1386 1387 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1388 unsigned NumFields = 1389 std::count_if(RD->field_begin(), RD->field_end(), 1390 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1391 assert(Bindings.size() != NumFields); 1392 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1393 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields 1394 << (NumFields < Bindings.size()); 1395 return true; 1396 }; 1397 1398 // all of E's non-static data members shall be [...] well-formed 1399 // when named as e.name in the context of the structured binding, 1400 // E shall not have an anonymous union member, ... 1401 unsigned I = 0; 1402 for (auto *FD : RD->fields()) { 1403 if (FD->isUnnamedBitfield()) 1404 continue; 1405 1406 // All the non-static data members are required to be nameable, so they 1407 // must all have names. 1408 if (!FD->getDeclName()) { 1409 if (RD->isLambda()) { 1410 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda); 1411 S.Diag(RD->getLocation(), diag::note_lambda_decl); 1412 return true; 1413 } 1414 1415 if (FD->isAnonymousStructOrUnion()) { 1416 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1417 << DecompType << FD->getType()->isUnionType(); 1418 S.Diag(FD->getLocation(), diag::note_declared_at); 1419 return true; 1420 } 1421 1422 // FIXME: Are there any other ways we could have an anonymous member? 1423 } 1424 1425 // We have a real field to bind. 1426 if (I >= Bindings.size()) 1427 return DiagnoseBadNumberOfBindings(); 1428 auto *B = Bindings[I++]; 1429 SourceLocation Loc = B->getLocation(); 1430 1431 // The field must be accessible in the context of the structured binding. 1432 // We already checked that the base class is accessible. 1433 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1434 // const_cast here. 1435 S.CheckStructuredBindingMemberAccess( 1436 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1437 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1438 BasePair.getAccess(), FD->getAccess()))); 1439 1440 // Initialize the binding to Src.FD. 1441 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1442 if (E.isInvalid()) 1443 return true; 1444 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1445 VK_LValue, &BasePath); 1446 if (E.isInvalid()) 1447 return true; 1448 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1449 CXXScopeSpec(), FD, 1450 DeclAccessPair::make(FD, FD->getAccess()), 1451 DeclarationNameInfo(FD->getDeclName(), Loc)); 1452 if (E.isInvalid()) 1453 return true; 1454 1455 // If the type of the member is T, the referenced type is cv T, where cv is 1456 // the cv-qualification of the decomposition expression. 1457 // 1458 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1459 // 'const' to the type of the field. 1460 Qualifiers Q = DecompType.getQualifiers(); 1461 if (FD->isMutable()) 1462 Q.removeConst(); 1463 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1464 } 1465 1466 if (I != Bindings.size()) 1467 return DiagnoseBadNumberOfBindings(); 1468 1469 return false; 1470 } 1471 1472 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1473 QualType DecompType = DD->getType(); 1474 1475 // If the type of the decomposition is dependent, then so is the type of 1476 // each binding. 1477 if (DecompType->isDependentType()) { 1478 for (auto *B : DD->bindings()) 1479 B->setType(Context.DependentTy); 1480 return; 1481 } 1482 1483 DecompType = DecompType.getNonReferenceType(); 1484 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1485 1486 // C++1z [dcl.decomp]/2: 1487 // If E is an array type [...] 1488 // As an extension, we also support decomposition of built-in complex and 1489 // vector types. 1490 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1491 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1492 DD->setInvalidDecl(); 1493 return; 1494 } 1495 if (auto *VT = DecompType->getAs<VectorType>()) { 1496 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1497 DD->setInvalidDecl(); 1498 return; 1499 } 1500 if (auto *CT = DecompType->getAs<ComplexType>()) { 1501 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1502 DD->setInvalidDecl(); 1503 return; 1504 } 1505 1506 // C++1z [dcl.decomp]/3: 1507 // if the expression std::tuple_size<E>::value is a well-formed integral 1508 // constant expression, [...] 1509 llvm::APSInt TupleSize(32); 1510 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1511 case IsTupleLike::Error: 1512 DD->setInvalidDecl(); 1513 return; 1514 1515 case IsTupleLike::TupleLike: 1516 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1517 DD->setInvalidDecl(); 1518 return; 1519 1520 case IsTupleLike::NotTupleLike: 1521 break; 1522 } 1523 1524 // C++1z [dcl.dcl]/8: 1525 // [E shall be of array or non-union class type] 1526 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1527 if (!RD || RD->isUnion()) { 1528 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1529 << DD << !RD << DecompType; 1530 DD->setInvalidDecl(); 1531 return; 1532 } 1533 1534 // C++1z [dcl.decomp]/4: 1535 // all of E's non-static data members shall be [...] direct members of 1536 // E or of the same unambiguous public base class of E, ... 1537 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1538 DD->setInvalidDecl(); 1539 } 1540 1541 /// Merge the exception specifications of two variable declarations. 1542 /// 1543 /// This is called when there's a redeclaration of a VarDecl. The function 1544 /// checks if the redeclaration might have an exception specification and 1545 /// validates compatibility and merges the specs if necessary. 1546 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1547 // Shortcut if exceptions are disabled. 1548 if (!getLangOpts().CXXExceptions) 1549 return; 1550 1551 assert(Context.hasSameType(New->getType(), Old->getType()) && 1552 "Should only be called if types are otherwise the same."); 1553 1554 QualType NewType = New->getType(); 1555 QualType OldType = Old->getType(); 1556 1557 // We're only interested in pointers and references to functions, as well 1558 // as pointers to member functions. 1559 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1560 NewType = R->getPointeeType(); 1561 OldType = OldType->castAs<ReferenceType>()->getPointeeType(); 1562 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1563 NewType = P->getPointeeType(); 1564 OldType = OldType->castAs<PointerType>()->getPointeeType(); 1565 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1566 NewType = M->getPointeeType(); 1567 OldType = OldType->castAs<MemberPointerType>()->getPointeeType(); 1568 } 1569 1570 if (!NewType->isFunctionProtoType()) 1571 return; 1572 1573 // There's lots of special cases for functions. For function pointers, system 1574 // libraries are hopefully not as broken so that we don't need these 1575 // workarounds. 1576 if (CheckEquivalentExceptionSpec( 1577 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1578 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1579 New->setInvalidDecl(); 1580 } 1581 } 1582 1583 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1584 /// function declaration are well-formed according to C++ 1585 /// [dcl.fct.default]. 1586 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1587 unsigned NumParams = FD->getNumParams(); 1588 unsigned ParamIdx = 0; 1589 1590 // This checking doesn't make sense for explicit specializations; their 1591 // default arguments are determined by the declaration we're specializing, 1592 // not by FD. 1593 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1594 return; 1595 if (auto *FTD = FD->getDescribedFunctionTemplate()) 1596 if (FTD->isMemberSpecialization()) 1597 return; 1598 1599 // Find first parameter with a default argument 1600 for (; ParamIdx < NumParams; ++ParamIdx) { 1601 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1602 if (Param->hasDefaultArg()) 1603 break; 1604 } 1605 1606 // C++20 [dcl.fct.default]p4: 1607 // In a given function declaration, each parameter subsequent to a parameter 1608 // with a default argument shall have a default argument supplied in this or 1609 // a previous declaration, unless the parameter was expanded from a 1610 // parameter pack, or shall be a function parameter pack. 1611 for (; ParamIdx < NumParams; ++ParamIdx) { 1612 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1613 if (!Param->hasDefaultArg() && !Param->isParameterPack() && 1614 !(CurrentInstantiationScope && 1615 CurrentInstantiationScope->isLocalPackExpansion(Param))) { 1616 if (Param->isInvalidDecl()) 1617 /* We already complained about this parameter. */; 1618 else if (Param->getIdentifier()) 1619 Diag(Param->getLocation(), 1620 diag::err_param_default_argument_missing_name) 1621 << Param->getIdentifier(); 1622 else 1623 Diag(Param->getLocation(), 1624 diag::err_param_default_argument_missing); 1625 } 1626 } 1627 } 1628 1629 /// Check that the given type is a literal type. Issue a diagnostic if not, 1630 /// if Kind is Diagnose. 1631 /// \return \c true if a problem has been found (and optionally diagnosed). 1632 template <typename... Ts> 1633 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1634 SourceLocation Loc, QualType T, unsigned DiagID, 1635 Ts &&...DiagArgs) { 1636 if (T->isDependentType()) 1637 return false; 1638 1639 switch (Kind) { 1640 case Sema::CheckConstexprKind::Diagnose: 1641 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1642 std::forward<Ts>(DiagArgs)...); 1643 1644 case Sema::CheckConstexprKind::CheckValid: 1645 return !T->isLiteralType(SemaRef.Context); 1646 } 1647 1648 llvm_unreachable("unknown CheckConstexprKind"); 1649 } 1650 1651 /// Determine whether a destructor cannot be constexpr due to 1652 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, 1653 const CXXDestructorDecl *DD, 1654 Sema::CheckConstexprKind Kind) { 1655 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { 1656 const CXXRecordDecl *RD = 1657 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1658 if (!RD || RD->hasConstexprDestructor()) 1659 return true; 1660 1661 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1662 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) 1663 << static_cast<int>(DD->getConstexprKind()) << !FD 1664 << (FD ? FD->getDeclName() : DeclarationName()) << T; 1665 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) 1666 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; 1667 } 1668 return false; 1669 }; 1670 1671 const CXXRecordDecl *RD = DD->getParent(); 1672 for (const CXXBaseSpecifier &B : RD->bases()) 1673 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) 1674 return false; 1675 for (const FieldDecl *FD : RD->fields()) 1676 if (!Check(FD->getLocation(), FD->getType(), FD)) 1677 return false; 1678 return true; 1679 } 1680 1681 /// Check whether a function's parameter types are all literal types. If so, 1682 /// return true. If not, produce a suitable diagnostic and return false. 1683 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1684 const FunctionDecl *FD, 1685 Sema::CheckConstexprKind Kind) { 1686 unsigned ArgIndex = 0; 1687 const auto *FT = FD->getType()->castAs<FunctionProtoType>(); 1688 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1689 e = FT->param_type_end(); 1690 i != e; ++i, ++ArgIndex) { 1691 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1692 SourceLocation ParamLoc = PD->getLocation(); 1693 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1694 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1695 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1696 FD->isConsteval())) 1697 return false; 1698 } 1699 return true; 1700 } 1701 1702 /// Check whether a function's return type is a literal type. If so, return 1703 /// true. If not, produce a suitable diagnostic and return false. 1704 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, 1705 Sema::CheckConstexprKind Kind) { 1706 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), 1707 diag::err_constexpr_non_literal_return, 1708 FD->isConsteval())) 1709 return false; 1710 return true; 1711 } 1712 1713 /// Get diagnostic %select index for tag kind for 1714 /// record diagnostic message. 1715 /// WARNING: Indexes apply to particular diagnostics only! 1716 /// 1717 /// \returns diagnostic %select index. 1718 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1719 switch (Tag) { 1720 case TTK_Struct: return 0; 1721 case TTK_Interface: return 1; 1722 case TTK_Class: return 2; 1723 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1724 } 1725 } 1726 1727 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1728 Stmt *Body, 1729 Sema::CheckConstexprKind Kind); 1730 1731 // Check whether a function declaration satisfies the requirements of a 1732 // constexpr function definition or a constexpr constructor definition. If so, 1733 // return true. If not, produce appropriate diagnostics (unless asked not to by 1734 // Kind) and return false. 1735 // 1736 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1737 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1738 CheckConstexprKind Kind) { 1739 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1740 if (MD && MD->isInstance()) { 1741 // C++11 [dcl.constexpr]p4: 1742 // The definition of a constexpr constructor shall satisfy the following 1743 // constraints: 1744 // - the class shall not have any virtual base classes; 1745 // 1746 // FIXME: This only applies to constructors and destructors, not arbitrary 1747 // member functions. 1748 const CXXRecordDecl *RD = MD->getParent(); 1749 if (RD->getNumVBases()) { 1750 if (Kind == CheckConstexprKind::CheckValid) 1751 return false; 1752 1753 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1754 << isa<CXXConstructorDecl>(NewFD) 1755 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1756 for (const auto &I : RD->vbases()) 1757 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1758 << I.getSourceRange(); 1759 return false; 1760 } 1761 } 1762 1763 if (!isa<CXXConstructorDecl>(NewFD)) { 1764 // C++11 [dcl.constexpr]p3: 1765 // The definition of a constexpr function shall satisfy the following 1766 // constraints: 1767 // - it shall not be virtual; (removed in C++20) 1768 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1769 if (Method && Method->isVirtual()) { 1770 if (getLangOpts().CPlusPlus20) { 1771 if (Kind == CheckConstexprKind::Diagnose) 1772 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1773 } else { 1774 if (Kind == CheckConstexprKind::CheckValid) 1775 return false; 1776 1777 Method = Method->getCanonicalDecl(); 1778 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1779 1780 // If it's not obvious why this function is virtual, find an overridden 1781 // function which uses the 'virtual' keyword. 1782 const CXXMethodDecl *WrittenVirtual = Method; 1783 while (!WrittenVirtual->isVirtualAsWritten()) 1784 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1785 if (WrittenVirtual != Method) 1786 Diag(WrittenVirtual->getLocation(), 1787 diag::note_overridden_virtual_function); 1788 return false; 1789 } 1790 } 1791 1792 // - its return type shall be a literal type; 1793 if (!CheckConstexprReturnType(*this, NewFD, Kind)) 1794 return false; 1795 } 1796 1797 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { 1798 // A destructor can be constexpr only if the defaulted destructor could be; 1799 // we don't need to check the members and bases if we already know they all 1800 // have constexpr destructors. 1801 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { 1802 if (Kind == CheckConstexprKind::CheckValid) 1803 return false; 1804 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) 1805 return false; 1806 } 1807 } 1808 1809 // - each of its parameter types shall be a literal type; 1810 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1811 return false; 1812 1813 Stmt *Body = NewFD->getBody(); 1814 assert(Body && 1815 "CheckConstexprFunctionDefinition called on function with no body"); 1816 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1817 } 1818 1819 /// Check the given declaration statement is legal within a constexpr function 1820 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1821 /// 1822 /// \return true if the body is OK (maybe only as an extension), false if we 1823 /// have diagnosed a problem. 1824 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1825 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1826 Sema::CheckConstexprKind Kind) { 1827 // C++11 [dcl.constexpr]p3 and p4: 1828 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1829 // contain only 1830 for (const auto *DclIt : DS->decls()) { 1831 switch (DclIt->getKind()) { 1832 case Decl::StaticAssert: 1833 case Decl::Using: 1834 case Decl::UsingShadow: 1835 case Decl::UsingDirective: 1836 case Decl::UnresolvedUsingTypename: 1837 case Decl::UnresolvedUsingValue: 1838 // - static_assert-declarations 1839 // - using-declarations, 1840 // - using-directives, 1841 continue; 1842 1843 case Decl::Typedef: 1844 case Decl::TypeAlias: { 1845 // - typedef declarations and alias-declarations that do not define 1846 // classes or enumerations, 1847 const auto *TN = cast<TypedefNameDecl>(DclIt); 1848 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1849 // Don't allow variably-modified types in constexpr functions. 1850 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1851 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1852 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1853 << TL.getSourceRange() << TL.getType() 1854 << isa<CXXConstructorDecl>(Dcl); 1855 } 1856 return false; 1857 } 1858 continue; 1859 } 1860 1861 case Decl::Enum: 1862 case Decl::CXXRecord: 1863 // C++1y allows types to be defined, not just declared. 1864 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1865 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1866 SemaRef.Diag(DS->getBeginLoc(), 1867 SemaRef.getLangOpts().CPlusPlus14 1868 ? diag::warn_cxx11_compat_constexpr_type_definition 1869 : diag::ext_constexpr_type_definition) 1870 << isa<CXXConstructorDecl>(Dcl); 1871 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1872 return false; 1873 } 1874 } 1875 continue; 1876 1877 case Decl::EnumConstant: 1878 case Decl::IndirectField: 1879 case Decl::ParmVar: 1880 // These can only appear with other declarations which are banned in 1881 // C++11 and permitted in C++1y, so ignore them. 1882 continue; 1883 1884 case Decl::Var: 1885 case Decl::Decomposition: { 1886 // C++1y [dcl.constexpr]p3 allows anything except: 1887 // a definition of a variable of non-literal type or of static or 1888 // thread storage duration or [before C++2a] for which no 1889 // initialization is performed. 1890 const auto *VD = cast<VarDecl>(DclIt); 1891 if (VD->isThisDeclarationADefinition()) { 1892 if (VD->isStaticLocal()) { 1893 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1894 SemaRef.Diag(VD->getLocation(), 1895 diag::err_constexpr_local_var_static) 1896 << isa<CXXConstructorDecl>(Dcl) 1897 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1898 } 1899 return false; 1900 } 1901 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1902 diag::err_constexpr_local_var_non_literal_type, 1903 isa<CXXConstructorDecl>(Dcl))) 1904 return false; 1905 if (!VD->getType()->isDependentType() && 1906 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1907 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1908 SemaRef.Diag( 1909 VD->getLocation(), 1910 SemaRef.getLangOpts().CPlusPlus20 1911 ? diag::warn_cxx17_compat_constexpr_local_var_no_init 1912 : diag::ext_constexpr_local_var_no_init) 1913 << isa<CXXConstructorDecl>(Dcl); 1914 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1915 return false; 1916 } 1917 continue; 1918 } 1919 } 1920 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1921 SemaRef.Diag(VD->getLocation(), 1922 SemaRef.getLangOpts().CPlusPlus14 1923 ? diag::warn_cxx11_compat_constexpr_local_var 1924 : diag::ext_constexpr_local_var) 1925 << isa<CXXConstructorDecl>(Dcl); 1926 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1927 return false; 1928 } 1929 continue; 1930 } 1931 1932 case Decl::NamespaceAlias: 1933 case Decl::Function: 1934 // These are disallowed in C++11 and permitted in C++1y. Allow them 1935 // everywhere as an extension. 1936 if (!Cxx1yLoc.isValid()) 1937 Cxx1yLoc = DS->getBeginLoc(); 1938 continue; 1939 1940 default: 1941 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1942 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1943 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1944 } 1945 return false; 1946 } 1947 } 1948 1949 return true; 1950 } 1951 1952 /// Check that the given field is initialized within a constexpr constructor. 1953 /// 1954 /// \param Dcl The constexpr constructor being checked. 1955 /// \param Field The field being checked. This may be a member of an anonymous 1956 /// struct or union nested within the class being checked. 1957 /// \param Inits All declarations, including anonymous struct/union members and 1958 /// indirect members, for which any initialization was provided. 1959 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1960 /// multiple notes for different members to the same error. 1961 /// \param Kind Whether we're diagnosing a constructor as written or determining 1962 /// whether the formal requirements are satisfied. 1963 /// \return \c false if we're checking for validity and the constructor does 1964 /// not satisfy the requirements on a constexpr constructor. 1965 static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1966 const FunctionDecl *Dcl, 1967 FieldDecl *Field, 1968 llvm::SmallSet<Decl*, 16> &Inits, 1969 bool &Diagnosed, 1970 Sema::CheckConstexprKind Kind) { 1971 // In C++20 onwards, there's nothing to check for validity. 1972 if (Kind == Sema::CheckConstexprKind::CheckValid && 1973 SemaRef.getLangOpts().CPlusPlus20) 1974 return true; 1975 1976 if (Field->isInvalidDecl()) 1977 return true; 1978 1979 if (Field->isUnnamedBitfield()) 1980 return true; 1981 1982 // Anonymous unions with no variant members and empty anonymous structs do not 1983 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1984 // indirect fields don't need initializing. 1985 if (Field->isAnonymousStructOrUnion() && 1986 (Field->getType()->isUnionType() 1987 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1988 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1989 return true; 1990 1991 if (!Inits.count(Field)) { 1992 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1993 if (!Diagnosed) { 1994 SemaRef.Diag(Dcl->getLocation(), 1995 SemaRef.getLangOpts().CPlusPlus20 1996 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init 1997 : diag::ext_constexpr_ctor_missing_init); 1998 Diagnosed = true; 1999 } 2000 SemaRef.Diag(Field->getLocation(), 2001 diag::note_constexpr_ctor_missing_init); 2002 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2003 return false; 2004 } 2005 } else if (Field->isAnonymousStructOrUnion()) { 2006 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 2007 for (auto *I : RD->fields()) 2008 // If an anonymous union contains an anonymous struct of which any member 2009 // is initialized, all members must be initialized. 2010 if (!RD->isUnion() || Inits.count(I)) 2011 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2012 Kind)) 2013 return false; 2014 } 2015 return true; 2016 } 2017 2018 /// Check the provided statement is allowed in a constexpr function 2019 /// definition. 2020 static bool 2021 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 2022 SmallVectorImpl<SourceLocation> &ReturnStmts, 2023 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 2024 Sema::CheckConstexprKind Kind) { 2025 // - its function-body shall be [...] a compound-statement that contains only 2026 switch (S->getStmtClass()) { 2027 case Stmt::NullStmtClass: 2028 // - null statements, 2029 return true; 2030 2031 case Stmt::DeclStmtClass: 2032 // - static_assert-declarations 2033 // - using-declarations, 2034 // - using-directives, 2035 // - typedef declarations and alias-declarations that do not define 2036 // classes or enumerations, 2037 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 2038 return false; 2039 return true; 2040 2041 case Stmt::ReturnStmtClass: 2042 // - and exactly one return statement; 2043 if (isa<CXXConstructorDecl>(Dcl)) { 2044 // C++1y allows return statements in constexpr constructors. 2045 if (!Cxx1yLoc.isValid()) 2046 Cxx1yLoc = S->getBeginLoc(); 2047 return true; 2048 } 2049 2050 ReturnStmts.push_back(S->getBeginLoc()); 2051 return true; 2052 2053 case Stmt::CompoundStmtClass: { 2054 // C++1y allows compound-statements. 2055 if (!Cxx1yLoc.isValid()) 2056 Cxx1yLoc = S->getBeginLoc(); 2057 2058 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2059 for (auto *BodyIt : CompStmt->body()) { 2060 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2061 Cxx1yLoc, Cxx2aLoc, Kind)) 2062 return false; 2063 } 2064 return true; 2065 } 2066 2067 case Stmt::AttributedStmtClass: 2068 if (!Cxx1yLoc.isValid()) 2069 Cxx1yLoc = S->getBeginLoc(); 2070 return true; 2071 2072 case Stmt::IfStmtClass: { 2073 // C++1y allows if-statements. 2074 if (!Cxx1yLoc.isValid()) 2075 Cxx1yLoc = S->getBeginLoc(); 2076 2077 IfStmt *If = cast<IfStmt>(S); 2078 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2079 Cxx1yLoc, Cxx2aLoc, Kind)) 2080 return false; 2081 if (If->getElse() && 2082 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2083 Cxx1yLoc, Cxx2aLoc, Kind)) 2084 return false; 2085 return true; 2086 } 2087 2088 case Stmt::WhileStmtClass: 2089 case Stmt::DoStmtClass: 2090 case Stmt::ForStmtClass: 2091 case Stmt::CXXForRangeStmtClass: 2092 case Stmt::ContinueStmtClass: 2093 // C++1y allows all of these. We don't allow them as extensions in C++11, 2094 // because they don't make sense without variable mutation. 2095 if (!SemaRef.getLangOpts().CPlusPlus14) 2096 break; 2097 if (!Cxx1yLoc.isValid()) 2098 Cxx1yLoc = S->getBeginLoc(); 2099 for (Stmt *SubStmt : S->children()) 2100 if (SubStmt && 2101 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2102 Cxx1yLoc, Cxx2aLoc, Kind)) 2103 return false; 2104 return true; 2105 2106 case Stmt::SwitchStmtClass: 2107 case Stmt::CaseStmtClass: 2108 case Stmt::DefaultStmtClass: 2109 case Stmt::BreakStmtClass: 2110 // C++1y allows switch-statements, and since they don't need variable 2111 // mutation, we can reasonably allow them in C++11 as an extension. 2112 if (!Cxx1yLoc.isValid()) 2113 Cxx1yLoc = S->getBeginLoc(); 2114 for (Stmt *SubStmt : S->children()) 2115 if (SubStmt && 2116 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2117 Cxx1yLoc, Cxx2aLoc, Kind)) 2118 return false; 2119 return true; 2120 2121 case Stmt::GCCAsmStmtClass: 2122 case Stmt::MSAsmStmtClass: 2123 // C++2a allows inline assembly statements. 2124 case Stmt::CXXTryStmtClass: 2125 if (Cxx2aLoc.isInvalid()) 2126 Cxx2aLoc = S->getBeginLoc(); 2127 for (Stmt *SubStmt : S->children()) { 2128 if (SubStmt && 2129 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2130 Cxx1yLoc, Cxx2aLoc, Kind)) 2131 return false; 2132 } 2133 return true; 2134 2135 case Stmt::CXXCatchStmtClass: 2136 // Do not bother checking the language mode (already covered by the 2137 // try block check). 2138 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2139 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2140 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2141 return false; 2142 return true; 2143 2144 default: 2145 if (!isa<Expr>(S)) 2146 break; 2147 2148 // C++1y allows expression-statements. 2149 if (!Cxx1yLoc.isValid()) 2150 Cxx1yLoc = S->getBeginLoc(); 2151 return true; 2152 } 2153 2154 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2155 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2156 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2157 } 2158 return false; 2159 } 2160 2161 /// Check the body for the given constexpr function declaration only contains 2162 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2163 /// 2164 /// \return true if the body is OK, false if we have found or diagnosed a 2165 /// problem. 2166 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2167 Stmt *Body, 2168 Sema::CheckConstexprKind Kind) { 2169 SmallVector<SourceLocation, 4> ReturnStmts; 2170 2171 if (isa<CXXTryStmt>(Body)) { 2172 // C++11 [dcl.constexpr]p3: 2173 // The definition of a constexpr function shall satisfy the following 2174 // constraints: [...] 2175 // - its function-body shall be = delete, = default, or a 2176 // compound-statement 2177 // 2178 // C++11 [dcl.constexpr]p4: 2179 // In the definition of a constexpr constructor, [...] 2180 // - its function-body shall not be a function-try-block; 2181 // 2182 // This restriction is lifted in C++2a, as long as inner statements also 2183 // apply the general constexpr rules. 2184 switch (Kind) { 2185 case Sema::CheckConstexprKind::CheckValid: 2186 if (!SemaRef.getLangOpts().CPlusPlus20) 2187 return false; 2188 break; 2189 2190 case Sema::CheckConstexprKind::Diagnose: 2191 SemaRef.Diag(Body->getBeginLoc(), 2192 !SemaRef.getLangOpts().CPlusPlus20 2193 ? diag::ext_constexpr_function_try_block_cxx20 2194 : diag::warn_cxx17_compat_constexpr_function_try_block) 2195 << isa<CXXConstructorDecl>(Dcl); 2196 break; 2197 } 2198 } 2199 2200 // - its function-body shall be [...] a compound-statement that contains only 2201 // [... list of cases ...] 2202 // 2203 // Note that walking the children here is enough to properly check for 2204 // CompoundStmt and CXXTryStmt body. 2205 SourceLocation Cxx1yLoc, Cxx2aLoc; 2206 for (Stmt *SubStmt : Body->children()) { 2207 if (SubStmt && 2208 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2209 Cxx1yLoc, Cxx2aLoc, Kind)) 2210 return false; 2211 } 2212 2213 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2214 // If this is only valid as an extension, report that we don't satisfy the 2215 // constraints of the current language. 2216 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) || 2217 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2218 return false; 2219 } else if (Cxx2aLoc.isValid()) { 2220 SemaRef.Diag(Cxx2aLoc, 2221 SemaRef.getLangOpts().CPlusPlus20 2222 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2223 : diag::ext_constexpr_body_invalid_stmt_cxx20) 2224 << isa<CXXConstructorDecl>(Dcl); 2225 } else if (Cxx1yLoc.isValid()) { 2226 SemaRef.Diag(Cxx1yLoc, 2227 SemaRef.getLangOpts().CPlusPlus14 2228 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2229 : diag::ext_constexpr_body_invalid_stmt) 2230 << isa<CXXConstructorDecl>(Dcl); 2231 } 2232 2233 if (const CXXConstructorDecl *Constructor 2234 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2235 const CXXRecordDecl *RD = Constructor->getParent(); 2236 // DR1359: 2237 // - every non-variant non-static data member and base class sub-object 2238 // shall be initialized; 2239 // DR1460: 2240 // - if the class is a union having variant members, exactly one of them 2241 // shall be initialized; 2242 if (RD->isUnion()) { 2243 if (Constructor->getNumCtorInitializers() == 0 && 2244 RD->hasVariantMembers()) { 2245 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2246 SemaRef.Diag( 2247 Dcl->getLocation(), 2248 SemaRef.getLangOpts().CPlusPlus20 2249 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2250 : diag::ext_constexpr_union_ctor_no_init); 2251 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2252 return false; 2253 } 2254 } 2255 } else if (!Constructor->isDependentContext() && 2256 !Constructor->isDelegatingConstructor()) { 2257 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2258 2259 // Skip detailed checking if we have enough initializers, and we would 2260 // allow at most one initializer per member. 2261 bool AnyAnonStructUnionMembers = false; 2262 unsigned Fields = 0; 2263 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2264 E = RD->field_end(); I != E; ++I, ++Fields) { 2265 if (I->isAnonymousStructOrUnion()) { 2266 AnyAnonStructUnionMembers = true; 2267 break; 2268 } 2269 } 2270 // DR1460: 2271 // - if the class is a union-like class, but is not a union, for each of 2272 // its anonymous union members having variant members, exactly one of 2273 // them shall be initialized; 2274 if (AnyAnonStructUnionMembers || 2275 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2276 // Check initialization of non-static data members. Base classes are 2277 // always initialized so do not need to be checked. Dependent bases 2278 // might not have initializers in the member initializer list. 2279 llvm::SmallSet<Decl*, 16> Inits; 2280 for (const auto *I: Constructor->inits()) { 2281 if (FieldDecl *FD = I->getMember()) 2282 Inits.insert(FD); 2283 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2284 Inits.insert(ID->chain_begin(), ID->chain_end()); 2285 } 2286 2287 bool Diagnosed = false; 2288 for (auto *I : RD->fields()) 2289 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2290 Kind)) 2291 return false; 2292 } 2293 } 2294 } else { 2295 if (ReturnStmts.empty()) { 2296 // C++1y doesn't require constexpr functions to contain a 'return' 2297 // statement. We still do, unless the return type might be void, because 2298 // otherwise if there's no return statement, the function cannot 2299 // be used in a core constant expression. 2300 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2301 (Dcl->getReturnType()->isVoidType() || 2302 Dcl->getReturnType()->isDependentType()); 2303 switch (Kind) { 2304 case Sema::CheckConstexprKind::Diagnose: 2305 SemaRef.Diag(Dcl->getLocation(), 2306 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2307 : diag::err_constexpr_body_no_return) 2308 << Dcl->isConsteval(); 2309 if (!OK) 2310 return false; 2311 break; 2312 2313 case Sema::CheckConstexprKind::CheckValid: 2314 // The formal requirements don't include this rule in C++14, even 2315 // though the "must be able to produce a constant expression" rules 2316 // still imply it in some cases. 2317 if (!SemaRef.getLangOpts().CPlusPlus14) 2318 return false; 2319 break; 2320 } 2321 } else if (ReturnStmts.size() > 1) { 2322 switch (Kind) { 2323 case Sema::CheckConstexprKind::Diagnose: 2324 SemaRef.Diag( 2325 ReturnStmts.back(), 2326 SemaRef.getLangOpts().CPlusPlus14 2327 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2328 : diag::ext_constexpr_body_multiple_return); 2329 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2330 SemaRef.Diag(ReturnStmts[I], 2331 diag::note_constexpr_body_previous_return); 2332 break; 2333 2334 case Sema::CheckConstexprKind::CheckValid: 2335 if (!SemaRef.getLangOpts().CPlusPlus14) 2336 return false; 2337 break; 2338 } 2339 } 2340 } 2341 2342 // C++11 [dcl.constexpr]p5: 2343 // if no function argument values exist such that the function invocation 2344 // substitution would produce a constant expression, the program is 2345 // ill-formed; no diagnostic required. 2346 // C++11 [dcl.constexpr]p3: 2347 // - every constructor call and implicit conversion used in initializing the 2348 // return value shall be one of those allowed in a constant expression. 2349 // C++11 [dcl.constexpr]p4: 2350 // - every constructor involved in initializing non-static data members and 2351 // base class sub-objects shall be a constexpr constructor. 2352 // 2353 // Note that this rule is distinct from the "requirements for a constexpr 2354 // function", so is not checked in CheckValid mode. 2355 SmallVector<PartialDiagnosticAt, 8> Diags; 2356 if (Kind == Sema::CheckConstexprKind::Diagnose && 2357 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2358 SemaRef.Diag(Dcl->getLocation(), 2359 diag::ext_constexpr_function_never_constant_expr) 2360 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2361 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2362 SemaRef.Diag(Diags[I].first, Diags[I].second); 2363 // Don't return false here: we allow this for compatibility in 2364 // system headers. 2365 } 2366 2367 return true; 2368 } 2369 2370 /// Get the class that is directly named by the current context. This is the 2371 /// class for which an unqualified-id in this scope could name a constructor 2372 /// or destructor. 2373 /// 2374 /// If the scope specifier denotes a class, this will be that class. 2375 /// If the scope specifier is empty, this will be the class whose 2376 /// member-specification we are currently within. Otherwise, there 2377 /// is no such class. 2378 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2379 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2380 2381 if (SS && SS->isInvalid()) 2382 return nullptr; 2383 2384 if (SS && SS->isNotEmpty()) { 2385 DeclContext *DC = computeDeclContext(*SS, true); 2386 return dyn_cast_or_null<CXXRecordDecl>(DC); 2387 } 2388 2389 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2390 } 2391 2392 /// isCurrentClassName - Determine whether the identifier II is the 2393 /// name of the class type currently being defined. In the case of 2394 /// nested classes, this will only return true if II is the name of 2395 /// the innermost class. 2396 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2397 const CXXScopeSpec *SS) { 2398 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2399 return CurDecl && &II == CurDecl->getIdentifier(); 2400 } 2401 2402 /// Determine whether the identifier II is a typo for the name of 2403 /// the class type currently being defined. If so, update it to the identifier 2404 /// that should have been used. 2405 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2406 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2407 2408 if (!getLangOpts().SpellChecking) 2409 return false; 2410 2411 CXXRecordDecl *CurDecl; 2412 if (SS && SS->isSet() && !SS->isInvalid()) { 2413 DeclContext *DC = computeDeclContext(*SS, true); 2414 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2415 } else 2416 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2417 2418 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2419 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2420 < II->getLength()) { 2421 II = CurDecl->getIdentifier(); 2422 return true; 2423 } 2424 2425 return false; 2426 } 2427 2428 /// Determine whether the given class is a base class of the given 2429 /// class, including looking at dependent bases. 2430 static bool findCircularInheritance(const CXXRecordDecl *Class, 2431 const CXXRecordDecl *Current) { 2432 SmallVector<const CXXRecordDecl*, 8> Queue; 2433 2434 Class = Class->getCanonicalDecl(); 2435 while (true) { 2436 for (const auto &I : Current->bases()) { 2437 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2438 if (!Base) 2439 continue; 2440 2441 Base = Base->getDefinition(); 2442 if (!Base) 2443 continue; 2444 2445 if (Base->getCanonicalDecl() == Class) 2446 return true; 2447 2448 Queue.push_back(Base); 2449 } 2450 2451 if (Queue.empty()) 2452 return false; 2453 2454 Current = Queue.pop_back_val(); 2455 } 2456 2457 return false; 2458 } 2459 2460 /// Check the validity of a C++ base class specifier. 2461 /// 2462 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2463 /// and returns NULL otherwise. 2464 CXXBaseSpecifier * 2465 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2466 SourceRange SpecifierRange, 2467 bool Virtual, AccessSpecifier Access, 2468 TypeSourceInfo *TInfo, 2469 SourceLocation EllipsisLoc) { 2470 QualType BaseType = TInfo->getType(); 2471 if (BaseType->containsErrors()) { 2472 // Already emitted a diagnostic when parsing the error type. 2473 return nullptr; 2474 } 2475 // C++ [class.union]p1: 2476 // A union shall not have base classes. 2477 if (Class->isUnion()) { 2478 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2479 << SpecifierRange; 2480 return nullptr; 2481 } 2482 2483 if (EllipsisLoc.isValid() && 2484 !TInfo->getType()->containsUnexpandedParameterPack()) { 2485 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2486 << TInfo->getTypeLoc().getSourceRange(); 2487 EllipsisLoc = SourceLocation(); 2488 } 2489 2490 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2491 2492 if (BaseType->isDependentType()) { 2493 // Make sure that we don't have circular inheritance among our dependent 2494 // bases. For non-dependent bases, the check for completeness below handles 2495 // this. 2496 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2497 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2498 ((BaseDecl = BaseDecl->getDefinition()) && 2499 findCircularInheritance(Class, BaseDecl))) { 2500 Diag(BaseLoc, diag::err_circular_inheritance) 2501 << BaseType << Context.getTypeDeclType(Class); 2502 2503 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2504 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2505 << BaseType; 2506 2507 return nullptr; 2508 } 2509 } 2510 2511 // Make sure that we don't make an ill-formed AST where the type of the 2512 // Class is non-dependent and its attached base class specifier is an 2513 // dependent type, which violates invariants in many clang code paths (e.g. 2514 // constexpr evaluator). If this case happens (in errory-recovery mode), we 2515 // explicitly mark the Class decl invalid. The diagnostic was already 2516 // emitted. 2517 if (!Class->getTypeForDecl()->isDependentType()) 2518 Class->setInvalidDecl(); 2519 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2520 Class->getTagKind() == TTK_Class, 2521 Access, TInfo, EllipsisLoc); 2522 } 2523 2524 // Base specifiers must be record types. 2525 if (!BaseType->isRecordType()) { 2526 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2527 return nullptr; 2528 } 2529 2530 // C++ [class.union]p1: 2531 // A union shall not be used as a base class. 2532 if (BaseType->isUnionType()) { 2533 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2534 return nullptr; 2535 } 2536 2537 // For the MS ABI, propagate DLL attributes to base class templates. 2538 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2539 if (Attr *ClassAttr = getDLLAttr(Class)) { 2540 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2541 BaseType->getAsCXXRecordDecl())) { 2542 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2543 BaseLoc); 2544 } 2545 } 2546 } 2547 2548 // C++ [class.derived]p2: 2549 // The class-name in a base-specifier shall not be an incompletely 2550 // defined class. 2551 if (RequireCompleteType(BaseLoc, BaseType, 2552 diag::err_incomplete_base_class, SpecifierRange)) { 2553 Class->setInvalidDecl(); 2554 return nullptr; 2555 } 2556 2557 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2558 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2559 assert(BaseDecl && "Record type has no declaration"); 2560 BaseDecl = BaseDecl->getDefinition(); 2561 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2562 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2563 assert(CXXBaseDecl && "Base type is not a C++ type"); 2564 2565 // Microsoft docs say: 2566 // "If a base-class has a code_seg attribute, derived classes must have the 2567 // same attribute." 2568 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2569 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2570 if ((DerivedCSA || BaseCSA) && 2571 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2572 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2573 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2574 << CXXBaseDecl; 2575 return nullptr; 2576 } 2577 2578 // A class which contains a flexible array member is not suitable for use as a 2579 // base class: 2580 // - If the layout determines that a base comes before another base, 2581 // the flexible array member would index into the subsequent base. 2582 // - If the layout determines that base comes before the derived class, 2583 // the flexible array member would index into the derived class. 2584 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2585 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2586 << CXXBaseDecl->getDeclName(); 2587 return nullptr; 2588 } 2589 2590 // C++ [class]p3: 2591 // If a class is marked final and it appears as a base-type-specifier in 2592 // base-clause, the program is ill-formed. 2593 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2594 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2595 << CXXBaseDecl->getDeclName() 2596 << FA->isSpelledAsSealed(); 2597 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2598 << CXXBaseDecl->getDeclName() << FA->getRange(); 2599 return nullptr; 2600 } 2601 2602 if (BaseDecl->isInvalidDecl()) 2603 Class->setInvalidDecl(); 2604 2605 // Create the base specifier. 2606 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2607 Class->getTagKind() == TTK_Class, 2608 Access, TInfo, EllipsisLoc); 2609 } 2610 2611 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2612 /// one entry in the base class list of a class specifier, for 2613 /// example: 2614 /// class foo : public bar, virtual private baz { 2615 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2616 BaseResult 2617 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2618 ParsedAttributes &Attributes, 2619 bool Virtual, AccessSpecifier Access, 2620 ParsedType basetype, SourceLocation BaseLoc, 2621 SourceLocation EllipsisLoc) { 2622 if (!classdecl) 2623 return true; 2624 2625 AdjustDeclIfTemplate(classdecl); 2626 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2627 if (!Class) 2628 return true; 2629 2630 // We haven't yet attached the base specifiers. 2631 Class->setIsParsingBaseSpecifiers(); 2632 2633 // We do not support any C++11 attributes on base-specifiers yet. 2634 // Diagnose any attributes we see. 2635 for (const ParsedAttr &AL : Attributes) { 2636 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2637 continue; 2638 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2639 ? (unsigned)diag::warn_unknown_attribute_ignored 2640 : (unsigned)diag::err_base_specifier_attribute) 2641 << AL << AL.getRange(); 2642 } 2643 2644 TypeSourceInfo *TInfo = nullptr; 2645 GetTypeFromParser(basetype, &TInfo); 2646 2647 if (EllipsisLoc.isInvalid() && 2648 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2649 UPPC_BaseType)) 2650 return true; 2651 2652 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2653 Virtual, Access, TInfo, 2654 EllipsisLoc)) 2655 return BaseSpec; 2656 else 2657 Class->setInvalidDecl(); 2658 2659 return true; 2660 } 2661 2662 /// Use small set to collect indirect bases. As this is only used 2663 /// locally, there's no need to abstract the small size parameter. 2664 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2665 2666 /// Recursively add the bases of Type. Don't add Type itself. 2667 static void 2668 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2669 const QualType &Type) 2670 { 2671 // Even though the incoming type is a base, it might not be 2672 // a class -- it could be a template parm, for instance. 2673 if (auto Rec = Type->getAs<RecordType>()) { 2674 auto Decl = Rec->getAsCXXRecordDecl(); 2675 2676 // Iterate over its bases. 2677 for (const auto &BaseSpec : Decl->bases()) { 2678 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2679 .getUnqualifiedType(); 2680 if (Set.insert(Base).second) 2681 // If we've not already seen it, recurse. 2682 NoteIndirectBases(Context, Set, Base); 2683 } 2684 } 2685 } 2686 2687 /// Performs the actual work of attaching the given base class 2688 /// specifiers to a C++ class. 2689 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2690 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2691 if (Bases.empty()) 2692 return false; 2693 2694 // Used to keep track of which base types we have already seen, so 2695 // that we can properly diagnose redundant direct base types. Note 2696 // that the key is always the unqualified canonical type of the base 2697 // class. 2698 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2699 2700 // Used to track indirect bases so we can see if a direct base is 2701 // ambiguous. 2702 IndirectBaseSet IndirectBaseTypes; 2703 2704 // Copy non-redundant base specifiers into permanent storage. 2705 unsigned NumGoodBases = 0; 2706 bool Invalid = false; 2707 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2708 QualType NewBaseType 2709 = Context.getCanonicalType(Bases[idx]->getType()); 2710 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2711 2712 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2713 if (KnownBase) { 2714 // C++ [class.mi]p3: 2715 // A class shall not be specified as a direct base class of a 2716 // derived class more than once. 2717 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2718 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2719 2720 // Delete the duplicate base class specifier; we're going to 2721 // overwrite its pointer later. 2722 Context.Deallocate(Bases[idx]); 2723 2724 Invalid = true; 2725 } else { 2726 // Okay, add this new base class. 2727 KnownBase = Bases[idx]; 2728 Bases[NumGoodBases++] = Bases[idx]; 2729 2730 // Note this base's direct & indirect bases, if there could be ambiguity. 2731 if (Bases.size() > 1) 2732 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2733 2734 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2735 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2736 if (Class->isInterface() && 2737 (!RD->isInterfaceLike() || 2738 KnownBase->getAccessSpecifier() != AS_public)) { 2739 // The Microsoft extension __interface does not permit bases that 2740 // are not themselves public interfaces. 2741 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2742 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2743 << RD->getSourceRange(); 2744 Invalid = true; 2745 } 2746 if (RD->hasAttr<WeakAttr>()) 2747 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2748 } 2749 } 2750 } 2751 2752 // Attach the remaining base class specifiers to the derived class. 2753 Class->setBases(Bases.data(), NumGoodBases); 2754 2755 // Check that the only base classes that are duplicate are virtual. 2756 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2757 // Check whether this direct base is inaccessible due to ambiguity. 2758 QualType BaseType = Bases[idx]->getType(); 2759 2760 // Skip all dependent types in templates being used as base specifiers. 2761 // Checks below assume that the base specifier is a CXXRecord. 2762 if (BaseType->isDependentType()) 2763 continue; 2764 2765 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2766 .getUnqualifiedType(); 2767 2768 if (IndirectBaseTypes.count(CanonicalBase)) { 2769 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2770 /*DetectVirtual=*/true); 2771 bool found 2772 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2773 assert(found); 2774 (void)found; 2775 2776 if (Paths.isAmbiguous(CanonicalBase)) 2777 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2778 << BaseType << getAmbiguousPathsDisplayString(Paths) 2779 << Bases[idx]->getSourceRange(); 2780 else 2781 assert(Bases[idx]->isVirtual()); 2782 } 2783 2784 // Delete the base class specifier, since its data has been copied 2785 // into the CXXRecordDecl. 2786 Context.Deallocate(Bases[idx]); 2787 } 2788 2789 return Invalid; 2790 } 2791 2792 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2793 /// class, after checking whether there are any duplicate base 2794 /// classes. 2795 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2796 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2797 if (!ClassDecl || Bases.empty()) 2798 return; 2799 2800 AdjustDeclIfTemplate(ClassDecl); 2801 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2802 } 2803 2804 /// Determine whether the type \p Derived is a C++ class that is 2805 /// derived from the type \p Base. 2806 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2807 if (!getLangOpts().CPlusPlus) 2808 return false; 2809 2810 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2811 if (!DerivedRD) 2812 return false; 2813 2814 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2815 if (!BaseRD) 2816 return false; 2817 2818 // If either the base or the derived type is invalid, don't try to 2819 // check whether one is derived from the other. 2820 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2821 return false; 2822 2823 // FIXME: In a modules build, do we need the entire path to be visible for us 2824 // to be able to use the inheritance relationship? 2825 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2826 return false; 2827 2828 return DerivedRD->isDerivedFrom(BaseRD); 2829 } 2830 2831 /// Determine whether the type \p Derived is a C++ class that is 2832 /// derived from the type \p Base. 2833 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2834 CXXBasePaths &Paths) { 2835 if (!getLangOpts().CPlusPlus) 2836 return false; 2837 2838 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2839 if (!DerivedRD) 2840 return false; 2841 2842 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2843 if (!BaseRD) 2844 return false; 2845 2846 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2847 return false; 2848 2849 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2850 } 2851 2852 static void BuildBasePathArray(const CXXBasePath &Path, 2853 CXXCastPath &BasePathArray) { 2854 // We first go backward and check if we have a virtual base. 2855 // FIXME: It would be better if CXXBasePath had the base specifier for 2856 // the nearest virtual base. 2857 unsigned Start = 0; 2858 for (unsigned I = Path.size(); I != 0; --I) { 2859 if (Path[I - 1].Base->isVirtual()) { 2860 Start = I - 1; 2861 break; 2862 } 2863 } 2864 2865 // Now add all bases. 2866 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2867 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2868 } 2869 2870 2871 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2872 CXXCastPath &BasePathArray) { 2873 assert(BasePathArray.empty() && "Base path array must be empty!"); 2874 assert(Paths.isRecordingPaths() && "Must record paths!"); 2875 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2876 } 2877 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2878 /// conversion (where Derived and Base are class types) is 2879 /// well-formed, meaning that the conversion is unambiguous (and 2880 /// that all of the base classes are accessible). Returns true 2881 /// and emits a diagnostic if the code is ill-formed, returns false 2882 /// otherwise. Loc is the location where this routine should point to 2883 /// if there is an error, and Range is the source range to highlight 2884 /// if there is an error. 2885 /// 2886 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the 2887 /// diagnostic for the respective type of error will be suppressed, but the 2888 /// check for ill-formed code will still be performed. 2889 bool 2890 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2891 unsigned InaccessibleBaseID, 2892 unsigned AmbiguousBaseConvID, 2893 SourceLocation Loc, SourceRange Range, 2894 DeclarationName Name, 2895 CXXCastPath *BasePath, 2896 bool IgnoreAccess) { 2897 // First, determine whether the path from Derived to Base is 2898 // ambiguous. This is slightly more expensive than checking whether 2899 // the Derived to Base conversion exists, because here we need to 2900 // explore multiple paths to determine if there is an ambiguity. 2901 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2902 /*DetectVirtual=*/false); 2903 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2904 if (!DerivationOkay) 2905 return true; 2906 2907 const CXXBasePath *Path = nullptr; 2908 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2909 Path = &Paths.front(); 2910 2911 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2912 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2913 // user to access such bases. 2914 if (!Path && getLangOpts().MSVCCompat) { 2915 for (const CXXBasePath &PossiblePath : Paths) { 2916 if (PossiblePath.size() == 1) { 2917 Path = &PossiblePath; 2918 if (AmbiguousBaseConvID) 2919 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2920 << Base << Derived << Range; 2921 break; 2922 } 2923 } 2924 } 2925 2926 if (Path) { 2927 if (!IgnoreAccess) { 2928 // Check that the base class can be accessed. 2929 switch ( 2930 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2931 case AR_inaccessible: 2932 return true; 2933 case AR_accessible: 2934 case AR_dependent: 2935 case AR_delayed: 2936 break; 2937 } 2938 } 2939 2940 // Build a base path if necessary. 2941 if (BasePath) 2942 ::BuildBasePathArray(*Path, *BasePath); 2943 return false; 2944 } 2945 2946 if (AmbiguousBaseConvID) { 2947 // We know that the derived-to-base conversion is ambiguous, and 2948 // we're going to produce a diagnostic. Perform the derived-to-base 2949 // search just one more time to compute all of the possible paths so 2950 // that we can print them out. This is more expensive than any of 2951 // the previous derived-to-base checks we've done, but at this point 2952 // performance isn't as much of an issue. 2953 Paths.clear(); 2954 Paths.setRecordingPaths(true); 2955 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2956 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2957 (void)StillOkay; 2958 2959 // Build up a textual representation of the ambiguous paths, e.g., 2960 // D -> B -> A, that will be used to illustrate the ambiguous 2961 // conversions in the diagnostic. We only print one of the paths 2962 // to each base class subobject. 2963 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2964 2965 Diag(Loc, AmbiguousBaseConvID) 2966 << Derived << Base << PathDisplayStr << Range << Name; 2967 } 2968 return true; 2969 } 2970 2971 bool 2972 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2973 SourceLocation Loc, SourceRange Range, 2974 CXXCastPath *BasePath, 2975 bool IgnoreAccess) { 2976 return CheckDerivedToBaseConversion( 2977 Derived, Base, diag::err_upcast_to_inaccessible_base, 2978 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2979 BasePath, IgnoreAccess); 2980 } 2981 2982 2983 /// Builds a string representing ambiguous paths from a 2984 /// specific derived class to different subobjects of the same base 2985 /// class. 2986 /// 2987 /// This function builds a string that can be used in error messages 2988 /// to show the different paths that one can take through the 2989 /// inheritance hierarchy to go from the derived class to different 2990 /// subobjects of a base class. The result looks something like this: 2991 /// @code 2992 /// struct D -> struct B -> struct A 2993 /// struct D -> struct C -> struct A 2994 /// @endcode 2995 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2996 std::string PathDisplayStr; 2997 std::set<unsigned> DisplayedPaths; 2998 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2999 Path != Paths.end(); ++Path) { 3000 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 3001 // We haven't displayed a path to this particular base 3002 // class subobject yet. 3003 PathDisplayStr += "\n "; 3004 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 3005 for (CXXBasePath::const_iterator Element = Path->begin(); 3006 Element != Path->end(); ++Element) 3007 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 3008 } 3009 } 3010 3011 return PathDisplayStr; 3012 } 3013 3014 //===----------------------------------------------------------------------===// 3015 // C++ class member Handling 3016 //===----------------------------------------------------------------------===// 3017 3018 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 3019 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 3020 SourceLocation ColonLoc, 3021 const ParsedAttributesView &Attrs) { 3022 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 3023 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 3024 ASLoc, ColonLoc); 3025 CurContext->addHiddenDecl(ASDecl); 3026 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 3027 } 3028 3029 /// CheckOverrideControl - Check C++11 override control semantics. 3030 void Sema::CheckOverrideControl(NamedDecl *D) { 3031 if (D->isInvalidDecl()) 3032 return; 3033 3034 // We only care about "override" and "final" declarations. 3035 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 3036 return; 3037 3038 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3039 3040 // We can't check dependent instance methods. 3041 if (MD && MD->isInstance() && 3042 (MD->getParent()->hasAnyDependentBases() || 3043 MD->getType()->isDependentType())) 3044 return; 3045 3046 if (MD && !MD->isVirtual()) { 3047 // If we have a non-virtual method, check if if hides a virtual method. 3048 // (In that case, it's most likely the method has the wrong type.) 3049 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 3050 FindHiddenVirtualMethods(MD, OverloadedMethods); 3051 3052 if (!OverloadedMethods.empty()) { 3053 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3054 Diag(OA->getLocation(), 3055 diag::override_keyword_hides_virtual_member_function) 3056 << "override" << (OverloadedMethods.size() > 1); 3057 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3058 Diag(FA->getLocation(), 3059 diag::override_keyword_hides_virtual_member_function) 3060 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3061 << (OverloadedMethods.size() > 1); 3062 } 3063 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3064 MD->setInvalidDecl(); 3065 return; 3066 } 3067 // Fall through into the general case diagnostic. 3068 // FIXME: We might want to attempt typo correction here. 3069 } 3070 3071 if (!MD || !MD->isVirtual()) { 3072 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3073 Diag(OA->getLocation(), 3074 diag::override_keyword_only_allowed_on_virtual_member_functions) 3075 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3076 D->dropAttr<OverrideAttr>(); 3077 } 3078 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3079 Diag(FA->getLocation(), 3080 diag::override_keyword_only_allowed_on_virtual_member_functions) 3081 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3082 << FixItHint::CreateRemoval(FA->getLocation()); 3083 D->dropAttr<FinalAttr>(); 3084 } 3085 return; 3086 } 3087 3088 // C++11 [class.virtual]p5: 3089 // If a function is marked with the virt-specifier override and 3090 // does not override a member function of a base class, the program is 3091 // ill-formed. 3092 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3093 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3094 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3095 << MD->getDeclName(); 3096 } 3097 3098 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { 3099 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3100 return; 3101 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3102 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3103 return; 3104 3105 SourceLocation Loc = MD->getLocation(); 3106 SourceLocation SpellingLoc = Loc; 3107 if (getSourceManager().isMacroArgExpansion(Loc)) 3108 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3109 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3110 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3111 return; 3112 3113 if (MD->size_overridden_methods() > 0) { 3114 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { 3115 unsigned DiagID = 3116 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation()) 3117 ? DiagInconsistent 3118 : DiagSuggest; 3119 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3120 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3121 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3122 }; 3123 if (isa<CXXDestructorDecl>(MD)) 3124 EmitDiag( 3125 diag::warn_inconsistent_destructor_marked_not_override_overriding, 3126 diag::warn_suggest_destructor_marked_not_override_overriding); 3127 else 3128 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding, 3129 diag::warn_suggest_function_marked_not_override_overriding); 3130 } 3131 } 3132 3133 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3134 /// function overrides a virtual member function marked 'final', according to 3135 /// C++11 [class.virtual]p4. 3136 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3137 const CXXMethodDecl *Old) { 3138 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3139 if (!FA) 3140 return false; 3141 3142 Diag(New->getLocation(), diag::err_final_function_overridden) 3143 << New->getDeclName() 3144 << FA->isSpelledAsSealed(); 3145 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3146 return true; 3147 } 3148 3149 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3150 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3151 // FIXME: Destruction of ObjC lifetime types has side-effects. 3152 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3153 return !RD->isCompleteDefinition() || 3154 !RD->hasTrivialDefaultConstructor() || 3155 !RD->hasTrivialDestructor(); 3156 return false; 3157 } 3158 3159 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3160 ParsedAttributesView::const_iterator Itr = 3161 llvm::find_if(list, [](const ParsedAttr &AL) { 3162 return AL.isDeclspecPropertyAttribute(); 3163 }); 3164 if (Itr != list.end()) 3165 return &*Itr; 3166 return nullptr; 3167 } 3168 3169 // Check if there is a field shadowing. 3170 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3171 DeclarationName FieldName, 3172 const CXXRecordDecl *RD, 3173 bool DeclIsField) { 3174 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3175 return; 3176 3177 // To record a shadowed field in a base 3178 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3179 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3180 CXXBasePath &Path) { 3181 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3182 // Record an ambiguous path directly 3183 if (Bases.find(Base) != Bases.end()) 3184 return true; 3185 for (const auto Field : Base->lookup(FieldName)) { 3186 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3187 Field->getAccess() != AS_private) { 3188 assert(Field->getAccess() != AS_none); 3189 assert(Bases.find(Base) == Bases.end()); 3190 Bases[Base] = Field; 3191 return true; 3192 } 3193 } 3194 return false; 3195 }; 3196 3197 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3198 /*DetectVirtual=*/true); 3199 if (!RD->lookupInBases(FieldShadowed, Paths)) 3200 return; 3201 3202 for (const auto &P : Paths) { 3203 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3204 auto It = Bases.find(Base); 3205 // Skip duplicated bases 3206 if (It == Bases.end()) 3207 continue; 3208 auto BaseField = It->second; 3209 assert(BaseField->getAccess() != AS_private); 3210 if (AS_none != 3211 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3212 Diag(Loc, diag::warn_shadow_field) 3213 << FieldName << RD << Base << DeclIsField; 3214 Diag(BaseField->getLocation(), diag::note_shadow_field); 3215 Bases.erase(It); 3216 } 3217 } 3218 } 3219 3220 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3221 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3222 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3223 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3224 /// present (but parsing it has been deferred). 3225 NamedDecl * 3226 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3227 MultiTemplateParamsArg TemplateParameterLists, 3228 Expr *BW, const VirtSpecifiers &VS, 3229 InClassInitStyle InitStyle) { 3230 const DeclSpec &DS = D.getDeclSpec(); 3231 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3232 DeclarationName Name = NameInfo.getName(); 3233 SourceLocation Loc = NameInfo.getLoc(); 3234 3235 // For anonymous bitfields, the location should point to the type. 3236 if (Loc.isInvalid()) 3237 Loc = D.getBeginLoc(); 3238 3239 Expr *BitWidth = static_cast<Expr*>(BW); 3240 3241 assert(isa<CXXRecordDecl>(CurContext)); 3242 assert(!DS.isFriendSpecified()); 3243 3244 bool isFunc = D.isDeclarationOfFunction(); 3245 const ParsedAttr *MSPropertyAttr = 3246 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3247 3248 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3249 // The Microsoft extension __interface only permits public member functions 3250 // and prohibits constructors, destructors, operators, non-public member 3251 // functions, static methods and data members. 3252 unsigned InvalidDecl; 3253 bool ShowDeclName = true; 3254 if (!isFunc && 3255 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3256 InvalidDecl = 0; 3257 else if (!isFunc) 3258 InvalidDecl = 1; 3259 else if (AS != AS_public) 3260 InvalidDecl = 2; 3261 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3262 InvalidDecl = 3; 3263 else switch (Name.getNameKind()) { 3264 case DeclarationName::CXXConstructorName: 3265 InvalidDecl = 4; 3266 ShowDeclName = false; 3267 break; 3268 3269 case DeclarationName::CXXDestructorName: 3270 InvalidDecl = 5; 3271 ShowDeclName = false; 3272 break; 3273 3274 case DeclarationName::CXXOperatorName: 3275 case DeclarationName::CXXConversionFunctionName: 3276 InvalidDecl = 6; 3277 break; 3278 3279 default: 3280 InvalidDecl = 0; 3281 break; 3282 } 3283 3284 if (InvalidDecl) { 3285 if (ShowDeclName) 3286 Diag(Loc, diag::err_invalid_member_in_interface) 3287 << (InvalidDecl-1) << Name; 3288 else 3289 Diag(Loc, diag::err_invalid_member_in_interface) 3290 << (InvalidDecl-1) << ""; 3291 return nullptr; 3292 } 3293 } 3294 3295 // C++ 9.2p6: A member shall not be declared to have automatic storage 3296 // duration (auto, register) or with the extern storage-class-specifier. 3297 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3298 // data members and cannot be applied to names declared const or static, 3299 // and cannot be applied to reference members. 3300 switch (DS.getStorageClassSpec()) { 3301 case DeclSpec::SCS_unspecified: 3302 case DeclSpec::SCS_typedef: 3303 case DeclSpec::SCS_static: 3304 break; 3305 case DeclSpec::SCS_mutable: 3306 if (isFunc) { 3307 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3308 3309 // FIXME: It would be nicer if the keyword was ignored only for this 3310 // declarator. Otherwise we could get follow-up errors. 3311 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3312 } 3313 break; 3314 default: 3315 Diag(DS.getStorageClassSpecLoc(), 3316 diag::err_storageclass_invalid_for_member); 3317 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3318 break; 3319 } 3320 3321 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3322 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3323 !isFunc); 3324 3325 if (DS.hasConstexprSpecifier() && isInstField) { 3326 SemaDiagnosticBuilder B = 3327 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3328 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3329 if (InitStyle == ICIS_NoInit) { 3330 B << 0 << 0; 3331 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3332 B << FixItHint::CreateRemoval(ConstexprLoc); 3333 else { 3334 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3335 D.getMutableDeclSpec().ClearConstexprSpec(); 3336 const char *PrevSpec; 3337 unsigned DiagID; 3338 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3339 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3340 (void)Failed; 3341 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3342 } 3343 } else { 3344 B << 1; 3345 const char *PrevSpec; 3346 unsigned DiagID; 3347 if (D.getMutableDeclSpec().SetStorageClassSpec( 3348 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3349 Context.getPrintingPolicy())) { 3350 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3351 "This is the only DeclSpec that should fail to be applied"); 3352 B << 1; 3353 } else { 3354 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3355 isInstField = false; 3356 } 3357 } 3358 } 3359 3360 NamedDecl *Member; 3361 if (isInstField) { 3362 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3363 3364 // Data members must have identifiers for names. 3365 if (!Name.isIdentifier()) { 3366 Diag(Loc, diag::err_bad_variable_name) 3367 << Name; 3368 return nullptr; 3369 } 3370 3371 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3372 3373 // Member field could not be with "template" keyword. 3374 // So TemplateParameterLists should be empty in this case. 3375 if (TemplateParameterLists.size()) { 3376 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3377 if (TemplateParams->size()) { 3378 // There is no such thing as a member field template. 3379 Diag(D.getIdentifierLoc(), diag::err_template_member) 3380 << II 3381 << SourceRange(TemplateParams->getTemplateLoc(), 3382 TemplateParams->getRAngleLoc()); 3383 } else { 3384 // There is an extraneous 'template<>' for this member. 3385 Diag(TemplateParams->getTemplateLoc(), 3386 diag::err_template_member_noparams) 3387 << II 3388 << SourceRange(TemplateParams->getTemplateLoc(), 3389 TemplateParams->getRAngleLoc()); 3390 } 3391 return nullptr; 3392 } 3393 3394 if (SS.isSet() && !SS.isInvalid()) { 3395 // The user provided a superfluous scope specifier inside a class 3396 // definition: 3397 // 3398 // class X { 3399 // int X::member; 3400 // }; 3401 if (DeclContext *DC = computeDeclContext(SS, false)) 3402 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3403 D.getName().getKind() == 3404 UnqualifiedIdKind::IK_TemplateId); 3405 else 3406 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3407 << Name << SS.getRange(); 3408 3409 SS.clear(); 3410 } 3411 3412 if (MSPropertyAttr) { 3413 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3414 BitWidth, InitStyle, AS, *MSPropertyAttr); 3415 if (!Member) 3416 return nullptr; 3417 isInstField = false; 3418 } else { 3419 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3420 BitWidth, InitStyle, AS); 3421 if (!Member) 3422 return nullptr; 3423 } 3424 3425 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3426 } else { 3427 Member = HandleDeclarator(S, D, TemplateParameterLists); 3428 if (!Member) 3429 return nullptr; 3430 3431 // Non-instance-fields can't have a bitfield. 3432 if (BitWidth) { 3433 if (Member->isInvalidDecl()) { 3434 // don't emit another diagnostic. 3435 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3436 // C++ 9.6p3: A bit-field shall not be a static member. 3437 // "static member 'A' cannot be a bit-field" 3438 Diag(Loc, diag::err_static_not_bitfield) 3439 << Name << BitWidth->getSourceRange(); 3440 } else if (isa<TypedefDecl>(Member)) { 3441 // "typedef member 'x' cannot be a bit-field" 3442 Diag(Loc, diag::err_typedef_not_bitfield) 3443 << Name << BitWidth->getSourceRange(); 3444 } else { 3445 // A function typedef ("typedef int f(); f a;"). 3446 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3447 Diag(Loc, diag::err_not_integral_type_bitfield) 3448 << Name << cast<ValueDecl>(Member)->getType() 3449 << BitWidth->getSourceRange(); 3450 } 3451 3452 BitWidth = nullptr; 3453 Member->setInvalidDecl(); 3454 } 3455 3456 NamedDecl *NonTemplateMember = Member; 3457 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3458 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3459 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3460 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3461 3462 Member->setAccess(AS); 3463 3464 // If we have declared a member function template or static data member 3465 // template, set the access of the templated declaration as well. 3466 if (NonTemplateMember != Member) 3467 NonTemplateMember->setAccess(AS); 3468 3469 // C++ [temp.deduct.guide]p3: 3470 // A deduction guide [...] for a member class template [shall be 3471 // declared] with the same access [as the template]. 3472 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3473 auto *TD = DG->getDeducedTemplate(); 3474 // Access specifiers are only meaningful if both the template and the 3475 // deduction guide are from the same scope. 3476 if (AS != TD->getAccess() && 3477 TD->getDeclContext()->getRedeclContext()->Equals( 3478 DG->getDeclContext()->getRedeclContext())) { 3479 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3480 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3481 << TD->getAccess(); 3482 const AccessSpecDecl *LastAccessSpec = nullptr; 3483 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3484 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3485 LastAccessSpec = AccessSpec; 3486 } 3487 assert(LastAccessSpec && "differing access with no access specifier"); 3488 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3489 << AS; 3490 } 3491 } 3492 } 3493 3494 if (VS.isOverrideSpecified()) 3495 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3496 AttributeCommonInfo::AS_Keyword)); 3497 if (VS.isFinalSpecified()) 3498 Member->addAttr(FinalAttr::Create( 3499 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3500 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3501 3502 if (VS.getLastLocation().isValid()) { 3503 // Update the end location of a method that has a virt-specifiers. 3504 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3505 MD->setRangeEnd(VS.getLastLocation()); 3506 } 3507 3508 CheckOverrideControl(Member); 3509 3510 assert((Name || isInstField) && "No identifier for non-field ?"); 3511 3512 if (isInstField) { 3513 FieldDecl *FD = cast<FieldDecl>(Member); 3514 FieldCollector->Add(FD); 3515 3516 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3517 // Remember all explicit private FieldDecls that have a name, no side 3518 // effects and are not part of a dependent type declaration. 3519 if (!FD->isImplicit() && FD->getDeclName() && 3520 FD->getAccess() == AS_private && 3521 !FD->hasAttr<UnusedAttr>() && 3522 !FD->getParent()->isDependentContext() && 3523 !InitializationHasSideEffects(*FD)) 3524 UnusedPrivateFields.insert(FD); 3525 } 3526 } 3527 3528 return Member; 3529 } 3530 3531 namespace { 3532 class UninitializedFieldVisitor 3533 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3534 Sema &S; 3535 // List of Decls to generate a warning on. Also remove Decls that become 3536 // initialized. 3537 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3538 // List of base classes of the record. Classes are removed after their 3539 // initializers. 3540 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3541 // Vector of decls to be removed from the Decl set prior to visiting the 3542 // nodes. These Decls may have been initialized in the prior initializer. 3543 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3544 // If non-null, add a note to the warning pointing back to the constructor. 3545 const CXXConstructorDecl *Constructor; 3546 // Variables to hold state when processing an initializer list. When 3547 // InitList is true, special case initialization of FieldDecls matching 3548 // InitListFieldDecl. 3549 bool InitList; 3550 FieldDecl *InitListFieldDecl; 3551 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3552 3553 public: 3554 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3555 UninitializedFieldVisitor(Sema &S, 3556 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3557 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3558 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3559 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3560 3561 // Returns true if the use of ME is not an uninitialized use. 3562 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3563 bool CheckReferenceOnly) { 3564 llvm::SmallVector<FieldDecl*, 4> Fields; 3565 bool ReferenceField = false; 3566 while (ME) { 3567 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3568 if (!FD) 3569 return false; 3570 Fields.push_back(FD); 3571 if (FD->getType()->isReferenceType()) 3572 ReferenceField = true; 3573 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3574 } 3575 3576 // Binding a reference to an uninitialized field is not an 3577 // uninitialized use. 3578 if (CheckReferenceOnly && !ReferenceField) 3579 return true; 3580 3581 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3582 // Discard the first field since it is the field decl that is being 3583 // initialized. 3584 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3585 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3586 } 3587 3588 for (auto UsedIter = UsedFieldIndex.begin(), 3589 UsedEnd = UsedFieldIndex.end(), 3590 OrigIter = InitFieldIndex.begin(), 3591 OrigEnd = InitFieldIndex.end(); 3592 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3593 if (*UsedIter < *OrigIter) 3594 return true; 3595 if (*UsedIter > *OrigIter) 3596 break; 3597 } 3598 3599 return false; 3600 } 3601 3602 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3603 bool AddressOf) { 3604 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3605 return; 3606 3607 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3608 // or union. 3609 MemberExpr *FieldME = ME; 3610 3611 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3612 3613 Expr *Base = ME; 3614 while (MemberExpr *SubME = 3615 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3616 3617 if (isa<VarDecl>(SubME->getMemberDecl())) 3618 return; 3619 3620 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3621 if (!FD->isAnonymousStructOrUnion()) 3622 FieldME = SubME; 3623 3624 if (!FieldME->getType().isPODType(S.Context)) 3625 AllPODFields = false; 3626 3627 Base = SubME->getBase(); 3628 } 3629 3630 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) { 3631 Visit(Base); 3632 return; 3633 } 3634 3635 if (AddressOf && AllPODFields) 3636 return; 3637 3638 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3639 3640 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3641 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3642 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3643 } 3644 3645 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3646 QualType T = BaseCast->getType(); 3647 if (T->isPointerType() && 3648 BaseClasses.count(T->getPointeeType())) { 3649 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3650 << T->getPointeeType() << FoundVD; 3651 } 3652 } 3653 } 3654 3655 if (!Decls.count(FoundVD)) 3656 return; 3657 3658 const bool IsReference = FoundVD->getType()->isReferenceType(); 3659 3660 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3661 // Special checking for initializer lists. 3662 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3663 return; 3664 } 3665 } else { 3666 // Prevent double warnings on use of unbounded references. 3667 if (CheckReferenceOnly && !IsReference) 3668 return; 3669 } 3670 3671 unsigned diag = IsReference 3672 ? diag::warn_reference_field_is_uninit 3673 : diag::warn_field_is_uninit; 3674 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3675 if (Constructor) 3676 S.Diag(Constructor->getLocation(), 3677 diag::note_uninit_in_this_constructor) 3678 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3679 3680 } 3681 3682 void HandleValue(Expr *E, bool AddressOf) { 3683 E = E->IgnoreParens(); 3684 3685 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3686 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3687 AddressOf /*AddressOf*/); 3688 return; 3689 } 3690 3691 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3692 Visit(CO->getCond()); 3693 HandleValue(CO->getTrueExpr(), AddressOf); 3694 HandleValue(CO->getFalseExpr(), AddressOf); 3695 return; 3696 } 3697 3698 if (BinaryConditionalOperator *BCO = 3699 dyn_cast<BinaryConditionalOperator>(E)) { 3700 Visit(BCO->getCond()); 3701 HandleValue(BCO->getFalseExpr(), AddressOf); 3702 return; 3703 } 3704 3705 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3706 HandleValue(OVE->getSourceExpr(), AddressOf); 3707 return; 3708 } 3709 3710 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3711 switch (BO->getOpcode()) { 3712 default: 3713 break; 3714 case(BO_PtrMemD): 3715 case(BO_PtrMemI): 3716 HandleValue(BO->getLHS(), AddressOf); 3717 Visit(BO->getRHS()); 3718 return; 3719 case(BO_Comma): 3720 Visit(BO->getLHS()); 3721 HandleValue(BO->getRHS(), AddressOf); 3722 return; 3723 } 3724 } 3725 3726 Visit(E); 3727 } 3728 3729 void CheckInitListExpr(InitListExpr *ILE) { 3730 InitFieldIndex.push_back(0); 3731 for (auto Child : ILE->children()) { 3732 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3733 CheckInitListExpr(SubList); 3734 } else { 3735 Visit(Child); 3736 } 3737 ++InitFieldIndex.back(); 3738 } 3739 InitFieldIndex.pop_back(); 3740 } 3741 3742 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3743 FieldDecl *Field, const Type *BaseClass) { 3744 // Remove Decls that may have been initialized in the previous 3745 // initializer. 3746 for (ValueDecl* VD : DeclsToRemove) 3747 Decls.erase(VD); 3748 DeclsToRemove.clear(); 3749 3750 Constructor = FieldConstructor; 3751 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3752 3753 if (ILE && Field) { 3754 InitList = true; 3755 InitListFieldDecl = Field; 3756 InitFieldIndex.clear(); 3757 CheckInitListExpr(ILE); 3758 } else { 3759 InitList = false; 3760 Visit(E); 3761 } 3762 3763 if (Field) 3764 Decls.erase(Field); 3765 if (BaseClass) 3766 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3767 } 3768 3769 void VisitMemberExpr(MemberExpr *ME) { 3770 // All uses of unbounded reference fields will warn. 3771 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3772 } 3773 3774 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3775 if (E->getCastKind() == CK_LValueToRValue) { 3776 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3777 return; 3778 } 3779 3780 Inherited::VisitImplicitCastExpr(E); 3781 } 3782 3783 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3784 if (E->getConstructor()->isCopyConstructor()) { 3785 Expr *ArgExpr = E->getArg(0); 3786 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3787 if (ILE->getNumInits() == 1) 3788 ArgExpr = ILE->getInit(0); 3789 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3790 if (ICE->getCastKind() == CK_NoOp) 3791 ArgExpr = ICE->getSubExpr(); 3792 HandleValue(ArgExpr, false /*AddressOf*/); 3793 return; 3794 } 3795 Inherited::VisitCXXConstructExpr(E); 3796 } 3797 3798 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3799 Expr *Callee = E->getCallee(); 3800 if (isa<MemberExpr>(Callee)) { 3801 HandleValue(Callee, false /*AddressOf*/); 3802 for (auto Arg : E->arguments()) 3803 Visit(Arg); 3804 return; 3805 } 3806 3807 Inherited::VisitCXXMemberCallExpr(E); 3808 } 3809 3810 void VisitCallExpr(CallExpr *E) { 3811 // Treat std::move as a use. 3812 if (E->isCallToStdMove()) { 3813 HandleValue(E->getArg(0), /*AddressOf=*/false); 3814 return; 3815 } 3816 3817 Inherited::VisitCallExpr(E); 3818 } 3819 3820 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3821 Expr *Callee = E->getCallee(); 3822 3823 if (isa<UnresolvedLookupExpr>(Callee)) 3824 return Inherited::VisitCXXOperatorCallExpr(E); 3825 3826 Visit(Callee); 3827 for (auto Arg : E->arguments()) 3828 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3829 } 3830 3831 void VisitBinaryOperator(BinaryOperator *E) { 3832 // If a field assignment is detected, remove the field from the 3833 // uninitiailized field set. 3834 if (E->getOpcode() == BO_Assign) 3835 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3836 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3837 if (!FD->getType()->isReferenceType()) 3838 DeclsToRemove.push_back(FD); 3839 3840 if (E->isCompoundAssignmentOp()) { 3841 HandleValue(E->getLHS(), false /*AddressOf*/); 3842 Visit(E->getRHS()); 3843 return; 3844 } 3845 3846 Inherited::VisitBinaryOperator(E); 3847 } 3848 3849 void VisitUnaryOperator(UnaryOperator *E) { 3850 if (E->isIncrementDecrementOp()) { 3851 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3852 return; 3853 } 3854 if (E->getOpcode() == UO_AddrOf) { 3855 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3856 HandleValue(ME->getBase(), true /*AddressOf*/); 3857 return; 3858 } 3859 } 3860 3861 Inherited::VisitUnaryOperator(E); 3862 } 3863 }; 3864 3865 // Diagnose value-uses of fields to initialize themselves, e.g. 3866 // foo(foo) 3867 // where foo is not also a parameter to the constructor. 3868 // Also diagnose across field uninitialized use such as 3869 // x(y), y(x) 3870 // TODO: implement -Wuninitialized and fold this into that framework. 3871 static void DiagnoseUninitializedFields( 3872 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3873 3874 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3875 Constructor->getLocation())) { 3876 return; 3877 } 3878 3879 if (Constructor->isInvalidDecl()) 3880 return; 3881 3882 const CXXRecordDecl *RD = Constructor->getParent(); 3883 3884 if (RD->isDependentContext()) 3885 return; 3886 3887 // Holds fields that are uninitialized. 3888 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3889 3890 // At the beginning, all fields are uninitialized. 3891 for (auto *I : RD->decls()) { 3892 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3893 UninitializedFields.insert(FD); 3894 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3895 UninitializedFields.insert(IFD->getAnonField()); 3896 } 3897 } 3898 3899 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3900 for (auto I : RD->bases()) 3901 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3902 3903 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3904 return; 3905 3906 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3907 UninitializedFields, 3908 UninitializedBaseClasses); 3909 3910 for (const auto *FieldInit : Constructor->inits()) { 3911 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3912 break; 3913 3914 Expr *InitExpr = FieldInit->getInit(); 3915 if (!InitExpr) 3916 continue; 3917 3918 if (CXXDefaultInitExpr *Default = 3919 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3920 InitExpr = Default->getExpr(); 3921 if (!InitExpr) 3922 continue; 3923 // In class initializers will point to the constructor. 3924 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3925 FieldInit->getAnyMember(), 3926 FieldInit->getBaseClass()); 3927 } else { 3928 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3929 FieldInit->getAnyMember(), 3930 FieldInit->getBaseClass()); 3931 } 3932 } 3933 } 3934 } // namespace 3935 3936 /// Enter a new C++ default initializer scope. After calling this, the 3937 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3938 /// parsing or instantiating the initializer failed. 3939 void Sema::ActOnStartCXXInClassMemberInitializer() { 3940 // Create a synthetic function scope to represent the call to the constructor 3941 // that notionally surrounds a use of this initializer. 3942 PushFunctionScope(); 3943 } 3944 3945 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 3946 if (!D.isFunctionDeclarator()) 3947 return; 3948 auto &FTI = D.getFunctionTypeInfo(); 3949 if (!FTI.Params) 3950 return; 3951 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 3952 FTI.NumParams)) { 3953 auto *ParamDecl = cast<NamedDecl>(Param.Param); 3954 if (ParamDecl->getDeclName()) 3955 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 3956 } 3957 } 3958 3959 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 3960 return ActOnRequiresClause(ConstraintExpr); 3961 } 3962 3963 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) { 3964 if (ConstraintExpr.isInvalid()) 3965 return ExprError(); 3966 3967 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr); 3968 if (ConstraintExpr.isInvalid()) 3969 return ExprError(); 3970 3971 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(), 3972 UPPC_RequiresClause)) 3973 return ExprError(); 3974 3975 return ConstraintExpr; 3976 } 3977 3978 /// This is invoked after parsing an in-class initializer for a 3979 /// non-static C++ class member, and after instantiating an in-class initializer 3980 /// in a class template. Such actions are deferred until the class is complete. 3981 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3982 SourceLocation InitLoc, 3983 Expr *InitExpr) { 3984 // Pop the notional constructor scope we created earlier. 3985 PopFunctionScopeInfo(nullptr, D); 3986 3987 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3988 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3989 "must set init style when field is created"); 3990 3991 if (!InitExpr) { 3992 D->setInvalidDecl(); 3993 if (FD) 3994 FD->removeInClassInitializer(); 3995 return; 3996 } 3997 3998 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3999 FD->setInvalidDecl(); 4000 FD->removeInClassInitializer(); 4001 return; 4002 } 4003 4004 ExprResult Init = InitExpr; 4005 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 4006 InitializedEntity Entity = 4007 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 4008 InitializationKind Kind = 4009 FD->getInClassInitStyle() == ICIS_ListInit 4010 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 4011 InitExpr->getBeginLoc(), 4012 InitExpr->getEndLoc()) 4013 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 4014 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 4015 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 4016 if (Init.isInvalid()) { 4017 FD->setInvalidDecl(); 4018 return; 4019 } 4020 } 4021 4022 // C++11 [class.base.init]p7: 4023 // The initialization of each base and member constitutes a 4024 // full-expression. 4025 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 4026 if (Init.isInvalid()) { 4027 FD->setInvalidDecl(); 4028 return; 4029 } 4030 4031 InitExpr = Init.get(); 4032 4033 FD->setInClassInitializer(InitExpr); 4034 } 4035 4036 /// Find the direct and/or virtual base specifiers that 4037 /// correspond to the given base type, for use in base initialization 4038 /// within a constructor. 4039 static bool FindBaseInitializer(Sema &SemaRef, 4040 CXXRecordDecl *ClassDecl, 4041 QualType BaseType, 4042 const CXXBaseSpecifier *&DirectBaseSpec, 4043 const CXXBaseSpecifier *&VirtualBaseSpec) { 4044 // First, check for a direct base class. 4045 DirectBaseSpec = nullptr; 4046 for (const auto &Base : ClassDecl->bases()) { 4047 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 4048 // We found a direct base of this type. That's what we're 4049 // initializing. 4050 DirectBaseSpec = &Base; 4051 break; 4052 } 4053 } 4054 4055 // Check for a virtual base class. 4056 // FIXME: We might be able to short-circuit this if we know in advance that 4057 // there are no virtual bases. 4058 VirtualBaseSpec = nullptr; 4059 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 4060 // We haven't found a base yet; search the class hierarchy for a 4061 // virtual base class. 4062 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 4063 /*DetectVirtual=*/false); 4064 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 4065 SemaRef.Context.getTypeDeclType(ClassDecl), 4066 BaseType, Paths)) { 4067 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 4068 Path != Paths.end(); ++Path) { 4069 if (Path->back().Base->isVirtual()) { 4070 VirtualBaseSpec = Path->back().Base; 4071 break; 4072 } 4073 } 4074 } 4075 } 4076 4077 return DirectBaseSpec || VirtualBaseSpec; 4078 } 4079 4080 /// Handle a C++ member initializer using braced-init-list syntax. 4081 MemInitResult 4082 Sema::ActOnMemInitializer(Decl *ConstructorD, 4083 Scope *S, 4084 CXXScopeSpec &SS, 4085 IdentifierInfo *MemberOrBase, 4086 ParsedType TemplateTypeTy, 4087 const DeclSpec &DS, 4088 SourceLocation IdLoc, 4089 Expr *InitList, 4090 SourceLocation EllipsisLoc) { 4091 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4092 DS, IdLoc, InitList, 4093 EllipsisLoc); 4094 } 4095 4096 /// Handle a C++ member initializer using parentheses syntax. 4097 MemInitResult 4098 Sema::ActOnMemInitializer(Decl *ConstructorD, 4099 Scope *S, 4100 CXXScopeSpec &SS, 4101 IdentifierInfo *MemberOrBase, 4102 ParsedType TemplateTypeTy, 4103 const DeclSpec &DS, 4104 SourceLocation IdLoc, 4105 SourceLocation LParenLoc, 4106 ArrayRef<Expr *> Args, 4107 SourceLocation RParenLoc, 4108 SourceLocation EllipsisLoc) { 4109 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4110 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4111 DS, IdLoc, List, EllipsisLoc); 4112 } 4113 4114 namespace { 4115 4116 // Callback to only accept typo corrections that can be a valid C++ member 4117 // intializer: either a non-static field member or a base class. 4118 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4119 public: 4120 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4121 : ClassDecl(ClassDecl) {} 4122 4123 bool ValidateCandidate(const TypoCorrection &candidate) override { 4124 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4125 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4126 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4127 return isa<TypeDecl>(ND); 4128 } 4129 return false; 4130 } 4131 4132 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4133 return std::make_unique<MemInitializerValidatorCCC>(*this); 4134 } 4135 4136 private: 4137 CXXRecordDecl *ClassDecl; 4138 }; 4139 4140 } 4141 4142 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4143 CXXScopeSpec &SS, 4144 ParsedType TemplateTypeTy, 4145 IdentifierInfo *MemberOrBase) { 4146 if (SS.getScopeRep() || TemplateTypeTy) 4147 return nullptr; 4148 for (auto *D : ClassDecl->lookup(MemberOrBase)) 4149 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) 4150 return cast<ValueDecl>(D); 4151 return nullptr; 4152 } 4153 4154 /// Handle a C++ member initializer. 4155 MemInitResult 4156 Sema::BuildMemInitializer(Decl *ConstructorD, 4157 Scope *S, 4158 CXXScopeSpec &SS, 4159 IdentifierInfo *MemberOrBase, 4160 ParsedType TemplateTypeTy, 4161 const DeclSpec &DS, 4162 SourceLocation IdLoc, 4163 Expr *Init, 4164 SourceLocation EllipsisLoc) { 4165 ExprResult Res = CorrectDelayedTyposInExpr(Init); 4166 if (!Res.isUsable()) 4167 return true; 4168 Init = Res.get(); 4169 4170 if (!ConstructorD) 4171 return true; 4172 4173 AdjustDeclIfTemplate(ConstructorD); 4174 4175 CXXConstructorDecl *Constructor 4176 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4177 if (!Constructor) { 4178 // The user wrote a constructor initializer on a function that is 4179 // not a C++ constructor. Ignore the error for now, because we may 4180 // have more member initializers coming; we'll diagnose it just 4181 // once in ActOnMemInitializers. 4182 return true; 4183 } 4184 4185 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4186 4187 // C++ [class.base.init]p2: 4188 // Names in a mem-initializer-id are looked up in the scope of the 4189 // constructor's class and, if not found in that scope, are looked 4190 // up in the scope containing the constructor's definition. 4191 // [Note: if the constructor's class contains a member with the 4192 // same name as a direct or virtual base class of the class, a 4193 // mem-initializer-id naming the member or base class and composed 4194 // of a single identifier refers to the class member. A 4195 // mem-initializer-id for the hidden base class may be specified 4196 // using a qualified name. ] 4197 4198 // Look for a member, first. 4199 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4200 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4201 if (EllipsisLoc.isValid()) 4202 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4203 << MemberOrBase 4204 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4205 4206 return BuildMemberInitializer(Member, Init, IdLoc); 4207 } 4208 // It didn't name a member, so see if it names a class. 4209 QualType BaseType; 4210 TypeSourceInfo *TInfo = nullptr; 4211 4212 if (TemplateTypeTy) { 4213 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4214 if (BaseType.isNull()) 4215 return true; 4216 } else if (DS.getTypeSpecType() == TST_decltype) { 4217 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4218 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4219 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4220 return true; 4221 } else { 4222 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4223 LookupParsedName(R, S, &SS); 4224 4225 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4226 if (!TyD) { 4227 if (R.isAmbiguous()) return true; 4228 4229 // We don't want access-control diagnostics here. 4230 R.suppressDiagnostics(); 4231 4232 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4233 bool NotUnknownSpecialization = false; 4234 DeclContext *DC = computeDeclContext(SS, false); 4235 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4236 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4237 4238 if (!NotUnknownSpecialization) { 4239 // When the scope specifier can refer to a member of an unknown 4240 // specialization, we take it as a type name. 4241 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4242 SS.getWithLocInContext(Context), 4243 *MemberOrBase, IdLoc); 4244 if (BaseType.isNull()) 4245 return true; 4246 4247 TInfo = Context.CreateTypeSourceInfo(BaseType); 4248 DependentNameTypeLoc TL = 4249 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4250 if (!TL.isNull()) { 4251 TL.setNameLoc(IdLoc); 4252 TL.setElaboratedKeywordLoc(SourceLocation()); 4253 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4254 } 4255 4256 R.clear(); 4257 R.setLookupName(MemberOrBase); 4258 } 4259 } 4260 4261 // If no results were found, try to correct typos. 4262 TypoCorrection Corr; 4263 MemInitializerValidatorCCC CCC(ClassDecl); 4264 if (R.empty() && BaseType.isNull() && 4265 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4266 CCC, CTK_ErrorRecovery, ClassDecl))) { 4267 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4268 // We have found a non-static data member with a similar 4269 // name to what was typed; complain and initialize that 4270 // member. 4271 diagnoseTypo(Corr, 4272 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4273 << MemberOrBase << true); 4274 return BuildMemberInitializer(Member, Init, IdLoc); 4275 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4276 const CXXBaseSpecifier *DirectBaseSpec; 4277 const CXXBaseSpecifier *VirtualBaseSpec; 4278 if (FindBaseInitializer(*this, ClassDecl, 4279 Context.getTypeDeclType(Type), 4280 DirectBaseSpec, VirtualBaseSpec)) { 4281 // We have found a direct or virtual base class with a 4282 // similar name to what was typed; complain and initialize 4283 // that base class. 4284 diagnoseTypo(Corr, 4285 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4286 << MemberOrBase << false, 4287 PDiag() /*Suppress note, we provide our own.*/); 4288 4289 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4290 : VirtualBaseSpec; 4291 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4292 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4293 4294 TyD = Type; 4295 } 4296 } 4297 } 4298 4299 if (!TyD && BaseType.isNull()) { 4300 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4301 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4302 return true; 4303 } 4304 } 4305 4306 if (BaseType.isNull()) { 4307 BaseType = Context.getTypeDeclType(TyD); 4308 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4309 if (SS.isSet()) { 4310 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4311 BaseType); 4312 TInfo = Context.CreateTypeSourceInfo(BaseType); 4313 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4314 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4315 TL.setElaboratedKeywordLoc(SourceLocation()); 4316 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4317 } 4318 } 4319 } 4320 4321 if (!TInfo) 4322 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4323 4324 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4325 } 4326 4327 MemInitResult 4328 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4329 SourceLocation IdLoc) { 4330 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4331 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4332 assert((DirectMember || IndirectMember) && 4333 "Member must be a FieldDecl or IndirectFieldDecl"); 4334 4335 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4336 return true; 4337 4338 if (Member->isInvalidDecl()) 4339 return true; 4340 4341 MultiExprArg Args; 4342 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4343 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4344 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4345 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4346 } else { 4347 // Template instantiation doesn't reconstruct ParenListExprs for us. 4348 Args = Init; 4349 } 4350 4351 SourceRange InitRange = Init->getSourceRange(); 4352 4353 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4354 // Can't check initialization for a member of dependent type or when 4355 // any of the arguments are type-dependent expressions. 4356 DiscardCleanupsInEvaluationContext(); 4357 } else { 4358 bool InitList = false; 4359 if (isa<InitListExpr>(Init)) { 4360 InitList = true; 4361 Args = Init; 4362 } 4363 4364 // Initialize the member. 4365 InitializedEntity MemberEntity = 4366 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4367 : InitializedEntity::InitializeMember(IndirectMember, 4368 nullptr); 4369 InitializationKind Kind = 4370 InitList ? InitializationKind::CreateDirectList( 4371 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4372 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4373 InitRange.getEnd()); 4374 4375 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4376 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4377 nullptr); 4378 if (MemberInit.isInvalid()) 4379 return true; 4380 4381 // C++11 [class.base.init]p7: 4382 // The initialization of each base and member constitutes a 4383 // full-expression. 4384 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4385 /*DiscardedValue*/ false); 4386 if (MemberInit.isInvalid()) 4387 return true; 4388 4389 Init = MemberInit.get(); 4390 } 4391 4392 if (DirectMember) { 4393 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4394 InitRange.getBegin(), Init, 4395 InitRange.getEnd()); 4396 } else { 4397 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4398 InitRange.getBegin(), Init, 4399 InitRange.getEnd()); 4400 } 4401 } 4402 4403 MemInitResult 4404 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4405 CXXRecordDecl *ClassDecl) { 4406 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4407 if (!LangOpts.CPlusPlus11) 4408 return Diag(NameLoc, diag::err_delegating_ctor) 4409 << TInfo->getTypeLoc().getLocalSourceRange(); 4410 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4411 4412 bool InitList = true; 4413 MultiExprArg Args = Init; 4414 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4415 InitList = false; 4416 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4417 } 4418 4419 SourceRange InitRange = Init->getSourceRange(); 4420 // Initialize the object. 4421 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4422 QualType(ClassDecl->getTypeForDecl(), 0)); 4423 InitializationKind Kind = 4424 InitList ? InitializationKind::CreateDirectList( 4425 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4426 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4427 InitRange.getEnd()); 4428 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4429 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4430 Args, nullptr); 4431 if (DelegationInit.isInvalid()) 4432 return true; 4433 4434 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4435 "Delegating constructor with no target?"); 4436 4437 // C++11 [class.base.init]p7: 4438 // The initialization of each base and member constitutes a 4439 // full-expression. 4440 DelegationInit = ActOnFinishFullExpr( 4441 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4442 if (DelegationInit.isInvalid()) 4443 return true; 4444 4445 // If we are in a dependent context, template instantiation will 4446 // perform this type-checking again. Just save the arguments that we 4447 // received in a ParenListExpr. 4448 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4449 // of the information that we have about the base 4450 // initializer. However, deconstructing the ASTs is a dicey process, 4451 // and this approach is far more likely to get the corner cases right. 4452 if (CurContext->isDependentContext()) 4453 DelegationInit = Init; 4454 4455 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4456 DelegationInit.getAs<Expr>(), 4457 InitRange.getEnd()); 4458 } 4459 4460 MemInitResult 4461 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4462 Expr *Init, CXXRecordDecl *ClassDecl, 4463 SourceLocation EllipsisLoc) { 4464 SourceLocation BaseLoc 4465 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4466 4467 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4468 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4469 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4470 4471 // C++ [class.base.init]p2: 4472 // [...] Unless the mem-initializer-id names a nonstatic data 4473 // member of the constructor's class or a direct or virtual base 4474 // of that class, the mem-initializer is ill-formed. A 4475 // mem-initializer-list can initialize a base class using any 4476 // name that denotes that base class type. 4477 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4478 4479 SourceRange InitRange = Init->getSourceRange(); 4480 if (EllipsisLoc.isValid()) { 4481 // This is a pack expansion. 4482 if (!BaseType->containsUnexpandedParameterPack()) { 4483 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4484 << SourceRange(BaseLoc, InitRange.getEnd()); 4485 4486 EllipsisLoc = SourceLocation(); 4487 } 4488 } else { 4489 // Check for any unexpanded parameter packs. 4490 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4491 return true; 4492 4493 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4494 return true; 4495 } 4496 4497 // Check for direct and virtual base classes. 4498 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4499 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4500 if (!Dependent) { 4501 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4502 BaseType)) 4503 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4504 4505 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4506 VirtualBaseSpec); 4507 4508 // C++ [base.class.init]p2: 4509 // Unless the mem-initializer-id names a nonstatic data member of the 4510 // constructor's class or a direct or virtual base of that class, the 4511 // mem-initializer is ill-formed. 4512 if (!DirectBaseSpec && !VirtualBaseSpec) { 4513 // If the class has any dependent bases, then it's possible that 4514 // one of those types will resolve to the same type as 4515 // BaseType. Therefore, just treat this as a dependent base 4516 // class initialization. FIXME: Should we try to check the 4517 // initialization anyway? It seems odd. 4518 if (ClassDecl->hasAnyDependentBases()) 4519 Dependent = true; 4520 else 4521 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4522 << BaseType << Context.getTypeDeclType(ClassDecl) 4523 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4524 } 4525 } 4526 4527 if (Dependent) { 4528 DiscardCleanupsInEvaluationContext(); 4529 4530 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4531 /*IsVirtual=*/false, 4532 InitRange.getBegin(), Init, 4533 InitRange.getEnd(), EllipsisLoc); 4534 } 4535 4536 // C++ [base.class.init]p2: 4537 // If a mem-initializer-id is ambiguous because it designates both 4538 // a direct non-virtual base class and an inherited virtual base 4539 // class, the mem-initializer is ill-formed. 4540 if (DirectBaseSpec && VirtualBaseSpec) 4541 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4542 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4543 4544 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4545 if (!BaseSpec) 4546 BaseSpec = VirtualBaseSpec; 4547 4548 // Initialize the base. 4549 bool InitList = true; 4550 MultiExprArg Args = Init; 4551 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4552 InitList = false; 4553 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4554 } 4555 4556 InitializedEntity BaseEntity = 4557 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4558 InitializationKind Kind = 4559 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4560 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4561 InitRange.getEnd()); 4562 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4563 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4564 if (BaseInit.isInvalid()) 4565 return true; 4566 4567 // C++11 [class.base.init]p7: 4568 // The initialization of each base and member constitutes a 4569 // full-expression. 4570 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4571 /*DiscardedValue*/ false); 4572 if (BaseInit.isInvalid()) 4573 return true; 4574 4575 // If we are in a dependent context, template instantiation will 4576 // perform this type-checking again. Just save the arguments that we 4577 // received in a ParenListExpr. 4578 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4579 // of the information that we have about the base 4580 // initializer. However, deconstructing the ASTs is a dicey process, 4581 // and this approach is far more likely to get the corner cases right. 4582 if (CurContext->isDependentContext()) 4583 BaseInit = Init; 4584 4585 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4586 BaseSpec->isVirtual(), 4587 InitRange.getBegin(), 4588 BaseInit.getAs<Expr>(), 4589 InitRange.getEnd(), EllipsisLoc); 4590 } 4591 4592 // Create a static_cast\<T&&>(expr). 4593 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4594 if (T.isNull()) T = E->getType(); 4595 QualType TargetType = SemaRef.BuildReferenceType( 4596 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4597 SourceLocation ExprLoc = E->getBeginLoc(); 4598 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4599 TargetType, ExprLoc); 4600 4601 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4602 SourceRange(ExprLoc, ExprLoc), 4603 E->getSourceRange()).get(); 4604 } 4605 4606 /// ImplicitInitializerKind - How an implicit base or member initializer should 4607 /// initialize its base or member. 4608 enum ImplicitInitializerKind { 4609 IIK_Default, 4610 IIK_Copy, 4611 IIK_Move, 4612 IIK_Inherit 4613 }; 4614 4615 static bool 4616 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4617 ImplicitInitializerKind ImplicitInitKind, 4618 CXXBaseSpecifier *BaseSpec, 4619 bool IsInheritedVirtualBase, 4620 CXXCtorInitializer *&CXXBaseInit) { 4621 InitializedEntity InitEntity 4622 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4623 IsInheritedVirtualBase); 4624 4625 ExprResult BaseInit; 4626 4627 switch (ImplicitInitKind) { 4628 case IIK_Inherit: 4629 case IIK_Default: { 4630 InitializationKind InitKind 4631 = InitializationKind::CreateDefault(Constructor->getLocation()); 4632 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4633 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4634 break; 4635 } 4636 4637 case IIK_Move: 4638 case IIK_Copy: { 4639 bool Moving = ImplicitInitKind == IIK_Move; 4640 ParmVarDecl *Param = Constructor->getParamDecl(0); 4641 QualType ParamType = Param->getType().getNonReferenceType(); 4642 4643 Expr *CopyCtorArg = 4644 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4645 SourceLocation(), Param, false, 4646 Constructor->getLocation(), ParamType, 4647 VK_LValue, nullptr); 4648 4649 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4650 4651 // Cast to the base class to avoid ambiguities. 4652 QualType ArgTy = 4653 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4654 ParamType.getQualifiers()); 4655 4656 if (Moving) { 4657 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4658 } 4659 4660 CXXCastPath BasePath; 4661 BasePath.push_back(BaseSpec); 4662 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4663 CK_UncheckedDerivedToBase, 4664 Moving ? VK_XValue : VK_LValue, 4665 &BasePath).get(); 4666 4667 InitializationKind InitKind 4668 = InitializationKind::CreateDirect(Constructor->getLocation(), 4669 SourceLocation(), SourceLocation()); 4670 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4671 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4672 break; 4673 } 4674 } 4675 4676 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4677 if (BaseInit.isInvalid()) 4678 return true; 4679 4680 CXXBaseInit = 4681 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4682 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4683 SourceLocation()), 4684 BaseSpec->isVirtual(), 4685 SourceLocation(), 4686 BaseInit.getAs<Expr>(), 4687 SourceLocation(), 4688 SourceLocation()); 4689 4690 return false; 4691 } 4692 4693 static bool RefersToRValueRef(Expr *MemRef) { 4694 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4695 return Referenced->getType()->isRValueReferenceType(); 4696 } 4697 4698 static bool 4699 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4700 ImplicitInitializerKind ImplicitInitKind, 4701 FieldDecl *Field, IndirectFieldDecl *Indirect, 4702 CXXCtorInitializer *&CXXMemberInit) { 4703 if (Field->isInvalidDecl()) 4704 return true; 4705 4706 SourceLocation Loc = Constructor->getLocation(); 4707 4708 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4709 bool Moving = ImplicitInitKind == IIK_Move; 4710 ParmVarDecl *Param = Constructor->getParamDecl(0); 4711 QualType ParamType = Param->getType().getNonReferenceType(); 4712 4713 // Suppress copying zero-width bitfields. 4714 if (Field->isZeroLengthBitField(SemaRef.Context)) 4715 return false; 4716 4717 Expr *MemberExprBase = 4718 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4719 SourceLocation(), Param, false, 4720 Loc, ParamType, VK_LValue, nullptr); 4721 4722 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4723 4724 if (Moving) { 4725 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4726 } 4727 4728 // Build a reference to this field within the parameter. 4729 CXXScopeSpec SS; 4730 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4731 Sema::LookupMemberName); 4732 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4733 : cast<ValueDecl>(Field), AS_public); 4734 MemberLookup.resolveKind(); 4735 ExprResult CtorArg 4736 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4737 ParamType, Loc, 4738 /*IsArrow=*/false, 4739 SS, 4740 /*TemplateKWLoc=*/SourceLocation(), 4741 /*FirstQualifierInScope=*/nullptr, 4742 MemberLookup, 4743 /*TemplateArgs=*/nullptr, 4744 /*S*/nullptr); 4745 if (CtorArg.isInvalid()) 4746 return true; 4747 4748 // C++11 [class.copy]p15: 4749 // - if a member m has rvalue reference type T&&, it is direct-initialized 4750 // with static_cast<T&&>(x.m); 4751 if (RefersToRValueRef(CtorArg.get())) { 4752 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4753 } 4754 4755 InitializedEntity Entity = 4756 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4757 /*Implicit*/ true) 4758 : InitializedEntity::InitializeMember(Field, nullptr, 4759 /*Implicit*/ true); 4760 4761 // Direct-initialize to use the copy constructor. 4762 InitializationKind InitKind = 4763 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4764 4765 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4766 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4767 ExprResult MemberInit = 4768 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4769 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4770 if (MemberInit.isInvalid()) 4771 return true; 4772 4773 if (Indirect) 4774 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4775 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4776 else 4777 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4778 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4779 return false; 4780 } 4781 4782 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4783 "Unhandled implicit init kind!"); 4784 4785 QualType FieldBaseElementType = 4786 SemaRef.Context.getBaseElementType(Field->getType()); 4787 4788 if (FieldBaseElementType->isRecordType()) { 4789 InitializedEntity InitEntity = 4790 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4791 /*Implicit*/ true) 4792 : InitializedEntity::InitializeMember(Field, nullptr, 4793 /*Implicit*/ true); 4794 InitializationKind InitKind = 4795 InitializationKind::CreateDefault(Loc); 4796 4797 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4798 ExprResult MemberInit = 4799 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4800 4801 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4802 if (MemberInit.isInvalid()) 4803 return true; 4804 4805 if (Indirect) 4806 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4807 Indirect, Loc, 4808 Loc, 4809 MemberInit.get(), 4810 Loc); 4811 else 4812 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4813 Field, Loc, Loc, 4814 MemberInit.get(), 4815 Loc); 4816 return false; 4817 } 4818 4819 if (!Field->getParent()->isUnion()) { 4820 if (FieldBaseElementType->isReferenceType()) { 4821 SemaRef.Diag(Constructor->getLocation(), 4822 diag::err_uninitialized_member_in_ctor) 4823 << (int)Constructor->isImplicit() 4824 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4825 << 0 << Field->getDeclName(); 4826 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4827 return true; 4828 } 4829 4830 if (FieldBaseElementType.isConstQualified()) { 4831 SemaRef.Diag(Constructor->getLocation(), 4832 diag::err_uninitialized_member_in_ctor) 4833 << (int)Constructor->isImplicit() 4834 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4835 << 1 << Field->getDeclName(); 4836 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4837 return true; 4838 } 4839 } 4840 4841 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4842 // ARC and Weak: 4843 // Default-initialize Objective-C pointers to NULL. 4844 CXXMemberInit 4845 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4846 Loc, Loc, 4847 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4848 Loc); 4849 return false; 4850 } 4851 4852 // Nothing to initialize. 4853 CXXMemberInit = nullptr; 4854 return false; 4855 } 4856 4857 namespace { 4858 struct BaseAndFieldInfo { 4859 Sema &S; 4860 CXXConstructorDecl *Ctor; 4861 bool AnyErrorsInInits; 4862 ImplicitInitializerKind IIK; 4863 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4864 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4865 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4866 4867 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4868 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4869 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4870 if (Ctor->getInheritedConstructor()) 4871 IIK = IIK_Inherit; 4872 else if (Generated && Ctor->isCopyConstructor()) 4873 IIK = IIK_Copy; 4874 else if (Generated && Ctor->isMoveConstructor()) 4875 IIK = IIK_Move; 4876 else 4877 IIK = IIK_Default; 4878 } 4879 4880 bool isImplicitCopyOrMove() const { 4881 switch (IIK) { 4882 case IIK_Copy: 4883 case IIK_Move: 4884 return true; 4885 4886 case IIK_Default: 4887 case IIK_Inherit: 4888 return false; 4889 } 4890 4891 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4892 } 4893 4894 bool addFieldInitializer(CXXCtorInitializer *Init) { 4895 AllToInit.push_back(Init); 4896 4897 // Check whether this initializer makes the field "used". 4898 if (Init->getInit()->HasSideEffects(S.Context)) 4899 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4900 4901 return false; 4902 } 4903 4904 bool isInactiveUnionMember(FieldDecl *Field) { 4905 RecordDecl *Record = Field->getParent(); 4906 if (!Record->isUnion()) 4907 return false; 4908 4909 if (FieldDecl *Active = 4910 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4911 return Active != Field->getCanonicalDecl(); 4912 4913 // In an implicit copy or move constructor, ignore any in-class initializer. 4914 if (isImplicitCopyOrMove()) 4915 return true; 4916 4917 // If there's no explicit initialization, the field is active only if it 4918 // has an in-class initializer... 4919 if (Field->hasInClassInitializer()) 4920 return false; 4921 // ... or it's an anonymous struct or union whose class has an in-class 4922 // initializer. 4923 if (!Field->isAnonymousStructOrUnion()) 4924 return true; 4925 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4926 return !FieldRD->hasInClassInitializer(); 4927 } 4928 4929 /// Determine whether the given field is, or is within, a union member 4930 /// that is inactive (because there was an initializer given for a different 4931 /// member of the union, or because the union was not initialized at all). 4932 bool isWithinInactiveUnionMember(FieldDecl *Field, 4933 IndirectFieldDecl *Indirect) { 4934 if (!Indirect) 4935 return isInactiveUnionMember(Field); 4936 4937 for (auto *C : Indirect->chain()) { 4938 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4939 if (Field && isInactiveUnionMember(Field)) 4940 return true; 4941 } 4942 return false; 4943 } 4944 }; 4945 } 4946 4947 /// Determine whether the given type is an incomplete or zero-lenfgth 4948 /// array type. 4949 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4950 if (T->isIncompleteArrayType()) 4951 return true; 4952 4953 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4954 if (!ArrayT->getSize()) 4955 return true; 4956 4957 T = ArrayT->getElementType(); 4958 } 4959 4960 return false; 4961 } 4962 4963 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4964 FieldDecl *Field, 4965 IndirectFieldDecl *Indirect = nullptr) { 4966 if (Field->isInvalidDecl()) 4967 return false; 4968 4969 // Overwhelmingly common case: we have a direct initializer for this field. 4970 if (CXXCtorInitializer *Init = 4971 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4972 return Info.addFieldInitializer(Init); 4973 4974 // C++11 [class.base.init]p8: 4975 // if the entity is a non-static data member that has a 4976 // brace-or-equal-initializer and either 4977 // -- the constructor's class is a union and no other variant member of that 4978 // union is designated by a mem-initializer-id or 4979 // -- the constructor's class is not a union, and, if the entity is a member 4980 // of an anonymous union, no other member of that union is designated by 4981 // a mem-initializer-id, 4982 // the entity is initialized as specified in [dcl.init]. 4983 // 4984 // We also apply the same rules to handle anonymous structs within anonymous 4985 // unions. 4986 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4987 return false; 4988 4989 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4990 ExprResult DIE = 4991 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4992 if (DIE.isInvalid()) 4993 return true; 4994 4995 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4996 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4997 4998 CXXCtorInitializer *Init; 4999 if (Indirect) 5000 Init = new (SemaRef.Context) 5001 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 5002 SourceLocation(), DIE.get(), SourceLocation()); 5003 else 5004 Init = new (SemaRef.Context) 5005 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 5006 SourceLocation(), DIE.get(), SourceLocation()); 5007 return Info.addFieldInitializer(Init); 5008 } 5009 5010 // Don't initialize incomplete or zero-length arrays. 5011 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 5012 return false; 5013 5014 // Don't try to build an implicit initializer if there were semantic 5015 // errors in any of the initializers (and therefore we might be 5016 // missing some that the user actually wrote). 5017 if (Info.AnyErrorsInInits) 5018 return false; 5019 5020 CXXCtorInitializer *Init = nullptr; 5021 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 5022 Indirect, Init)) 5023 return true; 5024 5025 if (!Init) 5026 return false; 5027 5028 return Info.addFieldInitializer(Init); 5029 } 5030 5031 bool 5032 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 5033 CXXCtorInitializer *Initializer) { 5034 assert(Initializer->isDelegatingInitializer()); 5035 Constructor->setNumCtorInitializers(1); 5036 CXXCtorInitializer **initializer = 5037 new (Context) CXXCtorInitializer*[1]; 5038 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 5039 Constructor->setCtorInitializers(initializer); 5040 5041 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 5042 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 5043 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 5044 } 5045 5046 DelegatingCtorDecls.push_back(Constructor); 5047 5048 DiagnoseUninitializedFields(*this, Constructor); 5049 5050 return false; 5051 } 5052 5053 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 5054 ArrayRef<CXXCtorInitializer *> Initializers) { 5055 if (Constructor->isDependentContext()) { 5056 // Just store the initializers as written, they will be checked during 5057 // instantiation. 5058 if (!Initializers.empty()) { 5059 Constructor->setNumCtorInitializers(Initializers.size()); 5060 CXXCtorInitializer **baseOrMemberInitializers = 5061 new (Context) CXXCtorInitializer*[Initializers.size()]; 5062 memcpy(baseOrMemberInitializers, Initializers.data(), 5063 Initializers.size() * sizeof(CXXCtorInitializer*)); 5064 Constructor->setCtorInitializers(baseOrMemberInitializers); 5065 } 5066 5067 // Let template instantiation know whether we had errors. 5068 if (AnyErrors) 5069 Constructor->setInvalidDecl(); 5070 5071 return false; 5072 } 5073 5074 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 5075 5076 // We need to build the initializer AST according to order of construction 5077 // and not what user specified in the Initializers list. 5078 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 5079 if (!ClassDecl) 5080 return true; 5081 5082 bool HadError = false; 5083 5084 for (unsigned i = 0; i < Initializers.size(); i++) { 5085 CXXCtorInitializer *Member = Initializers[i]; 5086 5087 if (Member->isBaseInitializer()) 5088 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5089 else { 5090 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5091 5092 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5093 for (auto *C : F->chain()) { 5094 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5095 if (FD && FD->getParent()->isUnion()) 5096 Info.ActiveUnionMember.insert(std::make_pair( 5097 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5098 } 5099 } else if (FieldDecl *FD = Member->getMember()) { 5100 if (FD->getParent()->isUnion()) 5101 Info.ActiveUnionMember.insert(std::make_pair( 5102 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5103 } 5104 } 5105 } 5106 5107 // Keep track of the direct virtual bases. 5108 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5109 for (auto &I : ClassDecl->bases()) { 5110 if (I.isVirtual()) 5111 DirectVBases.insert(&I); 5112 } 5113 5114 // Push virtual bases before others. 5115 for (auto &VBase : ClassDecl->vbases()) { 5116 if (CXXCtorInitializer *Value 5117 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5118 // [class.base.init]p7, per DR257: 5119 // A mem-initializer where the mem-initializer-id names a virtual base 5120 // class is ignored during execution of a constructor of any class that 5121 // is not the most derived class. 5122 if (ClassDecl->isAbstract()) { 5123 // FIXME: Provide a fixit to remove the base specifier. This requires 5124 // tracking the location of the associated comma for a base specifier. 5125 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5126 << VBase.getType() << ClassDecl; 5127 DiagnoseAbstractType(ClassDecl); 5128 } 5129 5130 Info.AllToInit.push_back(Value); 5131 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5132 // [class.base.init]p8, per DR257: 5133 // If a given [...] base class is not named by a mem-initializer-id 5134 // [...] and the entity is not a virtual base class of an abstract 5135 // class, then [...] the entity is default-initialized. 5136 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5137 CXXCtorInitializer *CXXBaseInit; 5138 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5139 &VBase, IsInheritedVirtualBase, 5140 CXXBaseInit)) { 5141 HadError = true; 5142 continue; 5143 } 5144 5145 Info.AllToInit.push_back(CXXBaseInit); 5146 } 5147 } 5148 5149 // Non-virtual bases. 5150 for (auto &Base : ClassDecl->bases()) { 5151 // Virtuals are in the virtual base list and already constructed. 5152 if (Base.isVirtual()) 5153 continue; 5154 5155 if (CXXCtorInitializer *Value 5156 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5157 Info.AllToInit.push_back(Value); 5158 } else if (!AnyErrors) { 5159 CXXCtorInitializer *CXXBaseInit; 5160 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5161 &Base, /*IsInheritedVirtualBase=*/false, 5162 CXXBaseInit)) { 5163 HadError = true; 5164 continue; 5165 } 5166 5167 Info.AllToInit.push_back(CXXBaseInit); 5168 } 5169 } 5170 5171 // Fields. 5172 for (auto *Mem : ClassDecl->decls()) { 5173 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5174 // C++ [class.bit]p2: 5175 // A declaration for a bit-field that omits the identifier declares an 5176 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5177 // initialized. 5178 if (F->isUnnamedBitfield()) 5179 continue; 5180 5181 // If we're not generating the implicit copy/move constructor, then we'll 5182 // handle anonymous struct/union fields based on their individual 5183 // indirect fields. 5184 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5185 continue; 5186 5187 if (CollectFieldInitializer(*this, Info, F)) 5188 HadError = true; 5189 continue; 5190 } 5191 5192 // Beyond this point, we only consider default initialization. 5193 if (Info.isImplicitCopyOrMove()) 5194 continue; 5195 5196 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5197 if (F->getType()->isIncompleteArrayType()) { 5198 assert(ClassDecl->hasFlexibleArrayMember() && 5199 "Incomplete array type is not valid"); 5200 continue; 5201 } 5202 5203 // Initialize each field of an anonymous struct individually. 5204 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5205 HadError = true; 5206 5207 continue; 5208 } 5209 } 5210 5211 unsigned NumInitializers = Info.AllToInit.size(); 5212 if (NumInitializers > 0) { 5213 Constructor->setNumCtorInitializers(NumInitializers); 5214 CXXCtorInitializer **baseOrMemberInitializers = 5215 new (Context) CXXCtorInitializer*[NumInitializers]; 5216 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5217 NumInitializers * sizeof(CXXCtorInitializer*)); 5218 Constructor->setCtorInitializers(baseOrMemberInitializers); 5219 5220 // Constructors implicitly reference the base and member 5221 // destructors. 5222 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5223 Constructor->getParent()); 5224 } 5225 5226 return HadError; 5227 } 5228 5229 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5230 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5231 const RecordDecl *RD = RT->getDecl(); 5232 if (RD->isAnonymousStructOrUnion()) { 5233 for (auto *Field : RD->fields()) 5234 PopulateKeysForFields(Field, IdealInits); 5235 return; 5236 } 5237 } 5238 IdealInits.push_back(Field->getCanonicalDecl()); 5239 } 5240 5241 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5242 return Context.getCanonicalType(BaseType).getTypePtr(); 5243 } 5244 5245 static const void *GetKeyForMember(ASTContext &Context, 5246 CXXCtorInitializer *Member) { 5247 if (!Member->isAnyMemberInitializer()) 5248 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5249 5250 return Member->getAnyMember()->getCanonicalDecl(); 5251 } 5252 5253 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, 5254 const CXXCtorInitializer *Previous, 5255 const CXXCtorInitializer *Current) { 5256 if (Previous->isAnyMemberInitializer()) 5257 Diag << 0 << Previous->getAnyMember(); 5258 else 5259 Diag << 1 << Previous->getTypeSourceInfo()->getType(); 5260 5261 if (Current->isAnyMemberInitializer()) 5262 Diag << 0 << Current->getAnyMember(); 5263 else 5264 Diag << 1 << Current->getTypeSourceInfo()->getType(); 5265 } 5266 5267 static void DiagnoseBaseOrMemInitializerOrder( 5268 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5269 ArrayRef<CXXCtorInitializer *> Inits) { 5270 if (Constructor->getDeclContext()->isDependentContext()) 5271 return; 5272 5273 // Don't check initializers order unless the warning is enabled at the 5274 // location of at least one initializer. 5275 bool ShouldCheckOrder = false; 5276 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5277 CXXCtorInitializer *Init = Inits[InitIndex]; 5278 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5279 Init->getSourceLocation())) { 5280 ShouldCheckOrder = true; 5281 break; 5282 } 5283 } 5284 if (!ShouldCheckOrder) 5285 return; 5286 5287 // Build the list of bases and members in the order that they'll 5288 // actually be initialized. The explicit initializers should be in 5289 // this same order but may be missing things. 5290 SmallVector<const void*, 32> IdealInitKeys; 5291 5292 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5293 5294 // 1. Virtual bases. 5295 for (const auto &VBase : ClassDecl->vbases()) 5296 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5297 5298 // 2. Non-virtual bases. 5299 for (const auto &Base : ClassDecl->bases()) { 5300 if (Base.isVirtual()) 5301 continue; 5302 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5303 } 5304 5305 // 3. Direct fields. 5306 for (auto *Field : ClassDecl->fields()) { 5307 if (Field->isUnnamedBitfield()) 5308 continue; 5309 5310 PopulateKeysForFields(Field, IdealInitKeys); 5311 } 5312 5313 unsigned NumIdealInits = IdealInitKeys.size(); 5314 unsigned IdealIndex = 0; 5315 5316 // Track initializers that are in an incorrect order for either a warning or 5317 // note if multiple ones occur. 5318 SmallVector<unsigned> WarnIndexes; 5319 // Correlates the index of an initializer in the init-list to the index of 5320 // the field/base in the class. 5321 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder; 5322 5323 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5324 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]); 5325 5326 // Scan forward to try to find this initializer in the idealized 5327 // initializers list. 5328 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5329 if (InitKey == IdealInitKeys[IdealIndex]) 5330 break; 5331 5332 // If we didn't find this initializer, it must be because we 5333 // scanned past it on a previous iteration. That can only 5334 // happen if we're out of order; emit a warning. 5335 if (IdealIndex == NumIdealInits && InitIndex) { 5336 WarnIndexes.push_back(InitIndex); 5337 5338 // Move back to the initializer's location in the ideal list. 5339 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5340 if (InitKey == IdealInitKeys[IdealIndex]) 5341 break; 5342 5343 assert(IdealIndex < NumIdealInits && 5344 "initializer not found in initializer list"); 5345 } 5346 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex); 5347 } 5348 5349 if (WarnIndexes.empty()) 5350 return; 5351 5352 // Sort based on the ideal order, first in the pair. 5353 llvm::sort(CorrelatedInitOrder, 5354 [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; }); 5355 5356 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to 5357 // emit the diagnostic before we can try adding notes. 5358 { 5359 Sema::SemaDiagnosticBuilder D = SemaRef.Diag( 5360 Inits[WarnIndexes.front() - 1]->getSourceLocation(), 5361 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order 5362 : diag::warn_some_initializers_out_of_order); 5363 5364 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) { 5365 if (CorrelatedInitOrder[I].second == I) 5366 continue; 5367 // Ideally we would be using InsertFromRange here, but clang doesn't 5368 // appear to handle InsertFromRange correctly when the source range is 5369 // modified by another fix-it. 5370 D << FixItHint::CreateReplacement( 5371 Inits[I]->getSourceRange(), 5372 Lexer::getSourceText( 5373 CharSourceRange::getTokenRange( 5374 Inits[CorrelatedInitOrder[I].second]->getSourceRange()), 5375 SemaRef.getSourceManager(), SemaRef.getLangOpts())); 5376 } 5377 5378 // If there is only 1 item out of order, the warning expects the name and 5379 // type of each being added to it. 5380 if (WarnIndexes.size() == 1) { 5381 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1], 5382 Inits[WarnIndexes.front()]); 5383 return; 5384 } 5385 } 5386 // More than 1 item to warn, create notes letting the user know which ones 5387 // are bad. 5388 for (unsigned WarnIndex : WarnIndexes) { 5389 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1]; 5390 auto D = SemaRef.Diag(PrevInit->getSourceLocation(), 5391 diag::note_initializer_out_of_order); 5392 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]); 5393 D << PrevInit->getSourceRange(); 5394 } 5395 } 5396 5397 namespace { 5398 bool CheckRedundantInit(Sema &S, 5399 CXXCtorInitializer *Init, 5400 CXXCtorInitializer *&PrevInit) { 5401 if (!PrevInit) { 5402 PrevInit = Init; 5403 return false; 5404 } 5405 5406 if (FieldDecl *Field = Init->getAnyMember()) 5407 S.Diag(Init->getSourceLocation(), 5408 diag::err_multiple_mem_initialization) 5409 << Field->getDeclName() 5410 << Init->getSourceRange(); 5411 else { 5412 const Type *BaseClass = Init->getBaseClass(); 5413 assert(BaseClass && "neither field nor base"); 5414 S.Diag(Init->getSourceLocation(), 5415 diag::err_multiple_base_initialization) 5416 << QualType(BaseClass, 0) 5417 << Init->getSourceRange(); 5418 } 5419 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5420 << 0 << PrevInit->getSourceRange(); 5421 5422 return true; 5423 } 5424 5425 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5426 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5427 5428 bool CheckRedundantUnionInit(Sema &S, 5429 CXXCtorInitializer *Init, 5430 RedundantUnionMap &Unions) { 5431 FieldDecl *Field = Init->getAnyMember(); 5432 RecordDecl *Parent = Field->getParent(); 5433 NamedDecl *Child = Field; 5434 5435 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5436 if (Parent->isUnion()) { 5437 UnionEntry &En = Unions[Parent]; 5438 if (En.first && En.first != Child) { 5439 S.Diag(Init->getSourceLocation(), 5440 diag::err_multiple_mem_union_initialization) 5441 << Field->getDeclName() 5442 << Init->getSourceRange(); 5443 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5444 << 0 << En.second->getSourceRange(); 5445 return true; 5446 } 5447 if (!En.first) { 5448 En.first = Child; 5449 En.second = Init; 5450 } 5451 if (!Parent->isAnonymousStructOrUnion()) 5452 return false; 5453 } 5454 5455 Child = Parent; 5456 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5457 } 5458 5459 return false; 5460 } 5461 } // namespace 5462 5463 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5464 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5465 SourceLocation ColonLoc, 5466 ArrayRef<CXXCtorInitializer*> MemInits, 5467 bool AnyErrors) { 5468 if (!ConstructorDecl) 5469 return; 5470 5471 AdjustDeclIfTemplate(ConstructorDecl); 5472 5473 CXXConstructorDecl *Constructor 5474 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5475 5476 if (!Constructor) { 5477 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5478 return; 5479 } 5480 5481 // Mapping for the duplicate initializers check. 5482 // For member initializers, this is keyed with a FieldDecl*. 5483 // For base initializers, this is keyed with a Type*. 5484 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5485 5486 // Mapping for the inconsistent anonymous-union initializers check. 5487 RedundantUnionMap MemberUnions; 5488 5489 bool HadError = false; 5490 for (unsigned i = 0; i < MemInits.size(); i++) { 5491 CXXCtorInitializer *Init = MemInits[i]; 5492 5493 // Set the source order index. 5494 Init->setSourceOrder(i); 5495 5496 if (Init->isAnyMemberInitializer()) { 5497 const void *Key = GetKeyForMember(Context, Init); 5498 if (CheckRedundantInit(*this, Init, Members[Key]) || 5499 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5500 HadError = true; 5501 } else if (Init->isBaseInitializer()) { 5502 const void *Key = GetKeyForMember(Context, Init); 5503 if (CheckRedundantInit(*this, Init, Members[Key])) 5504 HadError = true; 5505 } else { 5506 assert(Init->isDelegatingInitializer()); 5507 // This must be the only initializer 5508 if (MemInits.size() != 1) { 5509 Diag(Init->getSourceLocation(), 5510 diag::err_delegating_initializer_alone) 5511 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5512 // We will treat this as being the only initializer. 5513 } 5514 SetDelegatingInitializer(Constructor, MemInits[i]); 5515 // Return immediately as the initializer is set. 5516 return; 5517 } 5518 } 5519 5520 if (HadError) 5521 return; 5522 5523 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5524 5525 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5526 5527 DiagnoseUninitializedFields(*this, Constructor); 5528 } 5529 5530 void 5531 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5532 CXXRecordDecl *ClassDecl) { 5533 // Ignore dependent contexts. Also ignore unions, since their members never 5534 // have destructors implicitly called. 5535 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5536 return; 5537 5538 // FIXME: all the access-control diagnostics are positioned on the 5539 // field/base declaration. That's probably good; that said, the 5540 // user might reasonably want to know why the destructor is being 5541 // emitted, and we currently don't say. 5542 5543 // Non-static data members. 5544 for (auto *Field : ClassDecl->fields()) { 5545 if (Field->isInvalidDecl()) 5546 continue; 5547 5548 // Don't destroy incomplete or zero-length arrays. 5549 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5550 continue; 5551 5552 QualType FieldType = Context.getBaseElementType(Field->getType()); 5553 5554 const RecordType* RT = FieldType->getAs<RecordType>(); 5555 if (!RT) 5556 continue; 5557 5558 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5559 if (FieldClassDecl->isInvalidDecl()) 5560 continue; 5561 if (FieldClassDecl->hasIrrelevantDestructor()) 5562 continue; 5563 // The destructor for an implicit anonymous union member is never invoked. 5564 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5565 continue; 5566 5567 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5568 assert(Dtor && "No dtor found for FieldClassDecl!"); 5569 CheckDestructorAccess(Field->getLocation(), Dtor, 5570 PDiag(diag::err_access_dtor_field) 5571 << Field->getDeclName() 5572 << FieldType); 5573 5574 MarkFunctionReferenced(Location, Dtor); 5575 DiagnoseUseOfDecl(Dtor, Location); 5576 } 5577 5578 // We only potentially invoke the destructors of potentially constructed 5579 // subobjects. 5580 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5581 5582 // If the destructor exists and has already been marked used in the MS ABI, 5583 // then virtual base destructors have already been checked and marked used. 5584 // Skip checking them again to avoid duplicate diagnostics. 5585 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5586 CXXDestructorDecl *Dtor = ClassDecl->getDestructor(); 5587 if (Dtor && Dtor->isUsed()) 5588 VisitVirtualBases = false; 5589 } 5590 5591 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5592 5593 // Bases. 5594 for (const auto &Base : ClassDecl->bases()) { 5595 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5596 if (!RT) 5597 continue; 5598 5599 // Remember direct virtual bases. 5600 if (Base.isVirtual()) { 5601 if (!VisitVirtualBases) 5602 continue; 5603 DirectVirtualBases.insert(RT); 5604 } 5605 5606 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5607 // If our base class is invalid, we probably can't get its dtor anyway. 5608 if (BaseClassDecl->isInvalidDecl()) 5609 continue; 5610 if (BaseClassDecl->hasIrrelevantDestructor()) 5611 continue; 5612 5613 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5614 assert(Dtor && "No dtor found for BaseClassDecl!"); 5615 5616 // FIXME: caret should be on the start of the class name 5617 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5618 PDiag(diag::err_access_dtor_base) 5619 << Base.getType() << Base.getSourceRange(), 5620 Context.getTypeDeclType(ClassDecl)); 5621 5622 MarkFunctionReferenced(Location, Dtor); 5623 DiagnoseUseOfDecl(Dtor, Location); 5624 } 5625 5626 if (VisitVirtualBases) 5627 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl, 5628 &DirectVirtualBases); 5629 } 5630 5631 void Sema::MarkVirtualBaseDestructorsReferenced( 5632 SourceLocation Location, CXXRecordDecl *ClassDecl, 5633 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) { 5634 // Virtual bases. 5635 for (const auto &VBase : ClassDecl->vbases()) { 5636 // Bases are always records in a well-formed non-dependent class. 5637 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5638 5639 // Ignore already visited direct virtual bases. 5640 if (DirectVirtualBases && DirectVirtualBases->count(RT)) 5641 continue; 5642 5643 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5644 // If our base class is invalid, we probably can't get its dtor anyway. 5645 if (BaseClassDecl->isInvalidDecl()) 5646 continue; 5647 if (BaseClassDecl->hasIrrelevantDestructor()) 5648 continue; 5649 5650 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5651 assert(Dtor && "No dtor found for BaseClassDecl!"); 5652 if (CheckDestructorAccess( 5653 ClassDecl->getLocation(), Dtor, 5654 PDiag(diag::err_access_dtor_vbase) 5655 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5656 Context.getTypeDeclType(ClassDecl)) == 5657 AR_accessible) { 5658 CheckDerivedToBaseConversion( 5659 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5660 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5661 SourceRange(), DeclarationName(), nullptr); 5662 } 5663 5664 MarkFunctionReferenced(Location, Dtor); 5665 DiagnoseUseOfDecl(Dtor, Location); 5666 } 5667 } 5668 5669 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5670 if (!CDtorDecl) 5671 return; 5672 5673 if (CXXConstructorDecl *Constructor 5674 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5675 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5676 DiagnoseUninitializedFields(*this, Constructor); 5677 } 5678 } 5679 5680 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5681 if (!getLangOpts().CPlusPlus) 5682 return false; 5683 5684 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5685 if (!RD) 5686 return false; 5687 5688 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5689 // class template specialization here, but doing so breaks a lot of code. 5690 5691 // We can't answer whether something is abstract until it has a 5692 // definition. If it's currently being defined, we'll walk back 5693 // over all the declarations when we have a full definition. 5694 const CXXRecordDecl *Def = RD->getDefinition(); 5695 if (!Def || Def->isBeingDefined()) 5696 return false; 5697 5698 return RD->isAbstract(); 5699 } 5700 5701 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5702 TypeDiagnoser &Diagnoser) { 5703 if (!isAbstractType(Loc, T)) 5704 return false; 5705 5706 T = Context.getBaseElementType(T); 5707 Diagnoser.diagnose(*this, Loc, T); 5708 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5709 return true; 5710 } 5711 5712 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5713 // Check if we've already emitted the list of pure virtual functions 5714 // for this class. 5715 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5716 return; 5717 5718 // If the diagnostic is suppressed, don't emit the notes. We're only 5719 // going to emit them once, so try to attach them to a diagnostic we're 5720 // actually going to show. 5721 if (Diags.isLastDiagnosticIgnored()) 5722 return; 5723 5724 CXXFinalOverriderMap FinalOverriders; 5725 RD->getFinalOverriders(FinalOverriders); 5726 5727 // Keep a set of seen pure methods so we won't diagnose the same method 5728 // more than once. 5729 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5730 5731 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5732 MEnd = FinalOverriders.end(); 5733 M != MEnd; 5734 ++M) { 5735 for (OverridingMethods::iterator SO = M->second.begin(), 5736 SOEnd = M->second.end(); 5737 SO != SOEnd; ++SO) { 5738 // C++ [class.abstract]p4: 5739 // A class is abstract if it contains or inherits at least one 5740 // pure virtual function for which the final overrider is pure 5741 // virtual. 5742 5743 // 5744 if (SO->second.size() != 1) 5745 continue; 5746 5747 if (!SO->second.front().Method->isPure()) 5748 continue; 5749 5750 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5751 continue; 5752 5753 Diag(SO->second.front().Method->getLocation(), 5754 diag::note_pure_virtual_function) 5755 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5756 } 5757 } 5758 5759 if (!PureVirtualClassDiagSet) 5760 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5761 PureVirtualClassDiagSet->insert(RD); 5762 } 5763 5764 namespace { 5765 struct AbstractUsageInfo { 5766 Sema &S; 5767 CXXRecordDecl *Record; 5768 CanQualType AbstractType; 5769 bool Invalid; 5770 5771 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5772 : S(S), Record(Record), 5773 AbstractType(S.Context.getCanonicalType( 5774 S.Context.getTypeDeclType(Record))), 5775 Invalid(false) {} 5776 5777 void DiagnoseAbstractType() { 5778 if (Invalid) return; 5779 S.DiagnoseAbstractType(Record); 5780 Invalid = true; 5781 } 5782 5783 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5784 }; 5785 5786 struct CheckAbstractUsage { 5787 AbstractUsageInfo &Info; 5788 const NamedDecl *Ctx; 5789 5790 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5791 : Info(Info), Ctx(Ctx) {} 5792 5793 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5794 switch (TL.getTypeLocClass()) { 5795 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5796 #define TYPELOC(CLASS, PARENT) \ 5797 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5798 #include "clang/AST/TypeLocNodes.def" 5799 } 5800 } 5801 5802 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5803 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5804 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5805 if (!TL.getParam(I)) 5806 continue; 5807 5808 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5809 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5810 } 5811 } 5812 5813 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5814 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5815 } 5816 5817 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5818 // Visit the type parameters from a permissive context. 5819 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5820 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5821 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5822 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5823 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5824 // TODO: other template argument types? 5825 } 5826 } 5827 5828 // Visit pointee types from a permissive context. 5829 #define CheckPolymorphic(Type) \ 5830 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5831 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5832 } 5833 CheckPolymorphic(PointerTypeLoc) 5834 CheckPolymorphic(ReferenceTypeLoc) 5835 CheckPolymorphic(MemberPointerTypeLoc) 5836 CheckPolymorphic(BlockPointerTypeLoc) 5837 CheckPolymorphic(AtomicTypeLoc) 5838 5839 /// Handle all the types we haven't given a more specific 5840 /// implementation for above. 5841 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5842 // Every other kind of type that we haven't called out already 5843 // that has an inner type is either (1) sugar or (2) contains that 5844 // inner type in some way as a subobject. 5845 if (TypeLoc Next = TL.getNextTypeLoc()) 5846 return Visit(Next, Sel); 5847 5848 // If there's no inner type and we're in a permissive context, 5849 // don't diagnose. 5850 if (Sel == Sema::AbstractNone) return; 5851 5852 // Check whether the type matches the abstract type. 5853 QualType T = TL.getType(); 5854 if (T->isArrayType()) { 5855 Sel = Sema::AbstractArrayType; 5856 T = Info.S.Context.getBaseElementType(T); 5857 } 5858 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5859 if (CT != Info.AbstractType) return; 5860 5861 // It matched; do some magic. 5862 if (Sel == Sema::AbstractArrayType) { 5863 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5864 << T << TL.getSourceRange(); 5865 } else { 5866 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5867 << Sel << T << TL.getSourceRange(); 5868 } 5869 Info.DiagnoseAbstractType(); 5870 } 5871 }; 5872 5873 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5874 Sema::AbstractDiagSelID Sel) { 5875 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5876 } 5877 5878 } 5879 5880 /// Check for invalid uses of an abstract type in a method declaration. 5881 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5882 CXXMethodDecl *MD) { 5883 // No need to do the check on definitions, which require that 5884 // the return/param types be complete. 5885 if (MD->doesThisDeclarationHaveABody()) 5886 return; 5887 5888 // For safety's sake, just ignore it if we don't have type source 5889 // information. This should never happen for non-implicit methods, 5890 // but... 5891 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5892 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5893 } 5894 5895 /// Check for invalid uses of an abstract type within a class definition. 5896 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5897 CXXRecordDecl *RD) { 5898 for (auto *D : RD->decls()) { 5899 if (D->isImplicit()) continue; 5900 5901 // Methods and method templates. 5902 if (isa<CXXMethodDecl>(D)) { 5903 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5904 } else if (isa<FunctionTemplateDecl>(D)) { 5905 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5906 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5907 5908 // Fields and static variables. 5909 } else if (isa<FieldDecl>(D)) { 5910 FieldDecl *FD = cast<FieldDecl>(D); 5911 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5912 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5913 } else if (isa<VarDecl>(D)) { 5914 VarDecl *VD = cast<VarDecl>(D); 5915 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5916 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5917 5918 // Nested classes and class templates. 5919 } else if (isa<CXXRecordDecl>(D)) { 5920 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5921 } else if (isa<ClassTemplateDecl>(D)) { 5922 CheckAbstractClassUsage(Info, 5923 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5924 } 5925 } 5926 } 5927 5928 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5929 Attr *ClassAttr = getDLLAttr(Class); 5930 if (!ClassAttr) 5931 return; 5932 5933 assert(ClassAttr->getKind() == attr::DLLExport); 5934 5935 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5936 5937 if (TSK == TSK_ExplicitInstantiationDeclaration) 5938 // Don't go any further if this is just an explicit instantiation 5939 // declaration. 5940 return; 5941 5942 // Add a context note to explain how we got to any diagnostics produced below. 5943 struct MarkingClassDllexported { 5944 Sema &S; 5945 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class, 5946 SourceLocation AttrLoc) 5947 : S(S) { 5948 Sema::CodeSynthesisContext Ctx; 5949 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported; 5950 Ctx.PointOfInstantiation = AttrLoc; 5951 Ctx.Entity = Class; 5952 S.pushCodeSynthesisContext(Ctx); 5953 } 5954 ~MarkingClassDllexported() { 5955 S.popCodeSynthesisContext(); 5956 } 5957 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); 5958 5959 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5960 S.MarkVTableUsed(Class->getLocation(), Class, true); 5961 5962 for (Decl *Member : Class->decls()) { 5963 // Defined static variables that are members of an exported base 5964 // class must be marked export too. 5965 auto *VD = dyn_cast<VarDecl>(Member); 5966 if (VD && Member->getAttr<DLLExportAttr>() && 5967 VD->getStorageClass() == SC_Static && 5968 TSK == TSK_ImplicitInstantiation) 5969 S.MarkVariableReferenced(VD->getLocation(), VD); 5970 5971 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5972 if (!MD) 5973 continue; 5974 5975 if (Member->getAttr<DLLExportAttr>()) { 5976 if (MD->isUserProvided()) { 5977 // Instantiate non-default class member functions ... 5978 5979 // .. except for certain kinds of template specializations. 5980 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5981 continue; 5982 5983 S.MarkFunctionReferenced(Class->getLocation(), MD); 5984 5985 // The function will be passed to the consumer when its definition is 5986 // encountered. 5987 } else if (MD->isExplicitlyDefaulted()) { 5988 // Synthesize and instantiate explicitly defaulted methods. 5989 S.MarkFunctionReferenced(Class->getLocation(), MD); 5990 5991 if (TSK != TSK_ExplicitInstantiationDefinition) { 5992 // Except for explicit instantiation defs, we will not see the 5993 // definition again later, so pass it to the consumer now. 5994 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5995 } 5996 } else if (!MD->isTrivial() || 5997 MD->isCopyAssignmentOperator() || 5998 MD->isMoveAssignmentOperator()) { 5999 // Synthesize and instantiate non-trivial implicit methods, and the copy 6000 // and move assignment operators. The latter are exported even if they 6001 // are trivial, because the address of an operator can be taken and 6002 // should compare equal across libraries. 6003 S.MarkFunctionReferenced(Class->getLocation(), MD); 6004 6005 // There is no later point when we will see the definition of this 6006 // function, so pass it to the consumer now. 6007 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 6008 } 6009 } 6010 } 6011 } 6012 6013 static void checkForMultipleExportedDefaultConstructors(Sema &S, 6014 CXXRecordDecl *Class) { 6015 // Only the MS ABI has default constructor closures, so we don't need to do 6016 // this semantic checking anywhere else. 6017 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 6018 return; 6019 6020 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 6021 for (Decl *Member : Class->decls()) { 6022 // Look for exported default constructors. 6023 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 6024 if (!CD || !CD->isDefaultConstructor()) 6025 continue; 6026 auto *Attr = CD->getAttr<DLLExportAttr>(); 6027 if (!Attr) 6028 continue; 6029 6030 // If the class is non-dependent, mark the default arguments as ODR-used so 6031 // that we can properly codegen the constructor closure. 6032 if (!Class->isDependentContext()) { 6033 for (ParmVarDecl *PD : CD->parameters()) { 6034 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 6035 S.DiscardCleanupsInEvaluationContext(); 6036 } 6037 } 6038 6039 if (LastExportedDefaultCtor) { 6040 S.Diag(LastExportedDefaultCtor->getLocation(), 6041 diag::err_attribute_dll_ambiguous_default_ctor) 6042 << Class; 6043 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 6044 << CD->getDeclName(); 6045 return; 6046 } 6047 LastExportedDefaultCtor = CD; 6048 } 6049 } 6050 6051 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, 6052 CXXRecordDecl *Class) { 6053 bool ErrorReported = false; 6054 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6055 ClassTemplateDecl *TD) { 6056 if (ErrorReported) 6057 return; 6058 S.Diag(TD->getLocation(), 6059 diag::err_cuda_device_builtin_surftex_cls_template) 6060 << /*surface*/ 0 << TD; 6061 ErrorReported = true; 6062 }; 6063 6064 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6065 if (!TD) { 6066 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6067 if (!SD) { 6068 S.Diag(Class->getLocation(), 6069 diag::err_cuda_device_builtin_surftex_ref_decl) 6070 << /*surface*/ 0 << Class; 6071 S.Diag(Class->getLocation(), 6072 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6073 << Class; 6074 return; 6075 } 6076 TD = SD->getSpecializedTemplate(); 6077 } 6078 6079 TemplateParameterList *Params = TD->getTemplateParameters(); 6080 unsigned N = Params->size(); 6081 6082 if (N != 2) { 6083 reportIllegalClassTemplate(S, TD); 6084 S.Diag(TD->getLocation(), 6085 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6086 << TD << 2; 6087 } 6088 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6089 reportIllegalClassTemplate(S, TD); 6090 S.Diag(TD->getLocation(), 6091 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6092 << TD << /*1st*/ 0 << /*type*/ 0; 6093 } 6094 if (N > 1) { 6095 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6096 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6097 reportIllegalClassTemplate(S, TD); 6098 S.Diag(TD->getLocation(), 6099 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6100 << TD << /*2nd*/ 1 << /*integer*/ 1; 6101 } 6102 } 6103 } 6104 6105 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, 6106 CXXRecordDecl *Class) { 6107 bool ErrorReported = false; 6108 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6109 ClassTemplateDecl *TD) { 6110 if (ErrorReported) 6111 return; 6112 S.Diag(TD->getLocation(), 6113 diag::err_cuda_device_builtin_surftex_cls_template) 6114 << /*texture*/ 1 << TD; 6115 ErrorReported = true; 6116 }; 6117 6118 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6119 if (!TD) { 6120 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6121 if (!SD) { 6122 S.Diag(Class->getLocation(), 6123 diag::err_cuda_device_builtin_surftex_ref_decl) 6124 << /*texture*/ 1 << Class; 6125 S.Diag(Class->getLocation(), 6126 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6127 << Class; 6128 return; 6129 } 6130 TD = SD->getSpecializedTemplate(); 6131 } 6132 6133 TemplateParameterList *Params = TD->getTemplateParameters(); 6134 unsigned N = Params->size(); 6135 6136 if (N != 3) { 6137 reportIllegalClassTemplate(S, TD); 6138 S.Diag(TD->getLocation(), 6139 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6140 << TD << 3; 6141 } 6142 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6143 reportIllegalClassTemplate(S, TD); 6144 S.Diag(TD->getLocation(), 6145 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6146 << TD << /*1st*/ 0 << /*type*/ 0; 6147 } 6148 if (N > 1) { 6149 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6150 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6151 reportIllegalClassTemplate(S, TD); 6152 S.Diag(TD->getLocation(), 6153 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6154 << TD << /*2nd*/ 1 << /*integer*/ 1; 6155 } 6156 } 6157 if (N > 2) { 6158 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2)); 6159 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6160 reportIllegalClassTemplate(S, TD); 6161 S.Diag(TD->getLocation(), 6162 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6163 << TD << /*3rd*/ 2 << /*integer*/ 1; 6164 } 6165 } 6166 } 6167 6168 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 6169 // Mark any compiler-generated routines with the implicit code_seg attribute. 6170 for (auto *Method : Class->methods()) { 6171 if (Method->isUserProvided()) 6172 continue; 6173 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 6174 Method->addAttr(A); 6175 } 6176 } 6177 6178 /// Check class-level dllimport/dllexport attribute. 6179 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 6180 Attr *ClassAttr = getDLLAttr(Class); 6181 6182 // MSVC inherits DLL attributes to partial class template specializations. 6183 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) { 6184 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 6185 if (Attr *TemplateAttr = 6186 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 6187 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 6188 A->setInherited(true); 6189 ClassAttr = A; 6190 } 6191 } 6192 } 6193 6194 if (!ClassAttr) 6195 return; 6196 6197 if (!Class->isExternallyVisible()) { 6198 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 6199 << Class << ClassAttr; 6200 return; 6201 } 6202 6203 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6204 !ClassAttr->isInherited()) { 6205 // Diagnose dll attributes on members of class with dll attribute. 6206 for (Decl *Member : Class->decls()) { 6207 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 6208 continue; 6209 InheritableAttr *MemberAttr = getDLLAttr(Member); 6210 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 6211 continue; 6212 6213 Diag(MemberAttr->getLocation(), 6214 diag::err_attribute_dll_member_of_dll_class) 6215 << MemberAttr << ClassAttr; 6216 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 6217 Member->setInvalidDecl(); 6218 } 6219 } 6220 6221 if (Class->getDescribedClassTemplate()) 6222 // Don't inherit dll attribute until the template is instantiated. 6223 return; 6224 6225 // The class is either imported or exported. 6226 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 6227 6228 // Check if this was a dllimport attribute propagated from a derived class to 6229 // a base class template specialization. We don't apply these attributes to 6230 // static data members. 6231 const bool PropagatedImport = 6232 !ClassExported && 6233 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 6234 6235 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6236 6237 // Ignore explicit dllexport on explicit class template instantiation 6238 // declarations, except in MinGW mode. 6239 if (ClassExported && !ClassAttr->isInherited() && 6240 TSK == TSK_ExplicitInstantiationDeclaration && 6241 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 6242 Class->dropAttr<DLLExportAttr>(); 6243 return; 6244 } 6245 6246 // Force declaration of implicit members so they can inherit the attribute. 6247 ForceDeclarationOfImplicitMembers(Class); 6248 6249 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 6250 // seem to be true in practice? 6251 6252 for (Decl *Member : Class->decls()) { 6253 VarDecl *VD = dyn_cast<VarDecl>(Member); 6254 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 6255 6256 // Only methods and static fields inherit the attributes. 6257 if (!VD && !MD) 6258 continue; 6259 6260 if (MD) { 6261 // Don't process deleted methods. 6262 if (MD->isDeleted()) 6263 continue; 6264 6265 if (MD->isInlined()) { 6266 // MinGW does not import or export inline methods. But do it for 6267 // template instantiations. 6268 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6269 TSK != TSK_ExplicitInstantiationDeclaration && 6270 TSK != TSK_ExplicitInstantiationDefinition) 6271 continue; 6272 6273 // MSVC versions before 2015 don't export the move assignment operators 6274 // and move constructor, so don't attempt to import/export them if 6275 // we have a definition. 6276 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 6277 if ((MD->isMoveAssignmentOperator() || 6278 (Ctor && Ctor->isMoveConstructor())) && 6279 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 6280 continue; 6281 6282 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 6283 // operator is exported anyway. 6284 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6285 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 6286 continue; 6287 } 6288 } 6289 6290 // Don't apply dllimport attributes to static data members of class template 6291 // instantiations when the attribute is propagated from a derived class. 6292 if (VD && PropagatedImport) 6293 continue; 6294 6295 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6296 continue; 6297 6298 if (!getDLLAttr(Member)) { 6299 InheritableAttr *NewAttr = nullptr; 6300 6301 // Do not export/import inline function when -fno-dllexport-inlines is 6302 // passed. But add attribute for later local static var check. 6303 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6304 TSK != TSK_ExplicitInstantiationDeclaration && 6305 TSK != TSK_ExplicitInstantiationDefinition) { 6306 if (ClassExported) { 6307 NewAttr = ::new (getASTContext()) 6308 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6309 } else { 6310 NewAttr = ::new (getASTContext()) 6311 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6312 } 6313 } else { 6314 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6315 } 6316 6317 NewAttr->setInherited(true); 6318 Member->addAttr(NewAttr); 6319 6320 if (MD) { 6321 // Propagate DLLAttr to friend re-declarations of MD that have already 6322 // been constructed. 6323 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6324 FD = FD->getPreviousDecl()) { 6325 if (FD->getFriendObjectKind() == Decl::FOK_None) 6326 continue; 6327 assert(!getDLLAttr(FD) && 6328 "friend re-decl should not already have a DLLAttr"); 6329 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6330 NewAttr->setInherited(true); 6331 FD->addAttr(NewAttr); 6332 } 6333 } 6334 } 6335 } 6336 6337 if (ClassExported) 6338 DelayedDllExportClasses.push_back(Class); 6339 } 6340 6341 /// Perform propagation of DLL attributes from a derived class to a 6342 /// templated base class for MS compatibility. 6343 void Sema::propagateDLLAttrToBaseClassTemplate( 6344 CXXRecordDecl *Class, Attr *ClassAttr, 6345 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6346 if (getDLLAttr( 6347 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6348 // If the base class template has a DLL attribute, don't try to change it. 6349 return; 6350 } 6351 6352 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6353 if (!getDLLAttr(BaseTemplateSpec) && 6354 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6355 TSK == TSK_ImplicitInstantiation)) { 6356 // The template hasn't been instantiated yet (or it has, but only as an 6357 // explicit instantiation declaration or implicit instantiation, which means 6358 // we haven't codegenned any members yet), so propagate the attribute. 6359 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6360 NewAttr->setInherited(true); 6361 BaseTemplateSpec->addAttr(NewAttr); 6362 6363 // If this was an import, mark that we propagated it from a derived class to 6364 // a base class template specialization. 6365 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6366 ImportAttr->setPropagatedToBaseTemplate(); 6367 6368 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6369 // needs to be run again to work see the new attribute. Otherwise this will 6370 // get run whenever the template is instantiated. 6371 if (TSK != TSK_Undeclared) 6372 checkClassLevelDLLAttribute(BaseTemplateSpec); 6373 6374 return; 6375 } 6376 6377 if (getDLLAttr(BaseTemplateSpec)) { 6378 // The template has already been specialized or instantiated with an 6379 // attribute, explicitly or through propagation. We should not try to change 6380 // it. 6381 return; 6382 } 6383 6384 // The template was previously instantiated or explicitly specialized without 6385 // a dll attribute, It's too late for us to add an attribute, so warn that 6386 // this is unsupported. 6387 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6388 << BaseTemplateSpec->isExplicitSpecialization(); 6389 Diag(ClassAttr->getLocation(), diag::note_attribute); 6390 if (BaseTemplateSpec->isExplicitSpecialization()) { 6391 Diag(BaseTemplateSpec->getLocation(), 6392 diag::note_template_class_explicit_specialization_was_here) 6393 << BaseTemplateSpec; 6394 } else { 6395 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6396 diag::note_template_class_instantiation_was_here) 6397 << BaseTemplateSpec; 6398 } 6399 } 6400 6401 /// Determine the kind of defaulting that would be done for a given function. 6402 /// 6403 /// If the function is both a default constructor and a copy / move constructor 6404 /// (due to having a default argument for the first parameter), this picks 6405 /// CXXDefaultConstructor. 6406 /// 6407 /// FIXME: Check that case is properly handled by all callers. 6408 Sema::DefaultedFunctionKind 6409 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6410 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6411 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6412 if (Ctor->isDefaultConstructor()) 6413 return Sema::CXXDefaultConstructor; 6414 6415 if (Ctor->isCopyConstructor()) 6416 return Sema::CXXCopyConstructor; 6417 6418 if (Ctor->isMoveConstructor()) 6419 return Sema::CXXMoveConstructor; 6420 } 6421 6422 if (MD->isCopyAssignmentOperator()) 6423 return Sema::CXXCopyAssignment; 6424 6425 if (MD->isMoveAssignmentOperator()) 6426 return Sema::CXXMoveAssignment; 6427 6428 if (isa<CXXDestructorDecl>(FD)) 6429 return Sema::CXXDestructor; 6430 } 6431 6432 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6433 case OO_EqualEqual: 6434 return DefaultedComparisonKind::Equal; 6435 6436 case OO_ExclaimEqual: 6437 return DefaultedComparisonKind::NotEqual; 6438 6439 case OO_Spaceship: 6440 // No point allowing this if <=> doesn't exist in the current language mode. 6441 if (!getLangOpts().CPlusPlus20) 6442 break; 6443 return DefaultedComparisonKind::ThreeWay; 6444 6445 case OO_Less: 6446 case OO_LessEqual: 6447 case OO_Greater: 6448 case OO_GreaterEqual: 6449 // No point allowing this if <=> doesn't exist in the current language mode. 6450 if (!getLangOpts().CPlusPlus20) 6451 break; 6452 return DefaultedComparisonKind::Relational; 6453 6454 default: 6455 break; 6456 } 6457 6458 // Not defaultable. 6459 return DefaultedFunctionKind(); 6460 } 6461 6462 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, 6463 SourceLocation DefaultLoc) { 6464 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD); 6465 if (DFK.isComparison()) 6466 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison()); 6467 6468 switch (DFK.asSpecialMember()) { 6469 case Sema::CXXDefaultConstructor: 6470 S.DefineImplicitDefaultConstructor(DefaultLoc, 6471 cast<CXXConstructorDecl>(FD)); 6472 break; 6473 case Sema::CXXCopyConstructor: 6474 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6475 break; 6476 case Sema::CXXCopyAssignment: 6477 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6478 break; 6479 case Sema::CXXDestructor: 6480 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD)); 6481 break; 6482 case Sema::CXXMoveConstructor: 6483 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6484 break; 6485 case Sema::CXXMoveAssignment: 6486 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6487 break; 6488 case Sema::CXXInvalid: 6489 llvm_unreachable("Invalid special member."); 6490 } 6491 } 6492 6493 /// Determine whether a type is permitted to be passed or returned in 6494 /// registers, per C++ [class.temporary]p3. 6495 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6496 TargetInfo::CallingConvKind CCK) { 6497 if (D->isDependentType() || D->isInvalidDecl()) 6498 return false; 6499 6500 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6501 // The PS4 platform ABI follows the behavior of Clang 3.2. 6502 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6503 return !D->hasNonTrivialDestructorForCall() && 6504 !D->hasNonTrivialCopyConstructorForCall(); 6505 6506 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6507 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6508 bool DtorIsTrivialForCall = false; 6509 6510 // If a class has at least one non-deleted, trivial copy constructor, it 6511 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6512 // 6513 // Note: This permits classes with non-trivial copy or move ctors to be 6514 // passed in registers, so long as they *also* have a trivial copy ctor, 6515 // which is non-conforming. 6516 if (D->needsImplicitCopyConstructor()) { 6517 if (!D->defaultedCopyConstructorIsDeleted()) { 6518 if (D->hasTrivialCopyConstructor()) 6519 CopyCtorIsTrivial = true; 6520 if (D->hasTrivialCopyConstructorForCall()) 6521 CopyCtorIsTrivialForCall = true; 6522 } 6523 } else { 6524 for (const CXXConstructorDecl *CD : D->ctors()) { 6525 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6526 if (CD->isTrivial()) 6527 CopyCtorIsTrivial = true; 6528 if (CD->isTrivialForCall()) 6529 CopyCtorIsTrivialForCall = true; 6530 } 6531 } 6532 } 6533 6534 if (D->needsImplicitDestructor()) { 6535 if (!D->defaultedDestructorIsDeleted() && 6536 D->hasTrivialDestructorForCall()) 6537 DtorIsTrivialForCall = true; 6538 } else if (const auto *DD = D->getDestructor()) { 6539 if (!DD->isDeleted() && DD->isTrivialForCall()) 6540 DtorIsTrivialForCall = true; 6541 } 6542 6543 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6544 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6545 return true; 6546 6547 // If a class has a destructor, we'd really like to pass it indirectly 6548 // because it allows us to elide copies. Unfortunately, MSVC makes that 6549 // impossible for small types, which it will pass in a single register or 6550 // stack slot. Most objects with dtors are large-ish, so handle that early. 6551 // We can't call out all large objects as being indirect because there are 6552 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6553 // how we pass large POD types. 6554 6555 // Note: This permits small classes with nontrivial destructors to be 6556 // passed in registers, which is non-conforming. 6557 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6558 uint64_t TypeSize = isAArch64 ? 128 : 64; 6559 6560 if (CopyCtorIsTrivial && 6561 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6562 return true; 6563 return false; 6564 } 6565 6566 // Per C++ [class.temporary]p3, the relevant condition is: 6567 // each copy constructor, move constructor, and destructor of X is 6568 // either trivial or deleted, and X has at least one non-deleted copy 6569 // or move constructor 6570 bool HasNonDeletedCopyOrMove = false; 6571 6572 if (D->needsImplicitCopyConstructor() && 6573 !D->defaultedCopyConstructorIsDeleted()) { 6574 if (!D->hasTrivialCopyConstructorForCall()) 6575 return false; 6576 HasNonDeletedCopyOrMove = true; 6577 } 6578 6579 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6580 !D->defaultedMoveConstructorIsDeleted()) { 6581 if (!D->hasTrivialMoveConstructorForCall()) 6582 return false; 6583 HasNonDeletedCopyOrMove = true; 6584 } 6585 6586 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6587 !D->hasTrivialDestructorForCall()) 6588 return false; 6589 6590 for (const CXXMethodDecl *MD : D->methods()) { 6591 if (MD->isDeleted()) 6592 continue; 6593 6594 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6595 if (CD && CD->isCopyOrMoveConstructor()) 6596 HasNonDeletedCopyOrMove = true; 6597 else if (!isa<CXXDestructorDecl>(MD)) 6598 continue; 6599 6600 if (!MD->isTrivialForCall()) 6601 return false; 6602 } 6603 6604 return HasNonDeletedCopyOrMove; 6605 } 6606 6607 /// Report an error regarding overriding, along with any relevant 6608 /// overridden methods. 6609 /// 6610 /// \param DiagID the primary error to report. 6611 /// \param MD the overriding method. 6612 static bool 6613 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, 6614 llvm::function_ref<bool(const CXXMethodDecl *)> Report) { 6615 bool IssuedDiagnostic = false; 6616 for (const CXXMethodDecl *O : MD->overridden_methods()) { 6617 if (Report(O)) { 6618 if (!IssuedDiagnostic) { 6619 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6620 IssuedDiagnostic = true; 6621 } 6622 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 6623 } 6624 } 6625 return IssuedDiagnostic; 6626 } 6627 6628 /// Perform semantic checks on a class definition that has been 6629 /// completing, introducing implicitly-declared members, checking for 6630 /// abstract types, etc. 6631 /// 6632 /// \param S The scope in which the class was parsed. Null if we didn't just 6633 /// parse a class definition. 6634 /// \param Record The completed class. 6635 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6636 if (!Record) 6637 return; 6638 6639 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6640 AbstractUsageInfo Info(*this, Record); 6641 CheckAbstractClassUsage(Info, Record); 6642 } 6643 6644 // If this is not an aggregate type and has no user-declared constructor, 6645 // complain about any non-static data members of reference or const scalar 6646 // type, since they will never get initializers. 6647 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6648 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6649 !Record->isLambda()) { 6650 bool Complained = false; 6651 for (const auto *F : Record->fields()) { 6652 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6653 continue; 6654 6655 if (F->getType()->isReferenceType() || 6656 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6657 if (!Complained) { 6658 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6659 << Record->getTagKind() << Record; 6660 Complained = true; 6661 } 6662 6663 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6664 << F->getType()->isReferenceType() 6665 << F->getDeclName(); 6666 } 6667 } 6668 } 6669 6670 if (Record->getIdentifier()) { 6671 // C++ [class.mem]p13: 6672 // If T is the name of a class, then each of the following shall have a 6673 // name different from T: 6674 // - every member of every anonymous union that is a member of class T. 6675 // 6676 // C++ [class.mem]p14: 6677 // In addition, if class T has a user-declared constructor (12.1), every 6678 // non-static data member of class T shall have a name different from T. 6679 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6680 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6681 ++I) { 6682 NamedDecl *D = (*I)->getUnderlyingDecl(); 6683 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6684 Record->hasUserDeclaredConstructor()) || 6685 isa<IndirectFieldDecl>(D)) { 6686 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6687 << D->getDeclName(); 6688 break; 6689 } 6690 } 6691 } 6692 6693 // Warn if the class has virtual methods but non-virtual public destructor. 6694 if (Record->isPolymorphic() && !Record->isDependentType()) { 6695 CXXDestructorDecl *dtor = Record->getDestructor(); 6696 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6697 !Record->hasAttr<FinalAttr>()) 6698 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6699 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6700 } 6701 6702 if (Record->isAbstract()) { 6703 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6704 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6705 << FA->isSpelledAsSealed(); 6706 DiagnoseAbstractType(Record); 6707 } 6708 } 6709 6710 // Warn if the class has a final destructor but is not itself marked final. 6711 if (!Record->hasAttr<FinalAttr>()) { 6712 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6713 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6714 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6715 << FA->isSpelledAsSealed() 6716 << FixItHint::CreateInsertion( 6717 getLocForEndOfToken(Record->getLocation()), 6718 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6719 Diag(Record->getLocation(), 6720 diag::note_final_dtor_non_final_class_silence) 6721 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6722 } 6723 } 6724 } 6725 6726 // See if trivial_abi has to be dropped. 6727 if (Record->hasAttr<TrivialABIAttr>()) 6728 checkIllFormedTrivialABIStruct(*Record); 6729 6730 // Set HasTrivialSpecialMemberForCall if the record has attribute 6731 // "trivial_abi". 6732 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6733 6734 if (HasTrivialABI) 6735 Record->setHasTrivialSpecialMemberForCall(); 6736 6737 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6738 // We check these last because they can depend on the properties of the 6739 // primary comparison functions (==, <=>). 6740 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6741 6742 // Perform checks that can't be done until we know all the properties of a 6743 // member function (whether it's defaulted, deleted, virtual, overriding, 6744 // ...). 6745 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) { 6746 // A static function cannot override anything. 6747 if (MD->getStorageClass() == SC_Static) { 6748 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD, 6749 [](const CXXMethodDecl *) { return true; })) 6750 return; 6751 } 6752 6753 // A deleted function cannot override a non-deleted function and vice 6754 // versa. 6755 if (ReportOverrides(*this, 6756 MD->isDeleted() ? diag::err_deleted_override 6757 : diag::err_non_deleted_override, 6758 MD, [&](const CXXMethodDecl *V) { 6759 return MD->isDeleted() != V->isDeleted(); 6760 })) { 6761 if (MD->isDefaulted() && MD->isDeleted()) 6762 // Explain why this defaulted function was deleted. 6763 DiagnoseDeletedDefaultedFunction(MD); 6764 return; 6765 } 6766 6767 // A consteval function cannot override a non-consteval function and vice 6768 // versa. 6769 if (ReportOverrides(*this, 6770 MD->isConsteval() ? diag::err_consteval_override 6771 : diag::err_non_consteval_override, 6772 MD, [&](const CXXMethodDecl *V) { 6773 return MD->isConsteval() != V->isConsteval(); 6774 })) { 6775 if (MD->isDefaulted() && MD->isDeleted()) 6776 // Explain why this defaulted function was deleted. 6777 DiagnoseDeletedDefaultedFunction(MD); 6778 return; 6779 } 6780 }; 6781 6782 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool { 6783 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6784 return false; 6785 6786 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6787 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6788 DFK.asComparison() == DefaultedComparisonKind::Relational) { 6789 DefaultedSecondaryComparisons.push_back(FD); 6790 return true; 6791 } 6792 6793 CheckExplicitlyDefaultedFunction(S, FD); 6794 return false; 6795 }; 6796 6797 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6798 // Check whether the explicitly-defaulted members are valid. 6799 bool Incomplete = CheckForDefaultedFunction(M); 6800 6801 // Skip the rest of the checks for a member of a dependent class. 6802 if (Record->isDependentType()) 6803 return; 6804 6805 // For an explicitly defaulted or deleted special member, we defer 6806 // determining triviality until the class is complete. That time is now! 6807 CXXSpecialMember CSM = getSpecialMember(M); 6808 if (!M->isImplicit() && !M->isUserProvided()) { 6809 if (CSM != CXXInvalid) { 6810 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6811 // Inform the class that we've finished declaring this member. 6812 Record->finishedDefaultedOrDeletedMember(M); 6813 M->setTrivialForCall( 6814 HasTrivialABI || 6815 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6816 Record->setTrivialForCallFlags(M); 6817 } 6818 } 6819 6820 // Set triviality for the purpose of calls if this is a user-provided 6821 // copy/move constructor or destructor. 6822 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6823 CSM == CXXDestructor) && M->isUserProvided()) { 6824 M->setTrivialForCall(HasTrivialABI); 6825 Record->setTrivialForCallFlags(M); 6826 } 6827 6828 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6829 M->hasAttr<DLLExportAttr>()) { 6830 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6831 M->isTrivial() && 6832 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6833 CSM == CXXDestructor)) 6834 M->dropAttr<DLLExportAttr>(); 6835 6836 if (M->hasAttr<DLLExportAttr>()) { 6837 // Define after any fields with in-class initializers have been parsed. 6838 DelayedDllExportMemberFunctions.push_back(M); 6839 } 6840 } 6841 6842 // Define defaulted constexpr virtual functions that override a base class 6843 // function right away. 6844 // FIXME: We can defer doing this until the vtable is marked as used. 6845 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6846 DefineDefaultedFunction(*this, M, M->getLocation()); 6847 6848 if (!Incomplete) 6849 CheckCompletedMemberFunction(M); 6850 }; 6851 6852 // Check the destructor before any other member function. We need to 6853 // determine whether it's trivial in order to determine whether the claas 6854 // type is a literal type, which is a prerequisite for determining whether 6855 // other special member functions are valid and whether they're implicitly 6856 // 'constexpr'. 6857 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6858 CompleteMemberFunction(Dtor); 6859 6860 bool HasMethodWithOverrideControl = false, 6861 HasOverridingMethodWithoutOverrideControl = false; 6862 for (auto *D : Record->decls()) { 6863 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 6864 // FIXME: We could do this check for dependent types with non-dependent 6865 // bases. 6866 if (!Record->isDependentType()) { 6867 // See if a method overloads virtual methods in a base 6868 // class without overriding any. 6869 if (!M->isStatic()) 6870 DiagnoseHiddenVirtualMethods(M); 6871 if (M->hasAttr<OverrideAttr>()) 6872 HasMethodWithOverrideControl = true; 6873 else if (M->size_overridden_methods() > 0) 6874 HasOverridingMethodWithoutOverrideControl = true; 6875 } 6876 6877 if (!isa<CXXDestructorDecl>(M)) 6878 CompleteMemberFunction(M); 6879 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 6880 CheckForDefaultedFunction( 6881 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 6882 } 6883 } 6884 6885 if (HasOverridingMethodWithoutOverrideControl) { 6886 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl; 6887 for (auto *M : Record->methods()) 6888 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl); 6889 } 6890 6891 // Check the defaulted secondary comparisons after any other member functions. 6892 for (FunctionDecl *FD : DefaultedSecondaryComparisons) { 6893 CheckExplicitlyDefaultedFunction(S, FD); 6894 6895 // If this is a member function, we deferred checking it until now. 6896 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) 6897 CheckCompletedMemberFunction(MD); 6898 } 6899 6900 // ms_struct is a request to use the same ABI rules as MSVC. Check 6901 // whether this class uses any C++ features that are implemented 6902 // completely differently in MSVC, and if so, emit a diagnostic. 6903 // That diagnostic defaults to an error, but we allow projects to 6904 // map it down to a warning (or ignore it). It's a fairly common 6905 // practice among users of the ms_struct pragma to mass-annotate 6906 // headers, sweeping up a bunch of types that the project doesn't 6907 // really rely on MSVC-compatible layout for. We must therefore 6908 // support "ms_struct except for C++ stuff" as a secondary ABI. 6909 // Don't emit this diagnostic if the feature was enabled as a 6910 // language option (as opposed to via a pragma or attribute), as 6911 // the option -mms-bitfields otherwise essentially makes it impossible 6912 // to build C++ code, unless this diagnostic is turned off. 6913 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields && 6914 (Record->isPolymorphic() || Record->getNumBases())) { 6915 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6916 } 6917 6918 checkClassLevelDLLAttribute(Record); 6919 checkClassLevelCodeSegAttribute(Record); 6920 6921 bool ClangABICompat4 = 6922 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6923 TargetInfo::CallingConvKind CCK = 6924 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6925 bool CanPass = canPassInRegisters(*this, Record, CCK); 6926 6927 // Do not change ArgPassingRestrictions if it has already been set to 6928 // APK_CanNeverPassInRegs. 6929 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6930 Record->setArgPassingRestrictions(CanPass 6931 ? RecordDecl::APK_CanPassInRegs 6932 : RecordDecl::APK_CannotPassInRegs); 6933 6934 // If canPassInRegisters returns true despite the record having a non-trivial 6935 // destructor, the record is destructed in the callee. This happens only when 6936 // the record or one of its subobjects has a field annotated with trivial_abi 6937 // or a field qualified with ObjC __strong/__weak. 6938 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6939 Record->setParamDestroyedInCallee(true); 6940 else if (Record->hasNonTrivialDestructor()) 6941 Record->setParamDestroyedInCallee(CanPass); 6942 6943 if (getLangOpts().ForceEmitVTables) { 6944 // If we want to emit all the vtables, we need to mark it as used. This 6945 // is especially required for cases like vtable assumption loads. 6946 MarkVTableUsed(Record->getInnerLocStart(), Record); 6947 } 6948 6949 if (getLangOpts().CUDA) { 6950 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) 6951 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record); 6952 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>()) 6953 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record); 6954 } 6955 } 6956 6957 /// Look up the special member function that would be called by a special 6958 /// member function for a subobject of class type. 6959 /// 6960 /// \param Class The class type of the subobject. 6961 /// \param CSM The kind of special member function. 6962 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6963 /// \param ConstRHS True if this is a copy operation with a const object 6964 /// on its RHS, that is, if the argument to the outer special member 6965 /// function is 'const' and this is not a field marked 'mutable'. 6966 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6967 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6968 unsigned FieldQuals, bool ConstRHS) { 6969 unsigned LHSQuals = 0; 6970 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6971 LHSQuals = FieldQuals; 6972 6973 unsigned RHSQuals = FieldQuals; 6974 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6975 RHSQuals = 0; 6976 else if (ConstRHS) 6977 RHSQuals |= Qualifiers::Const; 6978 6979 return S.LookupSpecialMember(Class, CSM, 6980 RHSQuals & Qualifiers::Const, 6981 RHSQuals & Qualifiers::Volatile, 6982 false, 6983 LHSQuals & Qualifiers::Const, 6984 LHSQuals & Qualifiers::Volatile); 6985 } 6986 6987 class Sema::InheritedConstructorInfo { 6988 Sema &S; 6989 SourceLocation UseLoc; 6990 6991 /// A mapping from the base classes through which the constructor was 6992 /// inherited to the using shadow declaration in that base class (or a null 6993 /// pointer if the constructor was declared in that base class). 6994 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6995 InheritedFromBases; 6996 6997 public: 6998 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6999 ConstructorUsingShadowDecl *Shadow) 7000 : S(S), UseLoc(UseLoc) { 7001 bool DiagnosedMultipleConstructedBases = false; 7002 CXXRecordDecl *ConstructedBase = nullptr; 7003 UsingDecl *ConstructedBaseUsing = nullptr; 7004 7005 // Find the set of such base class subobjects and check that there's a 7006 // unique constructed subobject. 7007 for (auto *D : Shadow->redecls()) { 7008 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 7009 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 7010 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 7011 7012 InheritedFromBases.insert( 7013 std::make_pair(DNominatedBase->getCanonicalDecl(), 7014 DShadow->getNominatedBaseClassShadowDecl())); 7015 if (DShadow->constructsVirtualBase()) 7016 InheritedFromBases.insert( 7017 std::make_pair(DConstructedBase->getCanonicalDecl(), 7018 DShadow->getConstructedBaseClassShadowDecl())); 7019 else 7020 assert(DNominatedBase == DConstructedBase); 7021 7022 // [class.inhctor.init]p2: 7023 // If the constructor was inherited from multiple base class subobjects 7024 // of type B, the program is ill-formed. 7025 if (!ConstructedBase) { 7026 ConstructedBase = DConstructedBase; 7027 ConstructedBaseUsing = D->getUsingDecl(); 7028 } else if (ConstructedBase != DConstructedBase && 7029 !Shadow->isInvalidDecl()) { 7030 if (!DiagnosedMultipleConstructedBases) { 7031 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 7032 << Shadow->getTargetDecl(); 7033 S.Diag(ConstructedBaseUsing->getLocation(), 7034 diag::note_ambiguous_inherited_constructor_using) 7035 << ConstructedBase; 7036 DiagnosedMultipleConstructedBases = true; 7037 } 7038 S.Diag(D->getUsingDecl()->getLocation(), 7039 diag::note_ambiguous_inherited_constructor_using) 7040 << DConstructedBase; 7041 } 7042 } 7043 7044 if (DiagnosedMultipleConstructedBases) 7045 Shadow->setInvalidDecl(); 7046 } 7047 7048 /// Find the constructor to use for inherited construction of a base class, 7049 /// and whether that base class constructor inherits the constructor from a 7050 /// virtual base class (in which case it won't actually invoke it). 7051 std::pair<CXXConstructorDecl *, bool> 7052 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 7053 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 7054 if (It == InheritedFromBases.end()) 7055 return std::make_pair(nullptr, false); 7056 7057 // This is an intermediary class. 7058 if (It->second) 7059 return std::make_pair( 7060 S.findInheritingConstructor(UseLoc, Ctor, It->second), 7061 It->second->constructsVirtualBase()); 7062 7063 // This is the base class from which the constructor was inherited. 7064 return std::make_pair(Ctor, false); 7065 } 7066 }; 7067 7068 /// Is the special member function which would be selected to perform the 7069 /// specified operation on the specified class type a constexpr constructor? 7070 static bool 7071 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 7072 Sema::CXXSpecialMember CSM, unsigned Quals, 7073 bool ConstRHS, 7074 CXXConstructorDecl *InheritedCtor = nullptr, 7075 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7076 // If we're inheriting a constructor, see if we need to call it for this base 7077 // class. 7078 if (InheritedCtor) { 7079 assert(CSM == Sema::CXXDefaultConstructor); 7080 auto BaseCtor = 7081 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 7082 if (BaseCtor) 7083 return BaseCtor->isConstexpr(); 7084 } 7085 7086 if (CSM == Sema::CXXDefaultConstructor) 7087 return ClassDecl->hasConstexprDefaultConstructor(); 7088 if (CSM == Sema::CXXDestructor) 7089 return ClassDecl->hasConstexprDestructor(); 7090 7091 Sema::SpecialMemberOverloadResult SMOR = 7092 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 7093 if (!SMOR.getMethod()) 7094 // A constructor we wouldn't select can't be "involved in initializing" 7095 // anything. 7096 return true; 7097 return SMOR.getMethod()->isConstexpr(); 7098 } 7099 7100 /// Determine whether the specified special member function would be constexpr 7101 /// if it were implicitly defined. 7102 static bool defaultedSpecialMemberIsConstexpr( 7103 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 7104 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 7105 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7106 if (!S.getLangOpts().CPlusPlus11) 7107 return false; 7108 7109 // C++11 [dcl.constexpr]p4: 7110 // In the definition of a constexpr constructor [...] 7111 bool Ctor = true; 7112 switch (CSM) { 7113 case Sema::CXXDefaultConstructor: 7114 if (Inherited) 7115 break; 7116 // Since default constructor lookup is essentially trivial (and cannot 7117 // involve, for instance, template instantiation), we compute whether a 7118 // defaulted default constructor is constexpr directly within CXXRecordDecl. 7119 // 7120 // This is important for performance; we need to know whether the default 7121 // constructor is constexpr to determine whether the type is a literal type. 7122 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 7123 7124 case Sema::CXXCopyConstructor: 7125 case Sema::CXXMoveConstructor: 7126 // For copy or move constructors, we need to perform overload resolution. 7127 break; 7128 7129 case Sema::CXXCopyAssignment: 7130 case Sema::CXXMoveAssignment: 7131 if (!S.getLangOpts().CPlusPlus14) 7132 return false; 7133 // In C++1y, we need to perform overload resolution. 7134 Ctor = false; 7135 break; 7136 7137 case Sema::CXXDestructor: 7138 return ClassDecl->defaultedDestructorIsConstexpr(); 7139 7140 case Sema::CXXInvalid: 7141 return false; 7142 } 7143 7144 // -- if the class is a non-empty union, or for each non-empty anonymous 7145 // union member of a non-union class, exactly one non-static data member 7146 // shall be initialized; [DR1359] 7147 // 7148 // If we squint, this is guaranteed, since exactly one non-static data member 7149 // will be initialized (if the constructor isn't deleted), we just don't know 7150 // which one. 7151 if (Ctor && ClassDecl->isUnion()) 7152 return CSM == Sema::CXXDefaultConstructor 7153 ? ClassDecl->hasInClassInitializer() || 7154 !ClassDecl->hasVariantMembers() 7155 : true; 7156 7157 // -- the class shall not have any virtual base classes; 7158 if (Ctor && ClassDecl->getNumVBases()) 7159 return false; 7160 7161 // C++1y [class.copy]p26: 7162 // -- [the class] is a literal type, and 7163 if (!Ctor && !ClassDecl->isLiteral()) 7164 return false; 7165 7166 // -- every constructor involved in initializing [...] base class 7167 // sub-objects shall be a constexpr constructor; 7168 // -- the assignment operator selected to copy/move each direct base 7169 // class is a constexpr function, and 7170 for (const auto &B : ClassDecl->bases()) { 7171 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 7172 if (!BaseType) continue; 7173 7174 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7175 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 7176 InheritedCtor, Inherited)) 7177 return false; 7178 } 7179 7180 // -- every constructor involved in initializing non-static data members 7181 // [...] shall be a constexpr constructor; 7182 // -- every non-static data member and base class sub-object shall be 7183 // initialized 7184 // -- for each non-static data member of X that is of class type (or array 7185 // thereof), the assignment operator selected to copy/move that member is 7186 // a constexpr function 7187 for (const auto *F : ClassDecl->fields()) { 7188 if (F->isInvalidDecl()) 7189 continue; 7190 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 7191 continue; 7192 QualType BaseType = S.Context.getBaseElementType(F->getType()); 7193 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 7194 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7195 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 7196 BaseType.getCVRQualifiers(), 7197 ConstArg && !F->isMutable())) 7198 return false; 7199 } else if (CSM == Sema::CXXDefaultConstructor) { 7200 return false; 7201 } 7202 } 7203 7204 // All OK, it's constexpr! 7205 return true; 7206 } 7207 7208 namespace { 7209 /// RAII object to register a defaulted function as having its exception 7210 /// specification computed. 7211 struct ComputingExceptionSpec { 7212 Sema &S; 7213 7214 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 7215 : S(S) { 7216 Sema::CodeSynthesisContext Ctx; 7217 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 7218 Ctx.PointOfInstantiation = Loc; 7219 Ctx.Entity = FD; 7220 S.pushCodeSynthesisContext(Ctx); 7221 } 7222 ~ComputingExceptionSpec() { 7223 S.popCodeSynthesisContext(); 7224 } 7225 }; 7226 } 7227 7228 static Sema::ImplicitExceptionSpecification 7229 ComputeDefaultedSpecialMemberExceptionSpec( 7230 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 7231 Sema::InheritedConstructorInfo *ICI); 7232 7233 static Sema::ImplicitExceptionSpecification 7234 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 7235 FunctionDecl *FD, 7236 Sema::DefaultedComparisonKind DCK); 7237 7238 static Sema::ImplicitExceptionSpecification 7239 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 7240 auto DFK = S.getDefaultedFunctionKind(FD); 7241 if (DFK.isSpecialMember()) 7242 return ComputeDefaultedSpecialMemberExceptionSpec( 7243 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 7244 if (DFK.isComparison()) 7245 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 7246 DFK.asComparison()); 7247 7248 auto *CD = cast<CXXConstructorDecl>(FD); 7249 assert(CD->getInheritedConstructor() && 7250 "only defaulted functions and inherited constructors have implicit " 7251 "exception specs"); 7252 Sema::InheritedConstructorInfo ICI( 7253 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 7254 return ComputeDefaultedSpecialMemberExceptionSpec( 7255 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 7256 } 7257 7258 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 7259 CXXMethodDecl *MD) { 7260 FunctionProtoType::ExtProtoInfo EPI; 7261 7262 // Build an exception specification pointing back at this member. 7263 EPI.ExceptionSpec.Type = EST_Unevaluated; 7264 EPI.ExceptionSpec.SourceDecl = MD; 7265 7266 // Set the calling convention to the default for C++ instance methods. 7267 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 7268 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 7269 /*IsCXXMethod=*/true)); 7270 return EPI; 7271 } 7272 7273 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 7274 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 7275 if (FPT->getExceptionSpecType() != EST_Unevaluated) 7276 return; 7277 7278 // Evaluate the exception specification. 7279 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 7280 auto ESI = IES.getExceptionSpec(); 7281 7282 // Update the type of the special member to use it. 7283 UpdateExceptionSpec(FD, ESI); 7284 } 7285 7286 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 7287 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted"); 7288 7289 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 7290 if (!DefKind) { 7291 assert(FD->getDeclContext()->isDependentContext()); 7292 return; 7293 } 7294 7295 if (DefKind.isSpecialMember() 7296 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 7297 DefKind.asSpecialMember()) 7298 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 7299 FD->setInvalidDecl(); 7300 } 7301 7302 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7303 CXXSpecialMember CSM) { 7304 CXXRecordDecl *RD = MD->getParent(); 7305 7306 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 7307 "not an explicitly-defaulted special member"); 7308 7309 // Defer all checking for special members of a dependent type. 7310 if (RD->isDependentType()) 7311 return false; 7312 7313 // Whether this was the first-declared instance of the constructor. 7314 // This affects whether we implicitly add an exception spec and constexpr. 7315 bool First = MD == MD->getCanonicalDecl(); 7316 7317 bool HadError = false; 7318 7319 // C++11 [dcl.fct.def.default]p1: 7320 // A function that is explicitly defaulted shall 7321 // -- be a special member function [...] (checked elsewhere), 7322 // -- have the same type (except for ref-qualifiers, and except that a 7323 // copy operation can take a non-const reference) as an implicit 7324 // declaration, and 7325 // -- not have default arguments. 7326 // C++2a changes the second bullet to instead delete the function if it's 7327 // defaulted on its first declaration, unless it's "an assignment operator, 7328 // and its return type differs or its parameter type is not a reference". 7329 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First; 7330 bool ShouldDeleteForTypeMismatch = false; 7331 unsigned ExpectedParams = 1; 7332 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 7333 ExpectedParams = 0; 7334 if (MD->getNumParams() != ExpectedParams) { 7335 // This checks for default arguments: a copy or move constructor with a 7336 // default argument is classified as a default constructor, and assignment 7337 // operations and destructors can't have default arguments. 7338 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 7339 << CSM << MD->getSourceRange(); 7340 HadError = true; 7341 } else if (MD->isVariadic()) { 7342 if (DeleteOnTypeMismatch) 7343 ShouldDeleteForTypeMismatch = true; 7344 else { 7345 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 7346 << CSM << MD->getSourceRange(); 7347 HadError = true; 7348 } 7349 } 7350 7351 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 7352 7353 bool CanHaveConstParam = false; 7354 if (CSM == CXXCopyConstructor) 7355 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 7356 else if (CSM == CXXCopyAssignment) 7357 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 7358 7359 QualType ReturnType = Context.VoidTy; 7360 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 7361 // Check for return type matching. 7362 ReturnType = Type->getReturnType(); 7363 7364 QualType DeclType = Context.getTypeDeclType(RD); 7365 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 7366 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 7367 7368 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 7369 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 7370 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 7371 HadError = true; 7372 } 7373 7374 // A defaulted special member cannot have cv-qualifiers. 7375 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 7376 if (DeleteOnTypeMismatch) 7377 ShouldDeleteForTypeMismatch = true; 7378 else { 7379 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 7380 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 7381 HadError = true; 7382 } 7383 } 7384 } 7385 7386 // Check for parameter type matching. 7387 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 7388 bool HasConstParam = false; 7389 if (ExpectedParams && ArgType->isReferenceType()) { 7390 // Argument must be reference to possibly-const T. 7391 QualType ReferentType = ArgType->getPointeeType(); 7392 HasConstParam = ReferentType.isConstQualified(); 7393 7394 if (ReferentType.isVolatileQualified()) { 7395 if (DeleteOnTypeMismatch) 7396 ShouldDeleteForTypeMismatch = true; 7397 else { 7398 Diag(MD->getLocation(), 7399 diag::err_defaulted_special_member_volatile_param) << CSM; 7400 HadError = true; 7401 } 7402 } 7403 7404 if (HasConstParam && !CanHaveConstParam) { 7405 if (DeleteOnTypeMismatch) 7406 ShouldDeleteForTypeMismatch = true; 7407 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7408 Diag(MD->getLocation(), 7409 diag::err_defaulted_special_member_copy_const_param) 7410 << (CSM == CXXCopyAssignment); 7411 // FIXME: Explain why this special member can't be const. 7412 HadError = true; 7413 } else { 7414 Diag(MD->getLocation(), 7415 diag::err_defaulted_special_member_move_const_param) 7416 << (CSM == CXXMoveAssignment); 7417 HadError = true; 7418 } 7419 } 7420 } else if (ExpectedParams) { 7421 // A copy assignment operator can take its argument by value, but a 7422 // defaulted one cannot. 7423 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 7424 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7425 HadError = true; 7426 } 7427 7428 // C++11 [dcl.fct.def.default]p2: 7429 // An explicitly-defaulted function may be declared constexpr only if it 7430 // would have been implicitly declared as constexpr, 7431 // Do not apply this rule to members of class templates, since core issue 1358 7432 // makes such functions always instantiate to constexpr functions. For 7433 // functions which cannot be constexpr (for non-constructors in C++11 and for 7434 // destructors in C++14 and C++17), this is checked elsewhere. 7435 // 7436 // FIXME: This should not apply if the member is deleted. 7437 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7438 HasConstParam); 7439 if ((getLangOpts().CPlusPlus20 || 7440 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7441 : isa<CXXConstructorDecl>(MD))) && 7442 MD->isConstexpr() && !Constexpr && 7443 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7444 Diag(MD->getBeginLoc(), MD->isConsteval() 7445 ? diag::err_incorrect_defaulted_consteval 7446 : diag::err_incorrect_defaulted_constexpr) 7447 << CSM; 7448 // FIXME: Explain why the special member can't be constexpr. 7449 HadError = true; 7450 } 7451 7452 if (First) { 7453 // C++2a [dcl.fct.def.default]p3: 7454 // If a function is explicitly defaulted on its first declaration, it is 7455 // implicitly considered to be constexpr if the implicit declaration 7456 // would be. 7457 MD->setConstexprKind(Constexpr ? (MD->isConsteval() 7458 ? ConstexprSpecKind::Consteval 7459 : ConstexprSpecKind::Constexpr) 7460 : ConstexprSpecKind::Unspecified); 7461 7462 if (!Type->hasExceptionSpec()) { 7463 // C++2a [except.spec]p3: 7464 // If a declaration of a function does not have a noexcept-specifier 7465 // [and] is defaulted on its first declaration, [...] the exception 7466 // specification is as specified below 7467 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7468 EPI.ExceptionSpec.Type = EST_Unevaluated; 7469 EPI.ExceptionSpec.SourceDecl = MD; 7470 MD->setType(Context.getFunctionType(ReturnType, 7471 llvm::makeArrayRef(&ArgType, 7472 ExpectedParams), 7473 EPI)); 7474 } 7475 } 7476 7477 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7478 if (First) { 7479 SetDeclDeleted(MD, MD->getLocation()); 7480 if (!inTemplateInstantiation() && !HadError) { 7481 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7482 if (ShouldDeleteForTypeMismatch) { 7483 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7484 } else { 7485 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7486 } 7487 } 7488 if (ShouldDeleteForTypeMismatch && !HadError) { 7489 Diag(MD->getLocation(), 7490 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7491 } 7492 } else { 7493 // C++11 [dcl.fct.def.default]p4: 7494 // [For a] user-provided explicitly-defaulted function [...] if such a 7495 // function is implicitly defined as deleted, the program is ill-formed. 7496 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7497 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 7498 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7499 HadError = true; 7500 } 7501 } 7502 7503 return HadError; 7504 } 7505 7506 namespace { 7507 /// Helper class for building and checking a defaulted comparison. 7508 /// 7509 /// Defaulted functions are built in two phases: 7510 /// 7511 /// * First, the set of operations that the function will perform are 7512 /// identified, and some of them are checked. If any of the checked 7513 /// operations is invalid in certain ways, the comparison function is 7514 /// defined as deleted and no body is built. 7515 /// * Then, if the function is not defined as deleted, the body is built. 7516 /// 7517 /// This is accomplished by performing two visitation steps over the eventual 7518 /// body of the function. 7519 template<typename Derived, typename ResultList, typename Result, 7520 typename Subobject> 7521 class DefaultedComparisonVisitor { 7522 public: 7523 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7524 7525 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7526 DefaultedComparisonKind DCK) 7527 : S(S), RD(RD), FD(FD), DCK(DCK) { 7528 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7529 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7530 // UnresolvedSet to avoid this copy. 7531 Fns.assign(Info->getUnqualifiedLookups().begin(), 7532 Info->getUnqualifiedLookups().end()); 7533 } 7534 } 7535 7536 ResultList visit() { 7537 // The type of an lvalue naming a parameter of this function. 7538 QualType ParamLvalType = 7539 FD->getParamDecl(0)->getType().getNonReferenceType(); 7540 7541 ResultList Results; 7542 7543 switch (DCK) { 7544 case DefaultedComparisonKind::None: 7545 llvm_unreachable("not a defaulted comparison"); 7546 7547 case DefaultedComparisonKind::Equal: 7548 case DefaultedComparisonKind::ThreeWay: 7549 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7550 return Results; 7551 7552 case DefaultedComparisonKind::NotEqual: 7553 case DefaultedComparisonKind::Relational: 7554 Results.add(getDerived().visitExpandedSubobject( 7555 ParamLvalType, getDerived().getCompleteObject())); 7556 return Results; 7557 } 7558 llvm_unreachable(""); 7559 } 7560 7561 protected: 7562 Derived &getDerived() { return static_cast<Derived&>(*this); } 7563 7564 /// Visit the expanded list of subobjects of the given type, as specified in 7565 /// C++2a [class.compare.default]. 7566 /// 7567 /// \return \c true if the ResultList object said we're done, \c false if not. 7568 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7569 Qualifiers Quals) { 7570 // C++2a [class.compare.default]p4: 7571 // The direct base class subobjects of C 7572 for (CXXBaseSpecifier &Base : Record->bases()) 7573 if (Results.add(getDerived().visitSubobject( 7574 S.Context.getQualifiedType(Base.getType(), Quals), 7575 getDerived().getBase(&Base)))) 7576 return true; 7577 7578 // followed by the non-static data members of C 7579 for (FieldDecl *Field : Record->fields()) { 7580 // Recursively expand anonymous structs. 7581 if (Field->isAnonymousStructOrUnion()) { 7582 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7583 Quals)) 7584 return true; 7585 continue; 7586 } 7587 7588 // Figure out the type of an lvalue denoting this field. 7589 Qualifiers FieldQuals = Quals; 7590 if (Field->isMutable()) 7591 FieldQuals.removeConst(); 7592 QualType FieldType = 7593 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7594 7595 if (Results.add(getDerived().visitSubobject( 7596 FieldType, getDerived().getField(Field)))) 7597 return true; 7598 } 7599 7600 // form a list of subobjects. 7601 return false; 7602 } 7603 7604 Result visitSubobject(QualType Type, Subobject Subobj) { 7605 // In that list, any subobject of array type is recursively expanded 7606 const ArrayType *AT = S.Context.getAsArrayType(Type); 7607 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7608 return getDerived().visitSubobjectArray(CAT->getElementType(), 7609 CAT->getSize(), Subobj); 7610 return getDerived().visitExpandedSubobject(Type, Subobj); 7611 } 7612 7613 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7614 Subobject Subobj) { 7615 return getDerived().visitSubobject(Type, Subobj); 7616 } 7617 7618 protected: 7619 Sema &S; 7620 CXXRecordDecl *RD; 7621 FunctionDecl *FD; 7622 DefaultedComparisonKind DCK; 7623 UnresolvedSet<16> Fns; 7624 }; 7625 7626 /// Information about a defaulted comparison, as determined by 7627 /// DefaultedComparisonAnalyzer. 7628 struct DefaultedComparisonInfo { 7629 bool Deleted = false; 7630 bool Constexpr = true; 7631 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7632 7633 static DefaultedComparisonInfo deleted() { 7634 DefaultedComparisonInfo Deleted; 7635 Deleted.Deleted = true; 7636 return Deleted; 7637 } 7638 7639 bool add(const DefaultedComparisonInfo &R) { 7640 Deleted |= R.Deleted; 7641 Constexpr &= R.Constexpr; 7642 Category = commonComparisonType(Category, R.Category); 7643 return Deleted; 7644 } 7645 }; 7646 7647 /// An element in the expanded list of subobjects of a defaulted comparison, as 7648 /// specified in C++2a [class.compare.default]p4. 7649 struct DefaultedComparisonSubobject { 7650 enum { CompleteObject, Member, Base } Kind; 7651 NamedDecl *Decl; 7652 SourceLocation Loc; 7653 }; 7654 7655 /// A visitor over the notional body of a defaulted comparison that determines 7656 /// whether that body would be deleted or constexpr. 7657 class DefaultedComparisonAnalyzer 7658 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7659 DefaultedComparisonInfo, 7660 DefaultedComparisonInfo, 7661 DefaultedComparisonSubobject> { 7662 public: 7663 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7664 7665 private: 7666 DiagnosticKind Diagnose; 7667 7668 public: 7669 using Base = DefaultedComparisonVisitor; 7670 using Result = DefaultedComparisonInfo; 7671 using Subobject = DefaultedComparisonSubobject; 7672 7673 friend Base; 7674 7675 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7676 DefaultedComparisonKind DCK, 7677 DiagnosticKind Diagnose = NoDiagnostics) 7678 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7679 7680 Result visit() { 7681 if ((DCK == DefaultedComparisonKind::Equal || 7682 DCK == DefaultedComparisonKind::ThreeWay) && 7683 RD->hasVariantMembers()) { 7684 // C++2a [class.compare.default]p2 [P2002R0]: 7685 // A defaulted comparison operator function for class C is defined as 7686 // deleted if [...] C has variant members. 7687 if (Diagnose == ExplainDeleted) { 7688 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7689 << FD << RD->isUnion() << RD; 7690 } 7691 return Result::deleted(); 7692 } 7693 7694 return Base::visit(); 7695 } 7696 7697 private: 7698 Subobject getCompleteObject() { 7699 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()}; 7700 } 7701 7702 Subobject getBase(CXXBaseSpecifier *Base) { 7703 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7704 Base->getBaseTypeLoc()}; 7705 } 7706 7707 Subobject getField(FieldDecl *Field) { 7708 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7709 } 7710 7711 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7712 // C++2a [class.compare.default]p2 [P2002R0]: 7713 // A defaulted <=> or == operator function for class C is defined as 7714 // deleted if any non-static data member of C is of reference type 7715 if (Type->isReferenceType()) { 7716 if (Diagnose == ExplainDeleted) { 7717 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7718 << FD << RD; 7719 } 7720 return Result::deleted(); 7721 } 7722 7723 // [...] Let xi be an lvalue denoting the ith element [...] 7724 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7725 Expr *Args[] = {&Xi, &Xi}; 7726 7727 // All operators start by trying to apply that same operator recursively. 7728 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7729 assert(OO != OO_None && "not an overloaded operator!"); 7730 return visitBinaryOperator(OO, Args, Subobj); 7731 } 7732 7733 Result 7734 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7735 Subobject Subobj, 7736 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7737 // Note that there is no need to consider rewritten candidates here if 7738 // we've already found there is no viable 'operator<=>' candidate (and are 7739 // considering synthesizing a '<=>' from '==' and '<'). 7740 OverloadCandidateSet CandidateSet( 7741 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7742 OverloadCandidateSet::OperatorRewriteInfo( 7743 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7744 7745 /// C++2a [class.compare.default]p1 [P2002R0]: 7746 /// [...] the defaulted function itself is never a candidate for overload 7747 /// resolution [...] 7748 CandidateSet.exclude(FD); 7749 7750 if (Args[0]->getType()->isOverloadableType()) 7751 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7752 else if (OO == OO_EqualEqual || 7753 !Args[0]->getType()->isFunctionPointerType()) { 7754 // FIXME: We determine whether this is a valid expression by checking to 7755 // see if there's a viable builtin operator candidate for it. That isn't 7756 // really what the rules ask us to do, but should give the right results. 7757 // 7758 // Note that the builtin operator for relational comparisons on function 7759 // pointers is the only known case which cannot be used. 7760 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet); 7761 } 7762 7763 Result R; 7764 7765 OverloadCandidateSet::iterator Best; 7766 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7767 case OR_Success: { 7768 // C++2a [class.compare.secondary]p2 [P2002R0]: 7769 // The operator function [...] is defined as deleted if [...] the 7770 // candidate selected by overload resolution is not a rewritten 7771 // candidate. 7772 if ((DCK == DefaultedComparisonKind::NotEqual || 7773 DCK == DefaultedComparisonKind::Relational) && 7774 !Best->RewriteKind) { 7775 if (Diagnose == ExplainDeleted) { 7776 S.Diag(Best->Function->getLocation(), 7777 diag::note_defaulted_comparison_not_rewritten_callee) 7778 << FD; 7779 } 7780 return Result::deleted(); 7781 } 7782 7783 // Throughout C++2a [class.compare]: if overload resolution does not 7784 // result in a usable function, the candidate function is defined as 7785 // deleted. This requires that we selected an accessible function. 7786 // 7787 // Note that this only considers the access of the function when named 7788 // within the type of the subobject, and not the access path for any 7789 // derived-to-base conversion. 7790 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7791 if (ArgClass && Best->FoundDecl.getDecl() && 7792 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7793 QualType ObjectType = Subobj.Kind == Subobject::Member 7794 ? Args[0]->getType() 7795 : S.Context.getRecordType(RD); 7796 if (!S.isMemberAccessibleForDeletion( 7797 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7798 Diagnose == ExplainDeleted 7799 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7800 << FD << Subobj.Kind << Subobj.Decl 7801 : S.PDiag())) 7802 return Result::deleted(); 7803 } 7804 7805 // C++2a [class.compare.default]p3 [P2002R0]: 7806 // A defaulted comparison function is constexpr-compatible if [...] 7807 // no overlod resolution performed [...] results in a non-constexpr 7808 // function. 7809 if (FunctionDecl *BestFD = Best->Function) { 7810 assert(!BestFD->isDeleted() && "wrong overload resolution result"); 7811 // If it's not constexpr, explain why not. 7812 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 7813 if (Subobj.Kind != Subobject::CompleteObject) 7814 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7815 << Subobj.Kind << Subobj.Decl; 7816 S.Diag(BestFD->getLocation(), 7817 diag::note_defaulted_comparison_not_constexpr_here); 7818 // Bail out after explaining; we don't want any more notes. 7819 return Result::deleted(); 7820 } 7821 R.Constexpr &= BestFD->isConstexpr(); 7822 } 7823 7824 if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) { 7825 if (auto *BestFD = Best->Function) { 7826 // If any callee has an undeduced return type, deduce it now. 7827 // FIXME: It's not clear how a failure here should be handled. For 7828 // now, we produce an eager diagnostic, because that is forward 7829 // compatible with most (all?) other reasonable options. 7830 if (BestFD->getReturnType()->isUndeducedType() && 7831 S.DeduceReturnType(BestFD, FD->getLocation(), 7832 /*Diagnose=*/false)) { 7833 // Don't produce a duplicate error when asked to explain why the 7834 // comparison is deleted: we diagnosed that when initially checking 7835 // the defaulted operator. 7836 if (Diagnose == NoDiagnostics) { 7837 S.Diag( 7838 FD->getLocation(), 7839 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) 7840 << Subobj.Kind << Subobj.Decl; 7841 S.Diag( 7842 Subobj.Loc, 7843 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) 7844 << Subobj.Kind << Subobj.Decl; 7845 S.Diag(BestFD->getLocation(), 7846 diag::note_defaulted_comparison_cannot_deduce_callee) 7847 << Subobj.Kind << Subobj.Decl; 7848 } 7849 return Result::deleted(); 7850 } 7851 if (auto *Info = S.Context.CompCategories.lookupInfoForType( 7852 BestFD->getCallResultType())) { 7853 R.Category = Info->Kind; 7854 } else { 7855 if (Diagnose == ExplainDeleted) { 7856 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 7857 << Subobj.Kind << Subobj.Decl 7858 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 7859 S.Diag(BestFD->getLocation(), 7860 diag::note_defaulted_comparison_cannot_deduce_callee) 7861 << Subobj.Kind << Subobj.Decl; 7862 } 7863 return Result::deleted(); 7864 } 7865 } else { 7866 Optional<ComparisonCategoryType> Cat = 7867 getComparisonCategoryForBuiltinCmp(Args[0]->getType()); 7868 assert(Cat && "no category for builtin comparison?"); 7869 R.Category = *Cat; 7870 } 7871 } 7872 7873 // Note that we might be rewriting to a different operator. That call is 7874 // not considered until we come to actually build the comparison function. 7875 break; 7876 } 7877 7878 case OR_Ambiguous: 7879 if (Diagnose == ExplainDeleted) { 7880 unsigned Kind = 0; 7881 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 7882 Kind = OO == OO_EqualEqual ? 1 : 2; 7883 CandidateSet.NoteCandidates( 7884 PartialDiagnosticAt( 7885 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 7886 << FD << Kind << Subobj.Kind << Subobj.Decl), 7887 S, OCD_AmbiguousCandidates, Args); 7888 } 7889 R = Result::deleted(); 7890 break; 7891 7892 case OR_Deleted: 7893 if (Diagnose == ExplainDeleted) { 7894 if ((DCK == DefaultedComparisonKind::NotEqual || 7895 DCK == DefaultedComparisonKind::Relational) && 7896 !Best->RewriteKind) { 7897 S.Diag(Best->Function->getLocation(), 7898 diag::note_defaulted_comparison_not_rewritten_callee) 7899 << FD; 7900 } else { 7901 S.Diag(Subobj.Loc, 7902 diag::note_defaulted_comparison_calls_deleted) 7903 << FD << Subobj.Kind << Subobj.Decl; 7904 S.NoteDeletedFunction(Best->Function); 7905 } 7906 } 7907 R = Result::deleted(); 7908 break; 7909 7910 case OR_No_Viable_Function: 7911 // If there's no usable candidate, we're done unless we can rewrite a 7912 // '<=>' in terms of '==' and '<'. 7913 if (OO == OO_Spaceship && 7914 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 7915 // For any kind of comparison category return type, we need a usable 7916 // '==' and a usable '<'. 7917 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 7918 &CandidateSet))) 7919 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 7920 break; 7921 } 7922 7923 if (Diagnose == ExplainDeleted) { 7924 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 7925 << FD << Subobj.Kind << Subobj.Decl; 7926 7927 // For a three-way comparison, list both the candidates for the 7928 // original operator and the candidates for the synthesized operator. 7929 if (SpaceshipCandidates) { 7930 SpaceshipCandidates->NoteCandidates( 7931 S, Args, 7932 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 7933 Args, FD->getLocation())); 7934 S.Diag(Subobj.Loc, 7935 diag::note_defaulted_comparison_no_viable_function_synthesized) 7936 << (OO == OO_EqualEqual ? 0 : 1); 7937 } 7938 7939 CandidateSet.NoteCandidates( 7940 S, Args, 7941 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 7942 FD->getLocation())); 7943 } 7944 R = Result::deleted(); 7945 break; 7946 } 7947 7948 return R; 7949 } 7950 }; 7951 7952 /// A list of statements. 7953 struct StmtListResult { 7954 bool IsInvalid = false; 7955 llvm::SmallVector<Stmt*, 16> Stmts; 7956 7957 bool add(const StmtResult &S) { 7958 IsInvalid |= S.isInvalid(); 7959 if (IsInvalid) 7960 return true; 7961 Stmts.push_back(S.get()); 7962 return false; 7963 } 7964 }; 7965 7966 /// A visitor over the notional body of a defaulted comparison that synthesizes 7967 /// the actual body. 7968 class DefaultedComparisonSynthesizer 7969 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 7970 StmtListResult, StmtResult, 7971 std::pair<ExprResult, ExprResult>> { 7972 SourceLocation Loc; 7973 unsigned ArrayDepth = 0; 7974 7975 public: 7976 using Base = DefaultedComparisonVisitor; 7977 using ExprPair = std::pair<ExprResult, ExprResult>; 7978 7979 friend Base; 7980 7981 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7982 DefaultedComparisonKind DCK, 7983 SourceLocation BodyLoc) 7984 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 7985 7986 /// Build a suitable function body for this defaulted comparison operator. 7987 StmtResult build() { 7988 Sema::CompoundScopeRAII CompoundScope(S); 7989 7990 StmtListResult Stmts = visit(); 7991 if (Stmts.IsInvalid) 7992 return StmtError(); 7993 7994 ExprResult RetVal; 7995 switch (DCK) { 7996 case DefaultedComparisonKind::None: 7997 llvm_unreachable("not a defaulted comparison"); 7998 7999 case DefaultedComparisonKind::Equal: { 8000 // C++2a [class.eq]p3: 8001 // [...] compar[e] the corresponding elements [...] until the first 8002 // index i where xi == yi yields [...] false. If no such index exists, 8003 // V is true. Otherwise, V is false. 8004 // 8005 // Join the comparisons with '&&'s and return the result. Use a right 8006 // fold (traversing the conditions right-to-left), because that 8007 // short-circuits more naturally. 8008 auto OldStmts = std::move(Stmts.Stmts); 8009 Stmts.Stmts.clear(); 8010 ExprResult CmpSoFar; 8011 // Finish a particular comparison chain. 8012 auto FinishCmp = [&] { 8013 if (Expr *Prior = CmpSoFar.get()) { 8014 // Convert the last expression to 'return ...;' 8015 if (RetVal.isUnset() && Stmts.Stmts.empty()) 8016 RetVal = CmpSoFar; 8017 // Convert any prior comparison to 'if (!(...)) return false;' 8018 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 8019 return true; 8020 CmpSoFar = ExprResult(); 8021 } 8022 return false; 8023 }; 8024 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 8025 Expr *E = dyn_cast<Expr>(EAsStmt); 8026 if (!E) { 8027 // Found an array comparison. 8028 if (FinishCmp() || Stmts.add(EAsStmt)) 8029 return StmtError(); 8030 continue; 8031 } 8032 8033 if (CmpSoFar.isUnset()) { 8034 CmpSoFar = E; 8035 continue; 8036 } 8037 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 8038 if (CmpSoFar.isInvalid()) 8039 return StmtError(); 8040 } 8041 if (FinishCmp()) 8042 return StmtError(); 8043 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 8044 // If no such index exists, V is true. 8045 if (RetVal.isUnset()) 8046 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 8047 break; 8048 } 8049 8050 case DefaultedComparisonKind::ThreeWay: { 8051 // Per C++2a [class.spaceship]p3, as a fallback add: 8052 // return static_cast<R>(std::strong_ordering::equal); 8053 QualType StrongOrdering = S.CheckComparisonCategoryType( 8054 ComparisonCategoryType::StrongOrdering, Loc, 8055 Sema::ComparisonCategoryUsage::DefaultedOperator); 8056 if (StrongOrdering.isNull()) 8057 return StmtError(); 8058 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 8059 .getValueInfo(ComparisonCategoryResult::Equal) 8060 ->VD; 8061 RetVal = getDecl(EqualVD); 8062 if (RetVal.isInvalid()) 8063 return StmtError(); 8064 RetVal = buildStaticCastToR(RetVal.get()); 8065 break; 8066 } 8067 8068 case DefaultedComparisonKind::NotEqual: 8069 case DefaultedComparisonKind::Relational: 8070 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 8071 break; 8072 } 8073 8074 // Build the final return statement. 8075 if (RetVal.isInvalid()) 8076 return StmtError(); 8077 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 8078 if (ReturnStmt.isInvalid()) 8079 return StmtError(); 8080 Stmts.Stmts.push_back(ReturnStmt.get()); 8081 8082 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 8083 } 8084 8085 private: 8086 ExprResult getDecl(ValueDecl *VD) { 8087 return S.BuildDeclarationNameExpr( 8088 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 8089 } 8090 8091 ExprResult getParam(unsigned I) { 8092 ParmVarDecl *PD = FD->getParamDecl(I); 8093 return getDecl(PD); 8094 } 8095 8096 ExprPair getCompleteObject() { 8097 unsigned Param = 0; 8098 ExprResult LHS; 8099 if (isa<CXXMethodDecl>(FD)) { 8100 // LHS is '*this'. 8101 LHS = S.ActOnCXXThis(Loc); 8102 if (!LHS.isInvalid()) 8103 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 8104 } else { 8105 LHS = getParam(Param++); 8106 } 8107 ExprResult RHS = getParam(Param++); 8108 assert(Param == FD->getNumParams()); 8109 return {LHS, RHS}; 8110 } 8111 8112 ExprPair getBase(CXXBaseSpecifier *Base) { 8113 ExprPair Obj = getCompleteObject(); 8114 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8115 return {ExprError(), ExprError()}; 8116 CXXCastPath Path = {Base}; 8117 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 8118 CK_DerivedToBase, VK_LValue, &Path), 8119 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 8120 CK_DerivedToBase, VK_LValue, &Path)}; 8121 } 8122 8123 ExprPair getField(FieldDecl *Field) { 8124 ExprPair Obj = getCompleteObject(); 8125 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8126 return {ExprError(), ExprError()}; 8127 8128 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 8129 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 8130 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 8131 CXXScopeSpec(), Field, Found, NameInfo), 8132 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 8133 CXXScopeSpec(), Field, Found, NameInfo)}; 8134 } 8135 8136 // FIXME: When expanding a subobject, register a note in the code synthesis 8137 // stack to say which subobject we're comparing. 8138 8139 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 8140 if (Cond.isInvalid()) 8141 return StmtError(); 8142 8143 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 8144 if (NotCond.isInvalid()) 8145 return StmtError(); 8146 8147 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 8148 assert(!False.isInvalid() && "should never fail"); 8149 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 8150 if (ReturnFalse.isInvalid()) 8151 return StmtError(); 8152 8153 return S.ActOnIfStmt(Loc, false, Loc, nullptr, 8154 S.ActOnCondition(nullptr, Loc, NotCond.get(), 8155 Sema::ConditionKind::Boolean), 8156 Loc, ReturnFalse.get(), SourceLocation(), nullptr); 8157 } 8158 8159 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 8160 ExprPair Subobj) { 8161 QualType SizeType = S.Context.getSizeType(); 8162 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 8163 8164 // Build 'size_t i$n = 0'. 8165 IdentifierInfo *IterationVarName = nullptr; 8166 { 8167 SmallString<8> Str; 8168 llvm::raw_svector_ostream OS(Str); 8169 OS << "i" << ArrayDepth; 8170 IterationVarName = &S.Context.Idents.get(OS.str()); 8171 } 8172 VarDecl *IterationVar = VarDecl::Create( 8173 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 8174 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 8175 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8176 IterationVar->setInit( 8177 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8178 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 8179 8180 auto IterRef = [&] { 8181 ExprResult Ref = S.BuildDeclarationNameExpr( 8182 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 8183 IterationVar); 8184 assert(!Ref.isInvalid() && "can't reference our own variable?"); 8185 return Ref.get(); 8186 }; 8187 8188 // Build 'i$n != Size'. 8189 ExprResult Cond = S.CreateBuiltinBinOp( 8190 Loc, BO_NE, IterRef(), 8191 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 8192 assert(!Cond.isInvalid() && "should never fail"); 8193 8194 // Build '++i$n'. 8195 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 8196 assert(!Inc.isInvalid() && "should never fail"); 8197 8198 // Build 'a[i$n]' and 'b[i$n]'. 8199 auto Index = [&](ExprResult E) { 8200 if (E.isInvalid()) 8201 return ExprError(); 8202 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 8203 }; 8204 Subobj.first = Index(Subobj.first); 8205 Subobj.second = Index(Subobj.second); 8206 8207 // Compare the array elements. 8208 ++ArrayDepth; 8209 StmtResult Substmt = visitSubobject(Type, Subobj); 8210 --ArrayDepth; 8211 8212 if (Substmt.isInvalid()) 8213 return StmtError(); 8214 8215 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 8216 // For outer levels or for an 'operator<=>' we already have a suitable 8217 // statement that returns as necessary. 8218 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 8219 assert(DCK == DefaultedComparisonKind::Equal && 8220 "should have non-expression statement"); 8221 Substmt = buildIfNotCondReturnFalse(ElemCmp); 8222 if (Substmt.isInvalid()) 8223 return StmtError(); 8224 } 8225 8226 // Build 'for (...) ...' 8227 return S.ActOnForStmt(Loc, Loc, Init, 8228 S.ActOnCondition(nullptr, Loc, Cond.get(), 8229 Sema::ConditionKind::Boolean), 8230 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 8231 Substmt.get()); 8232 } 8233 8234 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 8235 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8236 return StmtError(); 8237 8238 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 8239 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); 8240 ExprResult Op; 8241 if (Type->isOverloadableType()) 8242 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(), 8243 Obj.second.get(), /*PerformADL=*/true, 8244 /*AllowRewrittenCandidates=*/true, FD); 8245 else 8246 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get()); 8247 if (Op.isInvalid()) 8248 return StmtError(); 8249 8250 switch (DCK) { 8251 case DefaultedComparisonKind::None: 8252 llvm_unreachable("not a defaulted comparison"); 8253 8254 case DefaultedComparisonKind::Equal: 8255 // Per C++2a [class.eq]p2, each comparison is individually contextually 8256 // converted to bool. 8257 Op = S.PerformContextuallyConvertToBool(Op.get()); 8258 if (Op.isInvalid()) 8259 return StmtError(); 8260 return Op.get(); 8261 8262 case DefaultedComparisonKind::ThreeWay: { 8263 // Per C++2a [class.spaceship]p3, form: 8264 // if (R cmp = static_cast<R>(op); cmp != 0) 8265 // return cmp; 8266 QualType R = FD->getReturnType(); 8267 Op = buildStaticCastToR(Op.get()); 8268 if (Op.isInvalid()) 8269 return StmtError(); 8270 8271 // R cmp = ...; 8272 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 8273 VarDecl *VD = 8274 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 8275 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 8276 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 8277 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 8278 8279 // cmp != 0 8280 ExprResult VDRef = getDecl(VD); 8281 if (VDRef.isInvalid()) 8282 return StmtError(); 8283 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 8284 Expr *Zero = 8285 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 8286 ExprResult Comp; 8287 if (VDRef.get()->getType()->isOverloadableType()) 8288 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true, 8289 true, FD); 8290 else 8291 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero); 8292 if (Comp.isInvalid()) 8293 return StmtError(); 8294 Sema::ConditionResult Cond = S.ActOnCondition( 8295 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 8296 if (Cond.isInvalid()) 8297 return StmtError(); 8298 8299 // return cmp; 8300 VDRef = getDecl(VD); 8301 if (VDRef.isInvalid()) 8302 return StmtError(); 8303 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 8304 if (ReturnStmt.isInvalid()) 8305 return StmtError(); 8306 8307 // if (...) 8308 return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc, 8309 ReturnStmt.get(), 8310 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr); 8311 } 8312 8313 case DefaultedComparisonKind::NotEqual: 8314 case DefaultedComparisonKind::Relational: 8315 // C++2a [class.compare.secondary]p2: 8316 // Otherwise, the operator function yields x @ y. 8317 return Op.get(); 8318 } 8319 llvm_unreachable(""); 8320 } 8321 8322 /// Build "static_cast<R>(E)". 8323 ExprResult buildStaticCastToR(Expr *E) { 8324 QualType R = FD->getReturnType(); 8325 assert(!R->isUndeducedType() && "type should have been deduced already"); 8326 8327 // Don't bother forming a no-op cast in the common case. 8328 if (E->isRValue() && S.Context.hasSameType(E->getType(), R)) 8329 return E; 8330 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 8331 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 8332 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 8333 } 8334 }; 8335 } 8336 8337 /// Perform the unqualified lookups that might be needed to form a defaulted 8338 /// comparison function for the given operator. 8339 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 8340 UnresolvedSetImpl &Operators, 8341 OverloadedOperatorKind Op) { 8342 auto Lookup = [&](OverloadedOperatorKind OO) { 8343 Self.LookupOverloadedOperatorName(OO, S, Operators); 8344 }; 8345 8346 // Every defaulted operator looks up itself. 8347 Lookup(Op); 8348 // ... and the rewritten form of itself, if any. 8349 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 8350 Lookup(ExtraOp); 8351 8352 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 8353 // synthesize a three-way comparison from '<' and '=='. In a dependent 8354 // context, we also need to look up '==' in case we implicitly declare a 8355 // defaulted 'operator=='. 8356 if (Op == OO_Spaceship) { 8357 Lookup(OO_ExclaimEqual); 8358 Lookup(OO_Less); 8359 Lookup(OO_EqualEqual); 8360 } 8361 } 8362 8363 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 8364 DefaultedComparisonKind DCK) { 8365 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison"); 8366 8367 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 8368 assert(RD && "defaulted comparison is not defaulted in a class"); 8369 8370 // Perform any unqualified lookups we're going to need to default this 8371 // function. 8372 if (S) { 8373 UnresolvedSet<32> Operators; 8374 lookupOperatorsForDefaultedComparison(*this, S, Operators, 8375 FD->getOverloadedOperator()); 8376 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 8377 Context, Operators.pairs())); 8378 } 8379 8380 // C++2a [class.compare.default]p1: 8381 // A defaulted comparison operator function for some class C shall be a 8382 // non-template function declared in the member-specification of C that is 8383 // -- a non-static const member of C having one parameter of type 8384 // const C&, or 8385 // -- a friend of C having two parameters of type const C& or two 8386 // parameters of type C. 8387 QualType ExpectedParmType1 = Context.getRecordType(RD); 8388 QualType ExpectedParmType2 = 8389 Context.getLValueReferenceType(ExpectedParmType1.withConst()); 8390 if (isa<CXXMethodDecl>(FD)) 8391 ExpectedParmType1 = ExpectedParmType2; 8392 for (const ParmVarDecl *Param : FD->parameters()) { 8393 if (!Param->getType()->isDependentType() && 8394 !Context.hasSameType(Param->getType(), ExpectedParmType1) && 8395 !Context.hasSameType(Param->getType(), ExpectedParmType2)) { 8396 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8397 // corresponding defaulted 'operator<=>' already. 8398 if (!FD->isImplicit()) { 8399 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 8400 << (int)DCK << Param->getType() << ExpectedParmType1 8401 << !isa<CXXMethodDecl>(FD) 8402 << ExpectedParmType2 << Param->getSourceRange(); 8403 } 8404 return true; 8405 } 8406 } 8407 if (FD->getNumParams() == 2 && 8408 !Context.hasSameType(FD->getParamDecl(0)->getType(), 8409 FD->getParamDecl(1)->getType())) { 8410 if (!FD->isImplicit()) { 8411 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 8412 << (int)DCK 8413 << FD->getParamDecl(0)->getType() 8414 << FD->getParamDecl(0)->getSourceRange() 8415 << FD->getParamDecl(1)->getType() 8416 << FD->getParamDecl(1)->getSourceRange(); 8417 } 8418 return true; 8419 } 8420 8421 // ... non-static const member ... 8422 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 8423 assert(!MD->isStatic() && "comparison function cannot be a static member"); 8424 if (!MD->isConst()) { 8425 SourceLocation InsertLoc; 8426 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 8427 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 8428 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8429 // corresponding defaulted 'operator<=>' already. 8430 if (!MD->isImplicit()) { 8431 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 8432 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 8433 } 8434 8435 // Add the 'const' to the type to recover. 8436 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 8437 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8438 EPI.TypeQuals.addConst(); 8439 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8440 FPT->getParamTypes(), EPI)); 8441 } 8442 } else { 8443 // A non-member function declared in a class must be a friend. 8444 assert(FD->getFriendObjectKind() && "expected a friend declaration"); 8445 } 8446 8447 // C++2a [class.eq]p1, [class.rel]p1: 8448 // A [defaulted comparison other than <=>] shall have a declared return 8449 // type bool. 8450 if (DCK != DefaultedComparisonKind::ThreeWay && 8451 !FD->getDeclaredReturnType()->isDependentType() && 8452 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8453 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8454 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8455 << FD->getReturnTypeSourceRange(); 8456 return true; 8457 } 8458 // C++2a [class.spaceship]p2 [P2002R0]: 8459 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8460 // R shall not contain a placeholder type. 8461 if (DCK == DefaultedComparisonKind::ThreeWay && 8462 FD->getDeclaredReturnType()->getContainedDeducedType() && 8463 !Context.hasSameType(FD->getDeclaredReturnType(), 8464 Context.getAutoDeductType())) { 8465 Diag(FD->getLocation(), 8466 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8467 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8468 << FD->getReturnTypeSourceRange(); 8469 return true; 8470 } 8471 8472 // For a defaulted function in a dependent class, defer all remaining checks 8473 // until instantiation. 8474 if (RD->isDependentType()) 8475 return false; 8476 8477 // Determine whether the function should be defined as deleted. 8478 DefaultedComparisonInfo Info = 8479 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8480 8481 bool First = FD == FD->getCanonicalDecl(); 8482 8483 // If we want to delete the function, then do so; there's nothing else to 8484 // check in that case. 8485 if (Info.Deleted) { 8486 if (!First) { 8487 // C++11 [dcl.fct.def.default]p4: 8488 // [For a] user-provided explicitly-defaulted function [...] if such a 8489 // function is implicitly defined as deleted, the program is ill-formed. 8490 // 8491 // This is really just a consequence of the general rule that you can 8492 // only delete a function on its first declaration. 8493 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8494 << FD->isImplicit() << (int)DCK; 8495 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8496 DefaultedComparisonAnalyzer::ExplainDeleted) 8497 .visit(); 8498 return true; 8499 } 8500 8501 SetDeclDeleted(FD, FD->getLocation()); 8502 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8503 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8504 << (int)DCK; 8505 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8506 DefaultedComparisonAnalyzer::ExplainDeleted) 8507 .visit(); 8508 } 8509 return false; 8510 } 8511 8512 // C++2a [class.spaceship]p2: 8513 // The return type is deduced as the common comparison type of R0, R1, ... 8514 if (DCK == DefaultedComparisonKind::ThreeWay && 8515 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8516 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8517 if (RetLoc.isInvalid()) 8518 RetLoc = FD->getBeginLoc(); 8519 // FIXME: Should we really care whether we have the complete type and the 8520 // 'enumerator' constants here? A forward declaration seems sufficient. 8521 QualType Cat = CheckComparisonCategoryType( 8522 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8523 if (Cat.isNull()) 8524 return true; 8525 Context.adjustDeducedFunctionResultType( 8526 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8527 } 8528 8529 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8530 // An explicitly-defaulted function that is not defined as deleted may be 8531 // declared constexpr or consteval only if it is constexpr-compatible. 8532 // C++2a [class.compare.default]p3 [P2002R0]: 8533 // A defaulted comparison function is constexpr-compatible if it satisfies 8534 // the requirements for a constexpr function [...] 8535 // The only relevant requirements are that the parameter and return types are 8536 // literal types. The remaining conditions are checked by the analyzer. 8537 if (FD->isConstexpr()) { 8538 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8539 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8540 !Info.Constexpr) { 8541 Diag(FD->getBeginLoc(), 8542 diag::err_incorrect_defaulted_comparison_constexpr) 8543 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8544 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8545 DefaultedComparisonAnalyzer::ExplainConstexpr) 8546 .visit(); 8547 } 8548 } 8549 8550 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8551 // If a constexpr-compatible function is explicitly defaulted on its first 8552 // declaration, it is implicitly considered to be constexpr. 8553 // FIXME: Only applying this to the first declaration seems problematic, as 8554 // simple reorderings can affect the meaning of the program. 8555 if (First && !FD->isConstexpr() && Info.Constexpr) 8556 FD->setConstexprKind(ConstexprSpecKind::Constexpr); 8557 8558 // C++2a [except.spec]p3: 8559 // If a declaration of a function does not have a noexcept-specifier 8560 // [and] is defaulted on its first declaration, [...] the exception 8561 // specification is as specified below 8562 if (FD->getExceptionSpecType() == EST_None) { 8563 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8564 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8565 EPI.ExceptionSpec.Type = EST_Unevaluated; 8566 EPI.ExceptionSpec.SourceDecl = FD; 8567 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8568 FPT->getParamTypes(), EPI)); 8569 } 8570 8571 return false; 8572 } 8573 8574 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8575 FunctionDecl *Spaceship) { 8576 Sema::CodeSynthesisContext Ctx; 8577 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8578 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8579 Ctx.Entity = Spaceship; 8580 pushCodeSynthesisContext(Ctx); 8581 8582 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8583 EqualEqual->setImplicit(); 8584 8585 popCodeSynthesisContext(); 8586 } 8587 8588 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8589 DefaultedComparisonKind DCK) { 8590 assert(FD->isDefaulted() && !FD->isDeleted() && 8591 !FD->doesThisDeclarationHaveABody()); 8592 if (FD->willHaveBody() || FD->isInvalidDecl()) 8593 return; 8594 8595 SynthesizedFunctionScope Scope(*this, FD); 8596 8597 // Add a context note for diagnostics produced after this point. 8598 Scope.addContextNote(UseLoc); 8599 8600 { 8601 // Build and set up the function body. 8602 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8603 SourceLocation BodyLoc = 8604 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8605 StmtResult Body = 8606 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8607 if (Body.isInvalid()) { 8608 FD->setInvalidDecl(); 8609 return; 8610 } 8611 FD->setBody(Body.get()); 8612 FD->markUsed(Context); 8613 } 8614 8615 // The exception specification is needed because we are defining the 8616 // function. Note that this will reuse the body we just built. 8617 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8618 8619 if (ASTMutationListener *L = getASTMutationListener()) 8620 L->CompletedImplicitDefinition(FD); 8621 } 8622 8623 static Sema::ImplicitExceptionSpecification 8624 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8625 FunctionDecl *FD, 8626 Sema::DefaultedComparisonKind DCK) { 8627 ComputingExceptionSpec CES(S, FD, Loc); 8628 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8629 8630 if (FD->isInvalidDecl()) 8631 return ExceptSpec; 8632 8633 // The common case is that we just defined the comparison function. In that 8634 // case, just look at whether the body can throw. 8635 if (FD->hasBody()) { 8636 ExceptSpec.CalledStmt(FD->getBody()); 8637 } else { 8638 // Otherwise, build a body so we can check it. This should ideally only 8639 // happen when we're not actually marking the function referenced. (This is 8640 // only really important for efficiency: we don't want to build and throw 8641 // away bodies for comparison functions more than we strictly need to.) 8642 8643 // Pretend to synthesize the function body in an unevaluated context. 8644 // Note that we can't actually just go ahead and define the function here: 8645 // we are not permitted to mark its callees as referenced. 8646 Sema::SynthesizedFunctionScope Scope(S, FD); 8647 EnterExpressionEvaluationContext Context( 8648 S, Sema::ExpressionEvaluationContext::Unevaluated); 8649 8650 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8651 SourceLocation BodyLoc = 8652 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8653 StmtResult Body = 8654 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8655 if (!Body.isInvalid()) 8656 ExceptSpec.CalledStmt(Body.get()); 8657 8658 // FIXME: Can we hold onto this body and just transform it to potentially 8659 // evaluated when we're asked to define the function rather than rebuilding 8660 // it? Either that, or we should only build the bits of the body that we 8661 // need (the expressions, not the statements). 8662 } 8663 8664 return ExceptSpec; 8665 } 8666 8667 void Sema::CheckDelayedMemberExceptionSpecs() { 8668 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8669 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8670 8671 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8672 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8673 8674 // Perform any deferred checking of exception specifications for virtual 8675 // destructors. 8676 for (auto &Check : Overriding) 8677 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8678 8679 // Perform any deferred checking of exception specifications for befriended 8680 // special members. 8681 for (auto &Check : Equivalent) 8682 CheckEquivalentExceptionSpec(Check.second, Check.first); 8683 } 8684 8685 namespace { 8686 /// CRTP base class for visiting operations performed by a special member 8687 /// function (or inherited constructor). 8688 template<typename Derived> 8689 struct SpecialMemberVisitor { 8690 Sema &S; 8691 CXXMethodDecl *MD; 8692 Sema::CXXSpecialMember CSM; 8693 Sema::InheritedConstructorInfo *ICI; 8694 8695 // Properties of the special member, computed for convenience. 8696 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8697 8698 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8699 Sema::InheritedConstructorInfo *ICI) 8700 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8701 switch (CSM) { 8702 case Sema::CXXDefaultConstructor: 8703 case Sema::CXXCopyConstructor: 8704 case Sema::CXXMoveConstructor: 8705 IsConstructor = true; 8706 break; 8707 case Sema::CXXCopyAssignment: 8708 case Sema::CXXMoveAssignment: 8709 IsAssignment = true; 8710 break; 8711 case Sema::CXXDestructor: 8712 break; 8713 case Sema::CXXInvalid: 8714 llvm_unreachable("invalid special member kind"); 8715 } 8716 8717 if (MD->getNumParams()) { 8718 if (const ReferenceType *RT = 8719 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8720 ConstArg = RT->getPointeeType().isConstQualified(); 8721 } 8722 } 8723 8724 Derived &getDerived() { return static_cast<Derived&>(*this); } 8725 8726 /// Is this a "move" special member? 8727 bool isMove() const { 8728 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8729 } 8730 8731 /// Look up the corresponding special member in the given class. 8732 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8733 unsigned Quals, bool IsMutable) { 8734 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8735 ConstArg && !IsMutable); 8736 } 8737 8738 /// Look up the constructor for the specified base class to see if it's 8739 /// overridden due to this being an inherited constructor. 8740 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8741 if (!ICI) 8742 return {}; 8743 assert(CSM == Sema::CXXDefaultConstructor); 8744 auto *BaseCtor = 8745 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8746 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8747 return MD; 8748 return {}; 8749 } 8750 8751 /// A base or member subobject. 8752 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8753 8754 /// Get the location to use for a subobject in diagnostics. 8755 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8756 // FIXME: For an indirect virtual base, the direct base leading to 8757 // the indirect virtual base would be a more useful choice. 8758 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8759 return B->getBaseTypeLoc(); 8760 else 8761 return Subobj.get<FieldDecl*>()->getLocation(); 8762 } 8763 8764 enum BasesToVisit { 8765 /// Visit all non-virtual (direct) bases. 8766 VisitNonVirtualBases, 8767 /// Visit all direct bases, virtual or not. 8768 VisitDirectBases, 8769 /// Visit all non-virtual bases, and all virtual bases if the class 8770 /// is not abstract. 8771 VisitPotentiallyConstructedBases, 8772 /// Visit all direct or virtual bases. 8773 VisitAllBases 8774 }; 8775 8776 // Visit the bases and members of the class. 8777 bool visit(BasesToVisit Bases) { 8778 CXXRecordDecl *RD = MD->getParent(); 8779 8780 if (Bases == VisitPotentiallyConstructedBases) 8781 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8782 8783 for (auto &B : RD->bases()) 8784 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8785 getDerived().visitBase(&B)) 8786 return true; 8787 8788 if (Bases == VisitAllBases) 8789 for (auto &B : RD->vbases()) 8790 if (getDerived().visitBase(&B)) 8791 return true; 8792 8793 for (auto *F : RD->fields()) 8794 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8795 getDerived().visitField(F)) 8796 return true; 8797 8798 return false; 8799 } 8800 }; 8801 } 8802 8803 namespace { 8804 struct SpecialMemberDeletionInfo 8805 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8806 bool Diagnose; 8807 8808 SourceLocation Loc; 8809 8810 bool AllFieldsAreConst; 8811 8812 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 8813 Sema::CXXSpecialMember CSM, 8814 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 8815 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 8816 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 8817 8818 bool inUnion() const { return MD->getParent()->isUnion(); } 8819 8820 Sema::CXXSpecialMember getEffectiveCSM() { 8821 return ICI ? Sema::CXXInvalid : CSM; 8822 } 8823 8824 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 8825 8826 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 8827 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 8828 8829 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 8830 bool shouldDeleteForField(FieldDecl *FD); 8831 bool shouldDeleteForAllConstMembers(); 8832 8833 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 8834 unsigned Quals); 8835 bool shouldDeleteForSubobjectCall(Subobject Subobj, 8836 Sema::SpecialMemberOverloadResult SMOR, 8837 bool IsDtorCallInCtor); 8838 8839 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 8840 }; 8841 } 8842 8843 /// Is the given special member inaccessible when used on the given 8844 /// sub-object. 8845 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 8846 CXXMethodDecl *target) { 8847 /// If we're operating on a base class, the object type is the 8848 /// type of this special member. 8849 QualType objectTy; 8850 AccessSpecifier access = target->getAccess(); 8851 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 8852 objectTy = S.Context.getTypeDeclType(MD->getParent()); 8853 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 8854 8855 // If we're operating on a field, the object type is the type of the field. 8856 } else { 8857 objectTy = S.Context.getTypeDeclType(target->getParent()); 8858 } 8859 8860 return S.isMemberAccessibleForDeletion( 8861 target->getParent(), DeclAccessPair::make(target, access), objectTy); 8862 } 8863 8864 /// Check whether we should delete a special member due to the implicit 8865 /// definition containing a call to a special member of a subobject. 8866 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 8867 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 8868 bool IsDtorCallInCtor) { 8869 CXXMethodDecl *Decl = SMOR.getMethod(); 8870 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8871 8872 int DiagKind = -1; 8873 8874 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 8875 DiagKind = !Decl ? 0 : 1; 8876 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 8877 DiagKind = 2; 8878 else if (!isAccessible(Subobj, Decl)) 8879 DiagKind = 3; 8880 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 8881 !Decl->isTrivial()) { 8882 // A member of a union must have a trivial corresponding special member. 8883 // As a weird special case, a destructor call from a union's constructor 8884 // must be accessible and non-deleted, but need not be trivial. Such a 8885 // destructor is never actually called, but is semantically checked as 8886 // if it were. 8887 DiagKind = 4; 8888 } 8889 8890 if (DiagKind == -1) 8891 return false; 8892 8893 if (Diagnose) { 8894 if (Field) { 8895 S.Diag(Field->getLocation(), 8896 diag::note_deleted_special_member_class_subobject) 8897 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 8898 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 8899 } else { 8900 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 8901 S.Diag(Base->getBeginLoc(), 8902 diag::note_deleted_special_member_class_subobject) 8903 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8904 << Base->getType() << DiagKind << IsDtorCallInCtor 8905 << /*IsObjCPtr*/false; 8906 } 8907 8908 if (DiagKind == 1) 8909 S.NoteDeletedFunction(Decl); 8910 // FIXME: Explain inaccessibility if DiagKind == 3. 8911 } 8912 8913 return true; 8914 } 8915 8916 /// Check whether we should delete a special member function due to having a 8917 /// direct or virtual base class or non-static data member of class type M. 8918 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 8919 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 8920 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8921 bool IsMutable = Field && Field->isMutable(); 8922 8923 // C++11 [class.ctor]p5: 8924 // -- any direct or virtual base class, or non-static data member with no 8925 // brace-or-equal-initializer, has class type M (or array thereof) and 8926 // either M has no default constructor or overload resolution as applied 8927 // to M's default constructor results in an ambiguity or in a function 8928 // that is deleted or inaccessible 8929 // C++11 [class.copy]p11, C++11 [class.copy]p23: 8930 // -- a direct or virtual base class B that cannot be copied/moved because 8931 // overload resolution, as applied to B's corresponding special member, 8932 // results in an ambiguity or a function that is deleted or inaccessible 8933 // from the defaulted special member 8934 // C++11 [class.dtor]p5: 8935 // -- any direct or virtual base class [...] has a type with a destructor 8936 // that is deleted or inaccessible 8937 if (!(CSM == Sema::CXXDefaultConstructor && 8938 Field && Field->hasInClassInitializer()) && 8939 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 8940 false)) 8941 return true; 8942 8943 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 8944 // -- any direct or virtual base class or non-static data member has a 8945 // type with a destructor that is deleted or inaccessible 8946 if (IsConstructor) { 8947 Sema::SpecialMemberOverloadResult SMOR = 8948 S.LookupSpecialMember(Class, Sema::CXXDestructor, 8949 false, false, false, false, false); 8950 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 8951 return true; 8952 } 8953 8954 return false; 8955 } 8956 8957 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 8958 FieldDecl *FD, QualType FieldType) { 8959 // The defaulted special functions are defined as deleted if this is a variant 8960 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 8961 // type under ARC. 8962 if (!FieldType.hasNonTrivialObjCLifetime()) 8963 return false; 8964 8965 // Don't make the defaulted default constructor defined as deleted if the 8966 // member has an in-class initializer. 8967 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 8968 return false; 8969 8970 if (Diagnose) { 8971 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 8972 S.Diag(FD->getLocation(), 8973 diag::note_deleted_special_member_class_subobject) 8974 << getEffectiveCSM() << ParentClass << /*IsField*/true 8975 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 8976 } 8977 8978 return true; 8979 } 8980 8981 /// Check whether we should delete a special member function due to the class 8982 /// having a particular direct or virtual base class. 8983 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 8984 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 8985 // If program is correct, BaseClass cannot be null, but if it is, the error 8986 // must be reported elsewhere. 8987 if (!BaseClass) 8988 return false; 8989 // If we have an inheriting constructor, check whether we're calling an 8990 // inherited constructor instead of a default constructor. 8991 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 8992 if (auto *BaseCtor = SMOR.getMethod()) { 8993 // Note that we do not check access along this path; other than that, 8994 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 8995 // FIXME: Check that the base has a usable destructor! Sink this into 8996 // shouldDeleteForClassSubobject. 8997 if (BaseCtor->isDeleted() && Diagnose) { 8998 S.Diag(Base->getBeginLoc(), 8999 diag::note_deleted_special_member_class_subobject) 9000 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 9001 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 9002 << /*IsObjCPtr*/false; 9003 S.NoteDeletedFunction(BaseCtor); 9004 } 9005 return BaseCtor->isDeleted(); 9006 } 9007 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 9008 } 9009 9010 /// Check whether we should delete a special member function due to the class 9011 /// having a particular non-static data member. 9012 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 9013 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 9014 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 9015 9016 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 9017 return true; 9018 9019 if (CSM == Sema::CXXDefaultConstructor) { 9020 // For a default constructor, all references must be initialized in-class 9021 // and, if a union, it must have a non-const member. 9022 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 9023 if (Diagnose) 9024 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9025 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 9026 return true; 9027 } 9028 // C++11 [class.ctor]p5: any non-variant non-static data member of 9029 // const-qualified type (or array thereof) with no 9030 // brace-or-equal-initializer does not have a user-provided default 9031 // constructor. 9032 if (!inUnion() && FieldType.isConstQualified() && 9033 !FD->hasInClassInitializer() && 9034 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 9035 if (Diagnose) 9036 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9037 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 9038 return true; 9039 } 9040 9041 if (inUnion() && !FieldType.isConstQualified()) 9042 AllFieldsAreConst = false; 9043 } else if (CSM == Sema::CXXCopyConstructor) { 9044 // For a copy constructor, data members must not be of rvalue reference 9045 // type. 9046 if (FieldType->isRValueReferenceType()) { 9047 if (Diagnose) 9048 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 9049 << MD->getParent() << FD << FieldType; 9050 return true; 9051 } 9052 } else if (IsAssignment) { 9053 // For an assignment operator, data members must not be of reference type. 9054 if (FieldType->isReferenceType()) { 9055 if (Diagnose) 9056 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9057 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 9058 return true; 9059 } 9060 if (!FieldRecord && FieldType.isConstQualified()) { 9061 // C++11 [class.copy]p23: 9062 // -- a non-static data member of const non-class type (or array thereof) 9063 if (Diagnose) 9064 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9065 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 9066 return true; 9067 } 9068 } 9069 9070 if (FieldRecord) { 9071 // Some additional restrictions exist on the variant members. 9072 if (!inUnion() && FieldRecord->isUnion() && 9073 FieldRecord->isAnonymousStructOrUnion()) { 9074 bool AllVariantFieldsAreConst = true; 9075 9076 // FIXME: Handle anonymous unions declared within anonymous unions. 9077 for (auto *UI : FieldRecord->fields()) { 9078 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 9079 9080 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 9081 return true; 9082 9083 if (!UnionFieldType.isConstQualified()) 9084 AllVariantFieldsAreConst = false; 9085 9086 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 9087 if (UnionFieldRecord && 9088 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 9089 UnionFieldType.getCVRQualifiers())) 9090 return true; 9091 } 9092 9093 // At least one member in each anonymous union must be non-const 9094 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 9095 !FieldRecord->field_empty()) { 9096 if (Diagnose) 9097 S.Diag(FieldRecord->getLocation(), 9098 diag::note_deleted_default_ctor_all_const) 9099 << !!ICI << MD->getParent() << /*anonymous union*/1; 9100 return true; 9101 } 9102 9103 // Don't check the implicit member of the anonymous union type. 9104 // This is technically non-conformant, but sanity demands it. 9105 return false; 9106 } 9107 9108 if (shouldDeleteForClassSubobject(FieldRecord, FD, 9109 FieldType.getCVRQualifiers())) 9110 return true; 9111 } 9112 9113 return false; 9114 } 9115 9116 /// C++11 [class.ctor] p5: 9117 /// A defaulted default constructor for a class X is defined as deleted if 9118 /// X is a union and all of its variant members are of const-qualified type. 9119 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 9120 // This is a silly definition, because it gives an empty union a deleted 9121 // default constructor. Don't do that. 9122 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 9123 bool AnyFields = false; 9124 for (auto *F : MD->getParent()->fields()) 9125 if ((AnyFields = !F->isUnnamedBitfield())) 9126 break; 9127 if (!AnyFields) 9128 return false; 9129 if (Diagnose) 9130 S.Diag(MD->getParent()->getLocation(), 9131 diag::note_deleted_default_ctor_all_const) 9132 << !!ICI << MD->getParent() << /*not anonymous union*/0; 9133 return true; 9134 } 9135 return false; 9136 } 9137 9138 /// Determine whether a defaulted special member function should be defined as 9139 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 9140 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 9141 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 9142 InheritedConstructorInfo *ICI, 9143 bool Diagnose) { 9144 if (MD->isInvalidDecl()) 9145 return false; 9146 CXXRecordDecl *RD = MD->getParent(); 9147 assert(!RD->isDependentType() && "do deletion after instantiation"); 9148 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 9149 return false; 9150 9151 // C++11 [expr.lambda.prim]p19: 9152 // The closure type associated with a lambda-expression has a 9153 // deleted (8.4.3) default constructor and a deleted copy 9154 // assignment operator. 9155 // C++2a adds back these operators if the lambda has no lambda-capture. 9156 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 9157 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 9158 if (Diagnose) 9159 Diag(RD->getLocation(), diag::note_lambda_decl); 9160 return true; 9161 } 9162 9163 // For an anonymous struct or union, the copy and assignment special members 9164 // will never be used, so skip the check. For an anonymous union declared at 9165 // namespace scope, the constructor and destructor are used. 9166 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 9167 RD->isAnonymousStructOrUnion()) 9168 return false; 9169 9170 // C++11 [class.copy]p7, p18: 9171 // If the class definition declares a move constructor or move assignment 9172 // operator, an implicitly declared copy constructor or copy assignment 9173 // operator is defined as deleted. 9174 if (MD->isImplicit() && 9175 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 9176 CXXMethodDecl *UserDeclaredMove = nullptr; 9177 9178 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 9179 // deletion of the corresponding copy operation, not both copy operations. 9180 // MSVC 2015 has adopted the standards conforming behavior. 9181 bool DeletesOnlyMatchingCopy = 9182 getLangOpts().MSVCCompat && 9183 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 9184 9185 if (RD->hasUserDeclaredMoveConstructor() && 9186 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 9187 if (!Diagnose) return true; 9188 9189 // Find any user-declared move constructor. 9190 for (auto *I : RD->ctors()) { 9191 if (I->isMoveConstructor()) { 9192 UserDeclaredMove = I; 9193 break; 9194 } 9195 } 9196 assert(UserDeclaredMove); 9197 } else if (RD->hasUserDeclaredMoveAssignment() && 9198 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 9199 if (!Diagnose) return true; 9200 9201 // Find any user-declared move assignment operator. 9202 for (auto *I : RD->methods()) { 9203 if (I->isMoveAssignmentOperator()) { 9204 UserDeclaredMove = I; 9205 break; 9206 } 9207 } 9208 assert(UserDeclaredMove); 9209 } 9210 9211 if (UserDeclaredMove) { 9212 Diag(UserDeclaredMove->getLocation(), 9213 diag::note_deleted_copy_user_declared_move) 9214 << (CSM == CXXCopyAssignment) << RD 9215 << UserDeclaredMove->isMoveAssignmentOperator(); 9216 return true; 9217 } 9218 } 9219 9220 // Do access control from the special member function 9221 ContextRAII MethodContext(*this, MD); 9222 9223 // C++11 [class.dtor]p5: 9224 // -- for a virtual destructor, lookup of the non-array deallocation function 9225 // results in an ambiguity or in a function that is deleted or inaccessible 9226 if (CSM == CXXDestructor && MD->isVirtual()) { 9227 FunctionDecl *OperatorDelete = nullptr; 9228 DeclarationName Name = 9229 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 9230 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 9231 OperatorDelete, /*Diagnose*/false)) { 9232 if (Diagnose) 9233 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 9234 return true; 9235 } 9236 } 9237 9238 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 9239 9240 // Per DR1611, do not consider virtual bases of constructors of abstract 9241 // classes, since we are not going to construct them. 9242 // Per DR1658, do not consider virtual bases of destructors of abstract 9243 // classes either. 9244 // Per DR2180, for assignment operators we only assign (and thus only 9245 // consider) direct bases. 9246 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 9247 : SMI.VisitPotentiallyConstructedBases)) 9248 return true; 9249 9250 if (SMI.shouldDeleteForAllConstMembers()) 9251 return true; 9252 9253 if (getLangOpts().CUDA) { 9254 // We should delete the special member in CUDA mode if target inference 9255 // failed. 9256 // For inherited constructors (non-null ICI), CSM may be passed so that MD 9257 // is treated as certain special member, which may not reflect what special 9258 // member MD really is. However inferCUDATargetForImplicitSpecialMember 9259 // expects CSM to match MD, therefore recalculate CSM. 9260 assert(ICI || CSM == getSpecialMember(MD)); 9261 auto RealCSM = CSM; 9262 if (ICI) 9263 RealCSM = getSpecialMember(MD); 9264 9265 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 9266 SMI.ConstArg, Diagnose); 9267 } 9268 9269 return false; 9270 } 9271 9272 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 9273 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 9274 assert(DFK && "not a defaultable function"); 9275 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted"); 9276 9277 if (DFK.isSpecialMember()) { 9278 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 9279 nullptr, /*Diagnose=*/true); 9280 } else { 9281 DefaultedComparisonAnalyzer( 9282 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 9283 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 9284 .visit(); 9285 } 9286 } 9287 9288 /// Perform lookup for a special member of the specified kind, and determine 9289 /// whether it is trivial. If the triviality can be determined without the 9290 /// lookup, skip it. This is intended for use when determining whether a 9291 /// special member of a containing object is trivial, and thus does not ever 9292 /// perform overload resolution for default constructors. 9293 /// 9294 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 9295 /// member that was most likely to be intended to be trivial, if any. 9296 /// 9297 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 9298 /// determine whether the special member is trivial. 9299 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 9300 Sema::CXXSpecialMember CSM, unsigned Quals, 9301 bool ConstRHS, 9302 Sema::TrivialABIHandling TAH, 9303 CXXMethodDecl **Selected) { 9304 if (Selected) 9305 *Selected = nullptr; 9306 9307 switch (CSM) { 9308 case Sema::CXXInvalid: 9309 llvm_unreachable("not a special member"); 9310 9311 case Sema::CXXDefaultConstructor: 9312 // C++11 [class.ctor]p5: 9313 // A default constructor is trivial if: 9314 // - all the [direct subobjects] have trivial default constructors 9315 // 9316 // Note, no overload resolution is performed in this case. 9317 if (RD->hasTrivialDefaultConstructor()) 9318 return true; 9319 9320 if (Selected) { 9321 // If there's a default constructor which could have been trivial, dig it 9322 // out. Otherwise, if there's any user-provided default constructor, point 9323 // to that as an example of why there's not a trivial one. 9324 CXXConstructorDecl *DefCtor = nullptr; 9325 if (RD->needsImplicitDefaultConstructor()) 9326 S.DeclareImplicitDefaultConstructor(RD); 9327 for (auto *CI : RD->ctors()) { 9328 if (!CI->isDefaultConstructor()) 9329 continue; 9330 DefCtor = CI; 9331 if (!DefCtor->isUserProvided()) 9332 break; 9333 } 9334 9335 *Selected = DefCtor; 9336 } 9337 9338 return false; 9339 9340 case Sema::CXXDestructor: 9341 // C++11 [class.dtor]p5: 9342 // A destructor is trivial if: 9343 // - all the direct [subobjects] have trivial destructors 9344 if (RD->hasTrivialDestructor() || 9345 (TAH == Sema::TAH_ConsiderTrivialABI && 9346 RD->hasTrivialDestructorForCall())) 9347 return true; 9348 9349 if (Selected) { 9350 if (RD->needsImplicitDestructor()) 9351 S.DeclareImplicitDestructor(RD); 9352 *Selected = RD->getDestructor(); 9353 } 9354 9355 return false; 9356 9357 case Sema::CXXCopyConstructor: 9358 // C++11 [class.copy]p12: 9359 // A copy constructor is trivial if: 9360 // - the constructor selected to copy each direct [subobject] is trivial 9361 if (RD->hasTrivialCopyConstructor() || 9362 (TAH == Sema::TAH_ConsiderTrivialABI && 9363 RD->hasTrivialCopyConstructorForCall())) { 9364 if (Quals == Qualifiers::Const) 9365 // We must either select the trivial copy constructor or reach an 9366 // ambiguity; no need to actually perform overload resolution. 9367 return true; 9368 } else if (!Selected) { 9369 return false; 9370 } 9371 // In C++98, we are not supposed to perform overload resolution here, but we 9372 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 9373 // cases like B as having a non-trivial copy constructor: 9374 // struct A { template<typename T> A(T&); }; 9375 // struct B { mutable A a; }; 9376 goto NeedOverloadResolution; 9377 9378 case Sema::CXXCopyAssignment: 9379 // C++11 [class.copy]p25: 9380 // A copy assignment operator is trivial if: 9381 // - the assignment operator selected to copy each direct [subobject] is 9382 // trivial 9383 if (RD->hasTrivialCopyAssignment()) { 9384 if (Quals == Qualifiers::Const) 9385 return true; 9386 } else if (!Selected) { 9387 return false; 9388 } 9389 // In C++98, we are not supposed to perform overload resolution here, but we 9390 // treat that as a language defect. 9391 goto NeedOverloadResolution; 9392 9393 case Sema::CXXMoveConstructor: 9394 case Sema::CXXMoveAssignment: 9395 NeedOverloadResolution: 9396 Sema::SpecialMemberOverloadResult SMOR = 9397 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 9398 9399 // The standard doesn't describe how to behave if the lookup is ambiguous. 9400 // We treat it as not making the member non-trivial, just like the standard 9401 // mandates for the default constructor. This should rarely matter, because 9402 // the member will also be deleted. 9403 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9404 return true; 9405 9406 if (!SMOR.getMethod()) { 9407 assert(SMOR.getKind() == 9408 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 9409 return false; 9410 } 9411 9412 // We deliberately don't check if we found a deleted special member. We're 9413 // not supposed to! 9414 if (Selected) 9415 *Selected = SMOR.getMethod(); 9416 9417 if (TAH == Sema::TAH_ConsiderTrivialABI && 9418 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 9419 return SMOR.getMethod()->isTrivialForCall(); 9420 return SMOR.getMethod()->isTrivial(); 9421 } 9422 9423 llvm_unreachable("unknown special method kind"); 9424 } 9425 9426 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 9427 for (auto *CI : RD->ctors()) 9428 if (!CI->isImplicit()) 9429 return CI; 9430 9431 // Look for constructor templates. 9432 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 9433 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 9434 if (CXXConstructorDecl *CD = 9435 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 9436 return CD; 9437 } 9438 9439 return nullptr; 9440 } 9441 9442 /// The kind of subobject we are checking for triviality. The values of this 9443 /// enumeration are used in diagnostics. 9444 enum TrivialSubobjectKind { 9445 /// The subobject is a base class. 9446 TSK_BaseClass, 9447 /// The subobject is a non-static data member. 9448 TSK_Field, 9449 /// The object is actually the complete object. 9450 TSK_CompleteObject 9451 }; 9452 9453 /// Check whether the special member selected for a given type would be trivial. 9454 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9455 QualType SubType, bool ConstRHS, 9456 Sema::CXXSpecialMember CSM, 9457 TrivialSubobjectKind Kind, 9458 Sema::TrivialABIHandling TAH, bool Diagnose) { 9459 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9460 if (!SubRD) 9461 return true; 9462 9463 CXXMethodDecl *Selected; 9464 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9465 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9466 return true; 9467 9468 if (Diagnose) { 9469 if (ConstRHS) 9470 SubType.addConst(); 9471 9472 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9473 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9474 << Kind << SubType.getUnqualifiedType(); 9475 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9476 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9477 } else if (!Selected) 9478 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9479 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9480 else if (Selected->isUserProvided()) { 9481 if (Kind == TSK_CompleteObject) 9482 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9483 << Kind << SubType.getUnqualifiedType() << CSM; 9484 else { 9485 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9486 << Kind << SubType.getUnqualifiedType() << CSM; 9487 S.Diag(Selected->getLocation(), diag::note_declared_at); 9488 } 9489 } else { 9490 if (Kind != TSK_CompleteObject) 9491 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9492 << Kind << SubType.getUnqualifiedType() << CSM; 9493 9494 // Explain why the defaulted or deleted special member isn't trivial. 9495 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9496 Diagnose); 9497 } 9498 } 9499 9500 return false; 9501 } 9502 9503 /// Check whether the members of a class type allow a special member to be 9504 /// trivial. 9505 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9506 Sema::CXXSpecialMember CSM, 9507 bool ConstArg, 9508 Sema::TrivialABIHandling TAH, 9509 bool Diagnose) { 9510 for (const auto *FI : RD->fields()) { 9511 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9512 continue; 9513 9514 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9515 9516 // Pretend anonymous struct or union members are members of this class. 9517 if (FI->isAnonymousStructOrUnion()) { 9518 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9519 CSM, ConstArg, TAH, Diagnose)) 9520 return false; 9521 continue; 9522 } 9523 9524 // C++11 [class.ctor]p5: 9525 // A default constructor is trivial if [...] 9526 // -- no non-static data member of its class has a 9527 // brace-or-equal-initializer 9528 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9529 if (Diagnose) 9530 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init) 9531 << FI; 9532 return false; 9533 } 9534 9535 // Objective C ARC 4.3.5: 9536 // [...] nontrivally ownership-qualified types are [...] not trivially 9537 // default constructible, copy constructible, move constructible, copy 9538 // assignable, move assignable, or destructible [...] 9539 if (FieldType.hasNonTrivialObjCLifetime()) { 9540 if (Diagnose) 9541 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9542 << RD << FieldType.getObjCLifetime(); 9543 return false; 9544 } 9545 9546 bool ConstRHS = ConstArg && !FI->isMutable(); 9547 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9548 CSM, TSK_Field, TAH, Diagnose)) 9549 return false; 9550 } 9551 9552 return true; 9553 } 9554 9555 /// Diagnose why the specified class does not have a trivial special member of 9556 /// the given kind. 9557 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9558 QualType Ty = Context.getRecordType(RD); 9559 9560 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9561 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9562 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9563 /*Diagnose*/true); 9564 } 9565 9566 /// Determine whether a defaulted or deleted special member function is trivial, 9567 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9568 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9569 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9570 TrivialABIHandling TAH, bool Diagnose) { 9571 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 9572 9573 CXXRecordDecl *RD = MD->getParent(); 9574 9575 bool ConstArg = false; 9576 9577 // C++11 [class.copy]p12, p25: [DR1593] 9578 // A [special member] is trivial if [...] its parameter-type-list is 9579 // equivalent to the parameter-type-list of an implicit declaration [...] 9580 switch (CSM) { 9581 case CXXDefaultConstructor: 9582 case CXXDestructor: 9583 // Trivial default constructors and destructors cannot have parameters. 9584 break; 9585 9586 case CXXCopyConstructor: 9587 case CXXCopyAssignment: { 9588 // Trivial copy operations always have const, non-volatile parameter types. 9589 ConstArg = true; 9590 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9591 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9592 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 9593 if (Diagnose) 9594 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9595 << Param0->getSourceRange() << Param0->getType() 9596 << Context.getLValueReferenceType( 9597 Context.getRecordType(RD).withConst()); 9598 return false; 9599 } 9600 break; 9601 } 9602 9603 case CXXMoveConstructor: 9604 case CXXMoveAssignment: { 9605 // Trivial move operations always have non-cv-qualified parameters. 9606 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9607 const RValueReferenceType *RT = 9608 Param0->getType()->getAs<RValueReferenceType>(); 9609 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9610 if (Diagnose) 9611 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9612 << Param0->getSourceRange() << Param0->getType() 9613 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9614 return false; 9615 } 9616 break; 9617 } 9618 9619 case CXXInvalid: 9620 llvm_unreachable("not a special member"); 9621 } 9622 9623 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9624 if (Diagnose) 9625 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9626 diag::note_nontrivial_default_arg) 9627 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9628 return false; 9629 } 9630 if (MD->isVariadic()) { 9631 if (Diagnose) 9632 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9633 return false; 9634 } 9635 9636 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9637 // A copy/move [constructor or assignment operator] is trivial if 9638 // -- the [member] selected to copy/move each direct base class subobject 9639 // is trivial 9640 // 9641 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9642 // A [default constructor or destructor] is trivial if 9643 // -- all the direct base classes have trivial [default constructors or 9644 // destructors] 9645 for (const auto &BI : RD->bases()) 9646 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9647 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9648 return false; 9649 9650 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9651 // A copy/move [constructor or assignment operator] for a class X is 9652 // trivial if 9653 // -- for each non-static data member of X that is of class type (or array 9654 // thereof), the constructor selected to copy/move that member is 9655 // trivial 9656 // 9657 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9658 // A [default constructor or destructor] is trivial if 9659 // -- for all of the non-static data members of its class that are of class 9660 // type (or array thereof), each such class has a trivial [default 9661 // constructor or destructor] 9662 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9663 return false; 9664 9665 // C++11 [class.dtor]p5: 9666 // A destructor is trivial if [...] 9667 // -- the destructor is not virtual 9668 if (CSM == CXXDestructor && MD->isVirtual()) { 9669 if (Diagnose) 9670 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9671 return false; 9672 } 9673 9674 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9675 // A [special member] for class X is trivial if [...] 9676 // -- class X has no virtual functions and no virtual base classes 9677 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9678 if (!Diagnose) 9679 return false; 9680 9681 if (RD->getNumVBases()) { 9682 // Check for virtual bases. We already know that the corresponding 9683 // member in all bases is trivial, so vbases must all be direct. 9684 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9685 assert(BS.isVirtual()); 9686 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9687 return false; 9688 } 9689 9690 // Must have a virtual method. 9691 for (const auto *MI : RD->methods()) { 9692 if (MI->isVirtual()) { 9693 SourceLocation MLoc = MI->getBeginLoc(); 9694 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9695 return false; 9696 } 9697 } 9698 9699 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 9700 } 9701 9702 // Looks like it's trivial! 9703 return true; 9704 } 9705 9706 namespace { 9707 struct FindHiddenVirtualMethod { 9708 Sema *S; 9709 CXXMethodDecl *Method; 9710 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9711 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9712 9713 private: 9714 /// Check whether any most overridden method from MD in Methods 9715 static bool CheckMostOverridenMethods( 9716 const CXXMethodDecl *MD, 9717 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9718 if (MD->size_overridden_methods() == 0) 9719 return Methods.count(MD->getCanonicalDecl()); 9720 for (const CXXMethodDecl *O : MD->overridden_methods()) 9721 if (CheckMostOverridenMethods(O, Methods)) 9722 return true; 9723 return false; 9724 } 9725 9726 public: 9727 /// Member lookup function that determines whether a given C++ 9728 /// method overloads virtual methods in a base class without overriding any, 9729 /// to be used with CXXRecordDecl::lookupInBases(). 9730 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9731 RecordDecl *BaseRecord = 9732 Specifier->getType()->castAs<RecordType>()->getDecl(); 9733 9734 DeclarationName Name = Method->getDeclName(); 9735 assert(Name.getNameKind() == DeclarationName::Identifier); 9736 9737 bool foundSameNameMethod = false; 9738 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9739 for (Path.Decls = BaseRecord->lookup(Name).begin(); 9740 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) { 9741 NamedDecl *D = *Path.Decls; 9742 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9743 MD = MD->getCanonicalDecl(); 9744 foundSameNameMethod = true; 9745 // Interested only in hidden virtual methods. 9746 if (!MD->isVirtual()) 9747 continue; 9748 // If the method we are checking overrides a method from its base 9749 // don't warn about the other overloaded methods. Clang deviates from 9750 // GCC by only diagnosing overloads of inherited virtual functions that 9751 // do not override any other virtual functions in the base. GCC's 9752 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9753 // function from a base class. These cases may be better served by a 9754 // warning (not specific to virtual functions) on call sites when the 9755 // call would select a different function from the base class, were it 9756 // visible. 9757 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9758 if (!S->IsOverload(Method, MD, false)) 9759 return true; 9760 // Collect the overload only if its hidden. 9761 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9762 overloadedMethods.push_back(MD); 9763 } 9764 } 9765 9766 if (foundSameNameMethod) 9767 OverloadedMethods.append(overloadedMethods.begin(), 9768 overloadedMethods.end()); 9769 return foundSameNameMethod; 9770 } 9771 }; 9772 } // end anonymous namespace 9773 9774 /// Add the most overriden methods from MD to Methods 9775 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9776 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9777 if (MD->size_overridden_methods() == 0) 9778 Methods.insert(MD->getCanonicalDecl()); 9779 else 9780 for (const CXXMethodDecl *O : MD->overridden_methods()) 9781 AddMostOverridenMethods(O, Methods); 9782 } 9783 9784 /// Check if a method overloads virtual methods in a base class without 9785 /// overriding any. 9786 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9787 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9788 if (!MD->getDeclName().isIdentifier()) 9789 return; 9790 9791 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9792 /*bool RecordPaths=*/false, 9793 /*bool DetectVirtual=*/false); 9794 FindHiddenVirtualMethod FHVM; 9795 FHVM.Method = MD; 9796 FHVM.S = this; 9797 9798 // Keep the base methods that were overridden or introduced in the subclass 9799 // by 'using' in a set. A base method not in this set is hidden. 9800 CXXRecordDecl *DC = MD->getParent(); 9801 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9802 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9803 NamedDecl *ND = *I; 9804 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9805 ND = shad->getTargetDecl(); 9806 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9807 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9808 } 9809 9810 if (DC->lookupInBases(FHVM, Paths)) 9811 OverloadedMethods = FHVM.OverloadedMethods; 9812 } 9813 9814 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 9815 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9816 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 9817 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 9818 PartialDiagnostic PD = PDiag( 9819 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 9820 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 9821 Diag(overloadedMD->getLocation(), PD); 9822 } 9823 } 9824 9825 /// Diagnose methods which overload virtual methods in a base class 9826 /// without overriding any. 9827 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 9828 if (MD->isInvalidDecl()) 9829 return; 9830 9831 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 9832 return; 9833 9834 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9835 FindHiddenVirtualMethods(MD, OverloadedMethods); 9836 if (!OverloadedMethods.empty()) { 9837 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 9838 << MD << (OverloadedMethods.size() > 1); 9839 9840 NoteHiddenVirtualMethods(MD, OverloadedMethods); 9841 } 9842 } 9843 9844 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 9845 auto PrintDiagAndRemoveAttr = [&](unsigned N) { 9846 // No diagnostics if this is a template instantiation. 9847 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) { 9848 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9849 diag::ext_cannot_use_trivial_abi) << &RD; 9850 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9851 diag::note_cannot_use_trivial_abi_reason) << &RD << N; 9852 } 9853 RD.dropAttr<TrivialABIAttr>(); 9854 }; 9855 9856 // Ill-formed if the copy and move constructors are deleted. 9857 auto HasNonDeletedCopyOrMoveConstructor = [&]() { 9858 // If the type is dependent, then assume it might have 9859 // implicit copy or move ctor because we won't know yet at this point. 9860 if (RD.isDependentType()) 9861 return true; 9862 if (RD.needsImplicitCopyConstructor() && 9863 !RD.defaultedCopyConstructorIsDeleted()) 9864 return true; 9865 if (RD.needsImplicitMoveConstructor() && 9866 !RD.defaultedMoveConstructorIsDeleted()) 9867 return true; 9868 for (const CXXConstructorDecl *CD : RD.ctors()) 9869 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted()) 9870 return true; 9871 return false; 9872 }; 9873 9874 if (!HasNonDeletedCopyOrMoveConstructor()) { 9875 PrintDiagAndRemoveAttr(0); 9876 return; 9877 } 9878 9879 // Ill-formed if the struct has virtual functions. 9880 if (RD.isPolymorphic()) { 9881 PrintDiagAndRemoveAttr(1); 9882 return; 9883 } 9884 9885 for (const auto &B : RD.bases()) { 9886 // Ill-formed if the base class is non-trivial for the purpose of calls or a 9887 // virtual base. 9888 if (!B.getType()->isDependentType() && 9889 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) { 9890 PrintDiagAndRemoveAttr(2); 9891 return; 9892 } 9893 9894 if (B.isVirtual()) { 9895 PrintDiagAndRemoveAttr(3); 9896 return; 9897 } 9898 } 9899 9900 for (const auto *FD : RD.fields()) { 9901 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 9902 // non-trivial for the purpose of calls. 9903 QualType FT = FD->getType(); 9904 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 9905 PrintDiagAndRemoveAttr(4); 9906 return; 9907 } 9908 9909 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 9910 if (!RT->isDependentType() && 9911 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 9912 PrintDiagAndRemoveAttr(5); 9913 return; 9914 } 9915 } 9916 } 9917 9918 void Sema::ActOnFinishCXXMemberSpecification( 9919 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 9920 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 9921 if (!TagDecl) 9922 return; 9923 9924 AdjustDeclIfTemplate(TagDecl); 9925 9926 for (const ParsedAttr &AL : AttrList) { 9927 if (AL.getKind() != ParsedAttr::AT_Visibility) 9928 continue; 9929 AL.setInvalid(); 9930 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 9931 } 9932 9933 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 9934 // strict aliasing violation! 9935 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 9936 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 9937 9938 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 9939 } 9940 9941 /// Find the equality comparison functions that should be implicitly declared 9942 /// in a given class definition, per C++2a [class.compare.default]p3. 9943 static void findImplicitlyDeclaredEqualityComparisons( 9944 ASTContext &Ctx, CXXRecordDecl *RD, 9945 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 9946 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 9947 if (!RD->lookup(EqEq).empty()) 9948 // Member operator== explicitly declared: no implicit operator==s. 9949 return; 9950 9951 // Traverse friends looking for an '==' or a '<=>'. 9952 for (FriendDecl *Friend : RD->friends()) { 9953 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 9954 if (!FD) continue; 9955 9956 if (FD->getOverloadedOperator() == OO_EqualEqual) { 9957 // Friend operator== explicitly declared: no implicit operator==s. 9958 Spaceships.clear(); 9959 return; 9960 } 9961 9962 if (FD->getOverloadedOperator() == OO_Spaceship && 9963 FD->isExplicitlyDefaulted()) 9964 Spaceships.push_back(FD); 9965 } 9966 9967 // Look for members named 'operator<=>'. 9968 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 9969 for (NamedDecl *ND : RD->lookup(Cmp)) { 9970 // Note that we could find a non-function here (either a function template 9971 // or a using-declaration). Neither case results in an implicit 9972 // 'operator=='. 9973 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 9974 if (FD->isExplicitlyDefaulted()) 9975 Spaceships.push_back(FD); 9976 } 9977 } 9978 9979 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 9980 /// special functions, such as the default constructor, copy 9981 /// constructor, or destructor, to the given C++ class (C++ 9982 /// [special]p1). This routine can only be executed just before the 9983 /// definition of the class is complete. 9984 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 9985 // Don't add implicit special members to templated classes. 9986 // FIXME: This means unqualified lookups for 'operator=' within a class 9987 // template don't work properly. 9988 if (!ClassDecl->isDependentType()) { 9989 if (ClassDecl->needsImplicitDefaultConstructor()) { 9990 ++getASTContext().NumImplicitDefaultConstructors; 9991 9992 if (ClassDecl->hasInheritedConstructor()) 9993 DeclareImplicitDefaultConstructor(ClassDecl); 9994 } 9995 9996 if (ClassDecl->needsImplicitCopyConstructor()) { 9997 ++getASTContext().NumImplicitCopyConstructors; 9998 9999 // If the properties or semantics of the copy constructor couldn't be 10000 // determined while the class was being declared, force a declaration 10001 // of it now. 10002 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 10003 ClassDecl->hasInheritedConstructor()) 10004 DeclareImplicitCopyConstructor(ClassDecl); 10005 // For the MS ABI we need to know whether the copy ctor is deleted. A 10006 // prerequisite for deleting the implicit copy ctor is that the class has 10007 // a move ctor or move assignment that is either user-declared or whose 10008 // semantics are inherited from a subobject. FIXME: We should provide a 10009 // more direct way for CodeGen to ask whether the constructor was deleted. 10010 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 10011 (ClassDecl->hasUserDeclaredMoveConstructor() || 10012 ClassDecl->needsOverloadResolutionForMoveConstructor() || 10013 ClassDecl->hasUserDeclaredMoveAssignment() || 10014 ClassDecl->needsOverloadResolutionForMoveAssignment())) 10015 DeclareImplicitCopyConstructor(ClassDecl); 10016 } 10017 10018 if (getLangOpts().CPlusPlus11 && 10019 ClassDecl->needsImplicitMoveConstructor()) { 10020 ++getASTContext().NumImplicitMoveConstructors; 10021 10022 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 10023 ClassDecl->hasInheritedConstructor()) 10024 DeclareImplicitMoveConstructor(ClassDecl); 10025 } 10026 10027 if (ClassDecl->needsImplicitCopyAssignment()) { 10028 ++getASTContext().NumImplicitCopyAssignmentOperators; 10029 10030 // If we have a dynamic class, then the copy assignment operator may be 10031 // virtual, so we have to declare it immediately. This ensures that, e.g., 10032 // it shows up in the right place in the vtable and that we diagnose 10033 // problems with the implicit exception specification. 10034 if (ClassDecl->isDynamicClass() || 10035 ClassDecl->needsOverloadResolutionForCopyAssignment() || 10036 ClassDecl->hasInheritedAssignment()) 10037 DeclareImplicitCopyAssignment(ClassDecl); 10038 } 10039 10040 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 10041 ++getASTContext().NumImplicitMoveAssignmentOperators; 10042 10043 // Likewise for the move assignment operator. 10044 if (ClassDecl->isDynamicClass() || 10045 ClassDecl->needsOverloadResolutionForMoveAssignment() || 10046 ClassDecl->hasInheritedAssignment()) 10047 DeclareImplicitMoveAssignment(ClassDecl); 10048 } 10049 10050 if (ClassDecl->needsImplicitDestructor()) { 10051 ++getASTContext().NumImplicitDestructors; 10052 10053 // If we have a dynamic class, then the destructor may be virtual, so we 10054 // have to declare the destructor immediately. This ensures that, e.g., it 10055 // shows up in the right place in the vtable and that we diagnose problems 10056 // with the implicit exception specification. 10057 if (ClassDecl->isDynamicClass() || 10058 ClassDecl->needsOverloadResolutionForDestructor()) 10059 DeclareImplicitDestructor(ClassDecl); 10060 } 10061 } 10062 10063 // C++2a [class.compare.default]p3: 10064 // If the member-specification does not explicitly declare any member or 10065 // friend named operator==, an == operator function is declared implicitly 10066 // for each defaulted three-way comparison operator function defined in 10067 // the member-specification 10068 // FIXME: Consider doing this lazily. 10069 // We do this during the initial parse for a class template, not during 10070 // instantiation, so that we can handle unqualified lookups for 'operator==' 10071 // when parsing the template. 10072 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) { 10073 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships; 10074 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 10075 DefaultedSpaceships); 10076 for (auto *FD : DefaultedSpaceships) 10077 DeclareImplicitEqualityComparison(ClassDecl, FD); 10078 } 10079 } 10080 10081 unsigned 10082 Sema::ActOnReenterTemplateScope(Decl *D, 10083 llvm::function_ref<Scope *()> EnterScope) { 10084 if (!D) 10085 return 0; 10086 AdjustDeclIfTemplate(D); 10087 10088 // In order to get name lookup right, reenter template scopes in order from 10089 // outermost to innermost. 10090 SmallVector<TemplateParameterList *, 4> ParameterLists; 10091 DeclContext *LookupDC = dyn_cast<DeclContext>(D); 10092 10093 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 10094 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 10095 ParameterLists.push_back(DD->getTemplateParameterList(i)); 10096 10097 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10098 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 10099 ParameterLists.push_back(FTD->getTemplateParameters()); 10100 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 10101 LookupDC = VD->getDeclContext(); 10102 10103 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate()) 10104 ParameterLists.push_back(VTD->getTemplateParameters()); 10105 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) 10106 ParameterLists.push_back(PSD->getTemplateParameters()); 10107 } 10108 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 10109 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 10110 ParameterLists.push_back(TD->getTemplateParameterList(i)); 10111 10112 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 10113 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 10114 ParameterLists.push_back(CTD->getTemplateParameters()); 10115 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 10116 ParameterLists.push_back(PSD->getTemplateParameters()); 10117 } 10118 } 10119 // FIXME: Alias declarations and concepts. 10120 10121 unsigned Count = 0; 10122 Scope *InnermostTemplateScope = nullptr; 10123 for (TemplateParameterList *Params : ParameterLists) { 10124 // Ignore explicit specializations; they don't contribute to the template 10125 // depth. 10126 if (Params->size() == 0) 10127 continue; 10128 10129 InnermostTemplateScope = EnterScope(); 10130 for (NamedDecl *Param : *Params) { 10131 if (Param->getDeclName()) { 10132 InnermostTemplateScope->AddDecl(Param); 10133 IdResolver.AddDecl(Param); 10134 } 10135 } 10136 ++Count; 10137 } 10138 10139 // Associate the new template scopes with the corresponding entities. 10140 if (InnermostTemplateScope) { 10141 assert(LookupDC && "no enclosing DeclContext for template lookup"); 10142 EnterTemplatedContext(InnermostTemplateScope, LookupDC); 10143 } 10144 10145 return Count; 10146 } 10147 10148 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10149 if (!RecordD) return; 10150 AdjustDeclIfTemplate(RecordD); 10151 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 10152 PushDeclContext(S, Record); 10153 } 10154 10155 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10156 if (!RecordD) return; 10157 PopDeclContext(); 10158 } 10159 10160 /// This is used to implement the constant expression evaluation part of the 10161 /// attribute enable_if extension. There is nothing in standard C++ which would 10162 /// require reentering parameters. 10163 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 10164 if (!Param) 10165 return; 10166 10167 S->AddDecl(Param); 10168 if (Param->getDeclName()) 10169 IdResolver.AddDecl(Param); 10170 } 10171 10172 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 10173 /// parsing a top-level (non-nested) C++ class, and we are now 10174 /// parsing those parts of the given Method declaration that could 10175 /// not be parsed earlier (C++ [class.mem]p2), such as default 10176 /// arguments. This action should enter the scope of the given 10177 /// Method declaration as if we had just parsed the qualified method 10178 /// name. However, it should not bring the parameters into scope; 10179 /// that will be performed by ActOnDelayedCXXMethodParameter. 10180 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10181 } 10182 10183 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 10184 /// C++ method declaration. We're (re-)introducing the given 10185 /// function parameter into scope for use in parsing later parts of 10186 /// the method declaration. For example, we could see an 10187 /// ActOnParamDefaultArgument event for this parameter. 10188 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 10189 if (!ParamD) 10190 return; 10191 10192 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 10193 10194 S->AddDecl(Param); 10195 if (Param->getDeclName()) 10196 IdResolver.AddDecl(Param); 10197 } 10198 10199 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 10200 /// processing the delayed method declaration for Method. The method 10201 /// declaration is now considered finished. There may be a separate 10202 /// ActOnStartOfFunctionDef action later (not necessarily 10203 /// immediately!) for this method, if it was also defined inside the 10204 /// class body. 10205 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10206 if (!MethodD) 10207 return; 10208 10209 AdjustDeclIfTemplate(MethodD); 10210 10211 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 10212 10213 // Now that we have our default arguments, check the constructor 10214 // again. It could produce additional diagnostics or affect whether 10215 // the class has implicitly-declared destructors, among other 10216 // things. 10217 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 10218 CheckConstructor(Constructor); 10219 10220 // Check the default arguments, which we may have added. 10221 if (!Method->isInvalidDecl()) 10222 CheckCXXDefaultArguments(Method); 10223 } 10224 10225 // Emit the given diagnostic for each non-address-space qualifier. 10226 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 10227 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 10228 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10229 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 10230 bool DiagOccured = false; 10231 FTI.MethodQualifiers->forEachQualifier( 10232 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 10233 SourceLocation SL) { 10234 // This diagnostic should be emitted on any qualifier except an addr 10235 // space qualifier. However, forEachQualifier currently doesn't visit 10236 // addr space qualifiers, so there's no way to write this condition 10237 // right now; we just diagnose on everything. 10238 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 10239 DiagOccured = true; 10240 }); 10241 if (DiagOccured) 10242 D.setInvalidType(); 10243 } 10244 } 10245 10246 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 10247 /// the well-formedness of the constructor declarator @p D with type @p 10248 /// R. If there are any errors in the declarator, this routine will 10249 /// emit diagnostics and set the invalid bit to true. In any case, the type 10250 /// will be updated to reflect a well-formed type for the constructor and 10251 /// returned. 10252 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 10253 StorageClass &SC) { 10254 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 10255 10256 // C++ [class.ctor]p3: 10257 // A constructor shall not be virtual (10.3) or static (9.4). A 10258 // constructor can be invoked for a const, volatile or const 10259 // volatile object. A constructor shall not be declared const, 10260 // volatile, or const volatile (9.3.2). 10261 if (isVirtual) { 10262 if (!D.isInvalidType()) 10263 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10264 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 10265 << SourceRange(D.getIdentifierLoc()); 10266 D.setInvalidType(); 10267 } 10268 if (SC == SC_Static) { 10269 if (!D.isInvalidType()) 10270 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10271 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10272 << SourceRange(D.getIdentifierLoc()); 10273 D.setInvalidType(); 10274 SC = SC_None; 10275 } 10276 10277 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10278 diagnoseIgnoredQualifiers( 10279 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 10280 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 10281 D.getDeclSpec().getRestrictSpecLoc(), 10282 D.getDeclSpec().getAtomicSpecLoc()); 10283 D.setInvalidType(); 10284 } 10285 10286 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 10287 10288 // C++0x [class.ctor]p4: 10289 // A constructor shall not be declared with a ref-qualifier. 10290 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10291 if (FTI.hasRefQualifier()) { 10292 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 10293 << FTI.RefQualifierIsLValueRef 10294 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10295 D.setInvalidType(); 10296 } 10297 10298 // Rebuild the function type "R" without any type qualifiers (in 10299 // case any of the errors above fired) and with "void" as the 10300 // return type, since constructors don't have return types. 10301 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10302 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 10303 return R; 10304 10305 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10306 EPI.TypeQuals = Qualifiers(); 10307 EPI.RefQualifier = RQ_None; 10308 10309 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 10310 } 10311 10312 /// CheckConstructor - Checks a fully-formed constructor for 10313 /// well-formedness, issuing any diagnostics required. Returns true if 10314 /// the constructor declarator is invalid. 10315 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 10316 CXXRecordDecl *ClassDecl 10317 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 10318 if (!ClassDecl) 10319 return Constructor->setInvalidDecl(); 10320 10321 // C++ [class.copy]p3: 10322 // A declaration of a constructor for a class X is ill-formed if 10323 // its first parameter is of type (optionally cv-qualified) X and 10324 // either there are no other parameters or else all other 10325 // parameters have default arguments. 10326 if (!Constructor->isInvalidDecl() && 10327 Constructor->hasOneParamOrDefaultArgs() && 10328 Constructor->getTemplateSpecializationKind() != 10329 TSK_ImplicitInstantiation) { 10330 QualType ParamType = Constructor->getParamDecl(0)->getType(); 10331 QualType ClassTy = Context.getTagDeclType(ClassDecl); 10332 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 10333 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 10334 const char *ConstRef 10335 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 10336 : " const &"; 10337 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 10338 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 10339 10340 // FIXME: Rather that making the constructor invalid, we should endeavor 10341 // to fix the type. 10342 Constructor->setInvalidDecl(); 10343 } 10344 } 10345 } 10346 10347 /// CheckDestructor - Checks a fully-formed destructor definition for 10348 /// well-formedness, issuing any diagnostics required. Returns true 10349 /// on error. 10350 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 10351 CXXRecordDecl *RD = Destructor->getParent(); 10352 10353 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 10354 SourceLocation Loc; 10355 10356 if (!Destructor->isImplicit()) 10357 Loc = Destructor->getLocation(); 10358 else 10359 Loc = RD->getLocation(); 10360 10361 // If we have a virtual destructor, look up the deallocation function 10362 if (FunctionDecl *OperatorDelete = 10363 FindDeallocationFunctionForDestructor(Loc, RD)) { 10364 Expr *ThisArg = nullptr; 10365 10366 // If the notional 'delete this' expression requires a non-trivial 10367 // conversion from 'this' to the type of a destroying operator delete's 10368 // first parameter, perform that conversion now. 10369 if (OperatorDelete->isDestroyingOperatorDelete()) { 10370 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 10371 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 10372 // C++ [class.dtor]p13: 10373 // ... as if for the expression 'delete this' appearing in a 10374 // non-virtual destructor of the destructor's class. 10375 ContextRAII SwitchContext(*this, Destructor); 10376 ExprResult This = 10377 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 10378 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 10379 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 10380 if (This.isInvalid()) { 10381 // FIXME: Register this as a context note so that it comes out 10382 // in the right order. 10383 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 10384 return true; 10385 } 10386 ThisArg = This.get(); 10387 } 10388 } 10389 10390 DiagnoseUseOfDecl(OperatorDelete, Loc); 10391 MarkFunctionReferenced(Loc, OperatorDelete); 10392 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 10393 } 10394 } 10395 10396 return false; 10397 } 10398 10399 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 10400 /// the well-formednes of the destructor declarator @p D with type @p 10401 /// R. If there are any errors in the declarator, this routine will 10402 /// emit diagnostics and set the declarator to invalid. Even if this happens, 10403 /// will be updated to reflect a well-formed type for the destructor and 10404 /// returned. 10405 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 10406 StorageClass& SC) { 10407 // C++ [class.dtor]p1: 10408 // [...] A typedef-name that names a class is a class-name 10409 // (7.1.3); however, a typedef-name that names a class shall not 10410 // be used as the identifier in the declarator for a destructor 10411 // declaration. 10412 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 10413 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 10414 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10415 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 10416 else if (const TemplateSpecializationType *TST = 10417 DeclaratorType->getAs<TemplateSpecializationType>()) 10418 if (TST->isTypeAlias()) 10419 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10420 << DeclaratorType << 1; 10421 10422 // C++ [class.dtor]p2: 10423 // A destructor is used to destroy objects of its class type. A 10424 // destructor takes no parameters, and no return type can be 10425 // specified for it (not even void). The address of a destructor 10426 // shall not be taken. A destructor shall not be static. A 10427 // destructor can be invoked for a const, volatile or const 10428 // volatile object. A destructor shall not be declared const, 10429 // volatile or const volatile (9.3.2). 10430 if (SC == SC_Static) { 10431 if (!D.isInvalidType()) 10432 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 10433 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10434 << SourceRange(D.getIdentifierLoc()) 10435 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10436 10437 SC = SC_None; 10438 } 10439 if (!D.isInvalidType()) { 10440 // Destructors don't have return types, but the parser will 10441 // happily parse something like: 10442 // 10443 // class X { 10444 // float ~X(); 10445 // }; 10446 // 10447 // The return type will be eliminated later. 10448 if (D.getDeclSpec().hasTypeSpecifier()) 10449 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 10450 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 10451 << SourceRange(D.getIdentifierLoc()); 10452 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10453 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 10454 SourceLocation(), 10455 D.getDeclSpec().getConstSpecLoc(), 10456 D.getDeclSpec().getVolatileSpecLoc(), 10457 D.getDeclSpec().getRestrictSpecLoc(), 10458 D.getDeclSpec().getAtomicSpecLoc()); 10459 D.setInvalidType(); 10460 } 10461 } 10462 10463 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 10464 10465 // C++0x [class.dtor]p2: 10466 // A destructor shall not be declared with a ref-qualifier. 10467 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10468 if (FTI.hasRefQualifier()) { 10469 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 10470 << FTI.RefQualifierIsLValueRef 10471 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10472 D.setInvalidType(); 10473 } 10474 10475 // Make sure we don't have any parameters. 10476 if (FTIHasNonVoidParameters(FTI)) { 10477 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 10478 10479 // Delete the parameters. 10480 FTI.freeParams(); 10481 D.setInvalidType(); 10482 } 10483 10484 // Make sure the destructor isn't variadic. 10485 if (FTI.isVariadic) { 10486 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10487 D.setInvalidType(); 10488 } 10489 10490 // Rebuild the function type "R" without any type qualifiers or 10491 // parameters (in case any of the errors above fired) and with 10492 // "void" as the return type, since destructors don't have return 10493 // types. 10494 if (!D.isInvalidType()) 10495 return R; 10496 10497 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10498 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10499 EPI.Variadic = false; 10500 EPI.TypeQuals = Qualifiers(); 10501 EPI.RefQualifier = RQ_None; 10502 return Context.getFunctionType(Context.VoidTy, None, EPI); 10503 } 10504 10505 static void extendLeft(SourceRange &R, SourceRange Before) { 10506 if (Before.isInvalid()) 10507 return; 10508 R.setBegin(Before.getBegin()); 10509 if (R.getEnd().isInvalid()) 10510 R.setEnd(Before.getEnd()); 10511 } 10512 10513 static void extendRight(SourceRange &R, SourceRange After) { 10514 if (After.isInvalid()) 10515 return; 10516 if (R.getBegin().isInvalid()) 10517 R.setBegin(After.getBegin()); 10518 R.setEnd(After.getEnd()); 10519 } 10520 10521 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10522 /// well-formednes of the conversion function declarator @p D with 10523 /// type @p R. If there are any errors in the declarator, this routine 10524 /// will emit diagnostics and return true. Otherwise, it will return 10525 /// false. Either way, the type @p R will be updated to reflect a 10526 /// well-formed type for the conversion operator. 10527 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10528 StorageClass& SC) { 10529 // C++ [class.conv.fct]p1: 10530 // Neither parameter types nor return type can be specified. The 10531 // type of a conversion function (8.3.5) is "function taking no 10532 // parameter returning conversion-type-id." 10533 if (SC == SC_Static) { 10534 if (!D.isInvalidType()) 10535 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10536 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10537 << D.getName().getSourceRange(); 10538 D.setInvalidType(); 10539 SC = SC_None; 10540 } 10541 10542 TypeSourceInfo *ConvTSI = nullptr; 10543 QualType ConvType = 10544 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10545 10546 const DeclSpec &DS = D.getDeclSpec(); 10547 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10548 // Conversion functions don't have return types, but the parser will 10549 // happily parse something like: 10550 // 10551 // class X { 10552 // float operator bool(); 10553 // }; 10554 // 10555 // The return type will be changed later anyway. 10556 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10557 << SourceRange(DS.getTypeSpecTypeLoc()) 10558 << SourceRange(D.getIdentifierLoc()); 10559 D.setInvalidType(); 10560 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10561 // It's also plausible that the user writes type qualifiers in the wrong 10562 // place, such as: 10563 // struct S { const operator int(); }; 10564 // FIXME: we could provide a fixit to move the qualifiers onto the 10565 // conversion type. 10566 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10567 << SourceRange(D.getIdentifierLoc()) << 0; 10568 D.setInvalidType(); 10569 } 10570 10571 const auto *Proto = R->castAs<FunctionProtoType>(); 10572 10573 // Make sure we don't have any parameters. 10574 if (Proto->getNumParams() > 0) { 10575 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10576 10577 // Delete the parameters. 10578 D.getFunctionTypeInfo().freeParams(); 10579 D.setInvalidType(); 10580 } else if (Proto->isVariadic()) { 10581 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10582 D.setInvalidType(); 10583 } 10584 10585 // Diagnose "&operator bool()" and other such nonsense. This 10586 // is actually a gcc extension which we don't support. 10587 if (Proto->getReturnType() != ConvType) { 10588 bool NeedsTypedef = false; 10589 SourceRange Before, After; 10590 10591 // Walk the chunks and extract information on them for our diagnostic. 10592 bool PastFunctionChunk = false; 10593 for (auto &Chunk : D.type_objects()) { 10594 switch (Chunk.Kind) { 10595 case DeclaratorChunk::Function: 10596 if (!PastFunctionChunk) { 10597 if (Chunk.Fun.HasTrailingReturnType) { 10598 TypeSourceInfo *TRT = nullptr; 10599 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10600 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10601 } 10602 PastFunctionChunk = true; 10603 break; 10604 } 10605 LLVM_FALLTHROUGH; 10606 case DeclaratorChunk::Array: 10607 NeedsTypedef = true; 10608 extendRight(After, Chunk.getSourceRange()); 10609 break; 10610 10611 case DeclaratorChunk::Pointer: 10612 case DeclaratorChunk::BlockPointer: 10613 case DeclaratorChunk::Reference: 10614 case DeclaratorChunk::MemberPointer: 10615 case DeclaratorChunk::Pipe: 10616 extendLeft(Before, Chunk.getSourceRange()); 10617 break; 10618 10619 case DeclaratorChunk::Paren: 10620 extendLeft(Before, Chunk.Loc); 10621 extendRight(After, Chunk.EndLoc); 10622 break; 10623 } 10624 } 10625 10626 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10627 After.isValid() ? After.getBegin() : 10628 D.getIdentifierLoc(); 10629 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10630 DB << Before << After; 10631 10632 if (!NeedsTypedef) { 10633 DB << /*don't need a typedef*/0; 10634 10635 // If we can provide a correct fix-it hint, do so. 10636 if (After.isInvalid() && ConvTSI) { 10637 SourceLocation InsertLoc = 10638 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10639 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10640 << FixItHint::CreateInsertionFromRange( 10641 InsertLoc, CharSourceRange::getTokenRange(Before)) 10642 << FixItHint::CreateRemoval(Before); 10643 } 10644 } else if (!Proto->getReturnType()->isDependentType()) { 10645 DB << /*typedef*/1 << Proto->getReturnType(); 10646 } else if (getLangOpts().CPlusPlus11) { 10647 DB << /*alias template*/2 << Proto->getReturnType(); 10648 } else { 10649 DB << /*might not be fixable*/3; 10650 } 10651 10652 // Recover by incorporating the other type chunks into the result type. 10653 // Note, this does *not* change the name of the function. This is compatible 10654 // with the GCC extension: 10655 // struct S { &operator int(); } s; 10656 // int &r = s.operator int(); // ok in GCC 10657 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10658 ConvType = Proto->getReturnType(); 10659 } 10660 10661 // C++ [class.conv.fct]p4: 10662 // The conversion-type-id shall not represent a function type nor 10663 // an array type. 10664 if (ConvType->isArrayType()) { 10665 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10666 ConvType = Context.getPointerType(ConvType); 10667 D.setInvalidType(); 10668 } else if (ConvType->isFunctionType()) { 10669 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10670 ConvType = Context.getPointerType(ConvType); 10671 D.setInvalidType(); 10672 } 10673 10674 // Rebuild the function type "R" without any parameters (in case any 10675 // of the errors above fired) and with the conversion type as the 10676 // return type. 10677 if (D.isInvalidType()) 10678 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 10679 10680 // C++0x explicit conversion operators. 10681 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20) 10682 Diag(DS.getExplicitSpecLoc(), 10683 getLangOpts().CPlusPlus11 10684 ? diag::warn_cxx98_compat_explicit_conversion_functions 10685 : diag::ext_explicit_conversion_functions) 10686 << SourceRange(DS.getExplicitSpecRange()); 10687 } 10688 10689 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 10690 /// the declaration of the given C++ conversion function. This routine 10691 /// is responsible for recording the conversion function in the C++ 10692 /// class, if possible. 10693 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 10694 assert(Conversion && "Expected to receive a conversion function declaration"); 10695 10696 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 10697 10698 // Make sure we aren't redeclaring the conversion function. 10699 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 10700 // C++ [class.conv.fct]p1: 10701 // [...] A conversion function is never used to convert a 10702 // (possibly cv-qualified) object to the (possibly cv-qualified) 10703 // same object type (or a reference to it), to a (possibly 10704 // cv-qualified) base class of that type (or a reference to it), 10705 // or to (possibly cv-qualified) void. 10706 QualType ClassType 10707 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10708 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 10709 ConvType = ConvTypeRef->getPointeeType(); 10710 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 10711 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 10712 /* Suppress diagnostics for instantiations. */; 10713 else if (Conversion->size_overridden_methods() != 0) 10714 /* Suppress diagnostics for overriding virtual function in a base class. */; 10715 else if (ConvType->isRecordType()) { 10716 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 10717 if (ConvType == ClassType) 10718 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 10719 << ClassType; 10720 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 10721 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 10722 << ClassType << ConvType; 10723 } else if (ConvType->isVoidType()) { 10724 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 10725 << ClassType << ConvType; 10726 } 10727 10728 if (FunctionTemplateDecl *ConversionTemplate 10729 = Conversion->getDescribedFunctionTemplate()) 10730 return ConversionTemplate; 10731 10732 return Conversion; 10733 } 10734 10735 namespace { 10736 /// Utility class to accumulate and print a diagnostic listing the invalid 10737 /// specifier(s) on a declaration. 10738 struct BadSpecifierDiagnoser { 10739 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10740 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10741 ~BadSpecifierDiagnoser() { 10742 Diagnostic << Specifiers; 10743 } 10744 10745 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10746 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10747 } 10748 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10749 return check(SpecLoc, 10750 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10751 } 10752 void check(SourceLocation SpecLoc, const char *Spec) { 10753 if (SpecLoc.isInvalid()) return; 10754 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10755 if (!Specifiers.empty()) Specifiers += " "; 10756 Specifiers += Spec; 10757 } 10758 10759 Sema &S; 10760 Sema::SemaDiagnosticBuilder Diagnostic; 10761 std::string Specifiers; 10762 }; 10763 } 10764 10765 /// Check the validity of a declarator that we parsed for a deduction-guide. 10766 /// These aren't actually declarators in the grammar, so we need to check that 10767 /// the user didn't specify any pieces that are not part of the deduction-guide 10768 /// grammar. 10769 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10770 StorageClass &SC) { 10771 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10772 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10773 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 10774 10775 // C++ [temp.deduct.guide]p3: 10776 // A deduction-gide shall be declared in the same scope as the 10777 // corresponding class template. 10778 if (!CurContext->getRedeclContext()->Equals( 10779 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10780 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10781 << GuidedTemplateDecl; 10782 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10783 } 10784 10785 auto &DS = D.getMutableDeclSpec(); 10786 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10787 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10788 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10789 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10790 BadSpecifierDiagnoser Diagnoser( 10791 *this, D.getIdentifierLoc(), 10792 diag::err_deduction_guide_invalid_specifier); 10793 10794 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10795 DS.ClearStorageClassSpecs(); 10796 SC = SC_None; 10797 10798 // 'explicit' is permitted. 10799 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10800 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10801 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10802 DS.ClearConstexprSpec(); 10803 10804 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10805 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10806 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10807 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10808 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10809 DS.ClearTypeQualifiers(); 10810 10811 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 10812 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 10813 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 10814 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 10815 DS.ClearTypeSpecType(); 10816 } 10817 10818 if (D.isInvalidType()) 10819 return; 10820 10821 // Check the declarator is simple enough. 10822 bool FoundFunction = false; 10823 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 10824 if (Chunk.Kind == DeclaratorChunk::Paren) 10825 continue; 10826 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 10827 Diag(D.getDeclSpec().getBeginLoc(), 10828 diag::err_deduction_guide_with_complex_decl) 10829 << D.getSourceRange(); 10830 break; 10831 } 10832 if (!Chunk.Fun.hasTrailingReturnType()) { 10833 Diag(D.getName().getBeginLoc(), 10834 diag::err_deduction_guide_no_trailing_return_type); 10835 break; 10836 } 10837 10838 // Check that the return type is written as a specialization of 10839 // the template specified as the deduction-guide's name. 10840 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 10841 TypeSourceInfo *TSI = nullptr; 10842 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 10843 assert(TSI && "deduction guide has valid type but invalid return type?"); 10844 bool AcceptableReturnType = false; 10845 bool MightInstantiateToSpecialization = false; 10846 if (auto RetTST = 10847 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 10848 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 10849 bool TemplateMatches = 10850 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 10851 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 10852 AcceptableReturnType = true; 10853 else { 10854 // This could still instantiate to the right type, unless we know it 10855 // names the wrong class template. 10856 auto *TD = SpecifiedName.getAsTemplateDecl(); 10857 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 10858 !TemplateMatches); 10859 } 10860 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 10861 MightInstantiateToSpecialization = true; 10862 } 10863 10864 if (!AcceptableReturnType) { 10865 Diag(TSI->getTypeLoc().getBeginLoc(), 10866 diag::err_deduction_guide_bad_trailing_return_type) 10867 << GuidedTemplate << TSI->getType() 10868 << MightInstantiateToSpecialization 10869 << TSI->getTypeLoc().getSourceRange(); 10870 } 10871 10872 // Keep going to check that we don't have any inner declarator pieces (we 10873 // could still have a function returning a pointer to a function). 10874 FoundFunction = true; 10875 } 10876 10877 if (D.isFunctionDefinition()) 10878 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 10879 } 10880 10881 //===----------------------------------------------------------------------===// 10882 // Namespace Handling 10883 //===----------------------------------------------------------------------===// 10884 10885 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 10886 /// reopened. 10887 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 10888 SourceLocation Loc, 10889 IdentifierInfo *II, bool *IsInline, 10890 NamespaceDecl *PrevNS) { 10891 assert(*IsInline != PrevNS->isInline()); 10892 10893 if (PrevNS->isInline()) 10894 // The user probably just forgot the 'inline', so suggest that it 10895 // be added back. 10896 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 10897 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 10898 else 10899 S.Diag(Loc, diag::err_inline_namespace_mismatch); 10900 10901 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 10902 *IsInline = PrevNS->isInline(); 10903 } 10904 10905 /// ActOnStartNamespaceDef - This is called at the start of a namespace 10906 /// definition. 10907 Decl *Sema::ActOnStartNamespaceDef( 10908 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 10909 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 10910 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 10911 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 10912 // For anonymous namespace, take the location of the left brace. 10913 SourceLocation Loc = II ? IdentLoc : LBrace; 10914 bool IsInline = InlineLoc.isValid(); 10915 bool IsInvalid = false; 10916 bool IsStd = false; 10917 bool AddToKnown = false; 10918 Scope *DeclRegionScope = NamespcScope->getParent(); 10919 10920 NamespaceDecl *PrevNS = nullptr; 10921 if (II) { 10922 // C++ [namespace.def]p2: 10923 // The identifier in an original-namespace-definition shall not 10924 // have been previously defined in the declarative region in 10925 // which the original-namespace-definition appears. The 10926 // identifier in an original-namespace-definition is the name of 10927 // the namespace. Subsequently in that declarative region, it is 10928 // treated as an original-namespace-name. 10929 // 10930 // Since namespace names are unique in their scope, and we don't 10931 // look through using directives, just look for any ordinary names 10932 // as if by qualified name lookup. 10933 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 10934 ForExternalRedeclaration); 10935 LookupQualifiedName(R, CurContext->getRedeclContext()); 10936 NamedDecl *PrevDecl = 10937 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 10938 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 10939 10940 if (PrevNS) { 10941 // This is an extended namespace definition. 10942 if (IsInline != PrevNS->isInline()) 10943 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 10944 &IsInline, PrevNS); 10945 } else if (PrevDecl) { 10946 // This is an invalid name redefinition. 10947 Diag(Loc, diag::err_redefinition_different_kind) 10948 << II; 10949 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10950 IsInvalid = true; 10951 // Continue on to push Namespc as current DeclContext and return it. 10952 } else if (II->isStr("std") && 10953 CurContext->getRedeclContext()->isTranslationUnit()) { 10954 // This is the first "real" definition of the namespace "std", so update 10955 // our cache of the "std" namespace to point at this definition. 10956 PrevNS = getStdNamespace(); 10957 IsStd = true; 10958 AddToKnown = !IsInline; 10959 } else { 10960 // We've seen this namespace for the first time. 10961 AddToKnown = !IsInline; 10962 } 10963 } else { 10964 // Anonymous namespaces. 10965 10966 // Determine whether the parent already has an anonymous namespace. 10967 DeclContext *Parent = CurContext->getRedeclContext(); 10968 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10969 PrevNS = TU->getAnonymousNamespace(); 10970 } else { 10971 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 10972 PrevNS = ND->getAnonymousNamespace(); 10973 } 10974 10975 if (PrevNS && IsInline != PrevNS->isInline()) 10976 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 10977 &IsInline, PrevNS); 10978 } 10979 10980 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 10981 StartLoc, Loc, II, PrevNS); 10982 if (IsInvalid) 10983 Namespc->setInvalidDecl(); 10984 10985 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 10986 AddPragmaAttributes(DeclRegionScope, Namespc); 10987 10988 // FIXME: Should we be merging attributes? 10989 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 10990 PushNamespaceVisibilityAttr(Attr, Loc); 10991 10992 if (IsStd) 10993 StdNamespace = Namespc; 10994 if (AddToKnown) 10995 KnownNamespaces[Namespc] = false; 10996 10997 if (II) { 10998 PushOnScopeChains(Namespc, DeclRegionScope); 10999 } else { 11000 // Link the anonymous namespace into its parent. 11001 DeclContext *Parent = CurContext->getRedeclContext(); 11002 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11003 TU->setAnonymousNamespace(Namespc); 11004 } else { 11005 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 11006 } 11007 11008 CurContext->addDecl(Namespc); 11009 11010 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 11011 // behaves as if it were replaced by 11012 // namespace unique { /* empty body */ } 11013 // using namespace unique; 11014 // namespace unique { namespace-body } 11015 // where all occurrences of 'unique' in a translation unit are 11016 // replaced by the same identifier and this identifier differs 11017 // from all other identifiers in the entire program. 11018 11019 // We just create the namespace with an empty name and then add an 11020 // implicit using declaration, just like the standard suggests. 11021 // 11022 // CodeGen enforces the "universally unique" aspect by giving all 11023 // declarations semantically contained within an anonymous 11024 // namespace internal linkage. 11025 11026 if (!PrevNS) { 11027 UD = UsingDirectiveDecl::Create(Context, Parent, 11028 /* 'using' */ LBrace, 11029 /* 'namespace' */ SourceLocation(), 11030 /* qualifier */ NestedNameSpecifierLoc(), 11031 /* identifier */ SourceLocation(), 11032 Namespc, 11033 /* Ancestor */ Parent); 11034 UD->setImplicit(); 11035 Parent->addDecl(UD); 11036 } 11037 } 11038 11039 ActOnDocumentableDecl(Namespc); 11040 11041 // Although we could have an invalid decl (i.e. the namespace name is a 11042 // redefinition), push it as current DeclContext and try to continue parsing. 11043 // FIXME: We should be able to push Namespc here, so that the each DeclContext 11044 // for the namespace has the declarations that showed up in that particular 11045 // namespace definition. 11046 PushDeclContext(NamespcScope, Namespc); 11047 return Namespc; 11048 } 11049 11050 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 11051 /// is a namespace alias, returns the namespace it points to. 11052 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 11053 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 11054 return AD->getNamespace(); 11055 return dyn_cast_or_null<NamespaceDecl>(D); 11056 } 11057 11058 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 11059 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 11060 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 11061 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 11062 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 11063 Namespc->setRBraceLoc(RBrace); 11064 PopDeclContext(); 11065 if (Namespc->hasAttr<VisibilityAttr>()) 11066 PopPragmaVisibility(true, RBrace); 11067 // If this namespace contains an export-declaration, export it now. 11068 if (DeferredExportedNamespaces.erase(Namespc)) 11069 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 11070 } 11071 11072 CXXRecordDecl *Sema::getStdBadAlloc() const { 11073 return cast_or_null<CXXRecordDecl>( 11074 StdBadAlloc.get(Context.getExternalSource())); 11075 } 11076 11077 EnumDecl *Sema::getStdAlignValT() const { 11078 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 11079 } 11080 11081 NamespaceDecl *Sema::getStdNamespace() const { 11082 return cast_or_null<NamespaceDecl>( 11083 StdNamespace.get(Context.getExternalSource())); 11084 } 11085 11086 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 11087 if (!StdExperimentalNamespaceCache) { 11088 if (auto Std = getStdNamespace()) { 11089 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 11090 SourceLocation(), LookupNamespaceName); 11091 if (!LookupQualifiedName(Result, Std) || 11092 !(StdExperimentalNamespaceCache = 11093 Result.getAsSingle<NamespaceDecl>())) 11094 Result.suppressDiagnostics(); 11095 } 11096 } 11097 return StdExperimentalNamespaceCache; 11098 } 11099 11100 namespace { 11101 11102 enum UnsupportedSTLSelect { 11103 USS_InvalidMember, 11104 USS_MissingMember, 11105 USS_NonTrivial, 11106 USS_Other 11107 }; 11108 11109 struct InvalidSTLDiagnoser { 11110 Sema &S; 11111 SourceLocation Loc; 11112 QualType TyForDiags; 11113 11114 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 11115 const VarDecl *VD = nullptr) { 11116 { 11117 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 11118 << TyForDiags << ((int)Sel); 11119 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 11120 assert(!Name.empty()); 11121 D << Name; 11122 } 11123 } 11124 if (Sel == USS_InvalidMember) { 11125 S.Diag(VD->getLocation(), diag::note_var_declared_here) 11126 << VD << VD->getSourceRange(); 11127 } 11128 return QualType(); 11129 } 11130 }; 11131 } // namespace 11132 11133 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 11134 SourceLocation Loc, 11135 ComparisonCategoryUsage Usage) { 11136 assert(getLangOpts().CPlusPlus && 11137 "Looking for comparison category type outside of C++."); 11138 11139 // Use an elaborated type for diagnostics which has a name containing the 11140 // prepended 'std' namespace but not any inline namespace names. 11141 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 11142 auto *NNS = 11143 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 11144 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 11145 }; 11146 11147 // Check if we've already successfully checked the comparison category type 11148 // before. If so, skip checking it again. 11149 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 11150 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 11151 // The only thing we need to check is that the type has a reachable 11152 // definition in the current context. 11153 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11154 return QualType(); 11155 11156 return Info->getType(); 11157 } 11158 11159 // If lookup failed 11160 if (!Info) { 11161 std::string NameForDiags = "std::"; 11162 NameForDiags += ComparisonCategories::getCategoryString(Kind); 11163 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 11164 << NameForDiags << (int)Usage; 11165 return QualType(); 11166 } 11167 11168 assert(Info->Kind == Kind); 11169 assert(Info->Record); 11170 11171 // Update the Record decl in case we encountered a forward declaration on our 11172 // first pass. FIXME: This is a bit of a hack. 11173 if (Info->Record->hasDefinition()) 11174 Info->Record = Info->Record->getDefinition(); 11175 11176 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11177 return QualType(); 11178 11179 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 11180 11181 if (!Info->Record->isTriviallyCopyable()) 11182 return UnsupportedSTLError(USS_NonTrivial); 11183 11184 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 11185 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 11186 // Tolerate empty base classes. 11187 if (Base->isEmpty()) 11188 continue; 11189 // Reject STL implementations which have at least one non-empty base. 11190 return UnsupportedSTLError(); 11191 } 11192 11193 // Check that the STL has implemented the types using a single integer field. 11194 // This expectation allows better codegen for builtin operators. We require: 11195 // (1) The class has exactly one field. 11196 // (2) The field is an integral or enumeration type. 11197 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 11198 if (std::distance(FIt, FEnd) != 1 || 11199 !FIt->getType()->isIntegralOrEnumerationType()) { 11200 return UnsupportedSTLError(); 11201 } 11202 11203 // Build each of the require values and store them in Info. 11204 for (ComparisonCategoryResult CCR : 11205 ComparisonCategories::getPossibleResultsForType(Kind)) { 11206 StringRef MemName = ComparisonCategories::getResultString(CCR); 11207 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 11208 11209 if (!ValInfo) 11210 return UnsupportedSTLError(USS_MissingMember, MemName); 11211 11212 VarDecl *VD = ValInfo->VD; 11213 assert(VD && "should not be null!"); 11214 11215 // Attempt to diagnose reasons why the STL definition of this type 11216 // might be foobar, including it failing to be a constant expression. 11217 // TODO Handle more ways the lookup or result can be invalid. 11218 if (!VD->isStaticDataMember() || 11219 !VD->isUsableInConstantExpressions(Context)) 11220 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 11221 11222 // Attempt to evaluate the var decl as a constant expression and extract 11223 // the value of its first field as a ICE. If this fails, the STL 11224 // implementation is not supported. 11225 if (!ValInfo->hasValidIntValue()) 11226 return UnsupportedSTLError(); 11227 11228 MarkVariableReferenced(Loc, VD); 11229 } 11230 11231 // We've successfully built the required types and expressions. Update 11232 // the cache and return the newly cached value. 11233 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 11234 return Info->getType(); 11235 } 11236 11237 /// Retrieve the special "std" namespace, which may require us to 11238 /// implicitly define the namespace. 11239 NamespaceDecl *Sema::getOrCreateStdNamespace() { 11240 if (!StdNamespace) { 11241 // The "std" namespace has not yet been defined, so build one implicitly. 11242 StdNamespace = NamespaceDecl::Create(Context, 11243 Context.getTranslationUnitDecl(), 11244 /*Inline=*/false, 11245 SourceLocation(), SourceLocation(), 11246 &PP.getIdentifierTable().get("std"), 11247 /*PrevDecl=*/nullptr); 11248 getStdNamespace()->setImplicit(true); 11249 } 11250 11251 return getStdNamespace(); 11252 } 11253 11254 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 11255 assert(getLangOpts().CPlusPlus && 11256 "Looking for std::initializer_list outside of C++."); 11257 11258 // We're looking for implicit instantiations of 11259 // template <typename E> class std::initializer_list. 11260 11261 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 11262 return false; 11263 11264 ClassTemplateDecl *Template = nullptr; 11265 const TemplateArgument *Arguments = nullptr; 11266 11267 if (const RecordType *RT = Ty->getAs<RecordType>()) { 11268 11269 ClassTemplateSpecializationDecl *Specialization = 11270 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 11271 if (!Specialization) 11272 return false; 11273 11274 Template = Specialization->getSpecializedTemplate(); 11275 Arguments = Specialization->getTemplateArgs().data(); 11276 } else if (const TemplateSpecializationType *TST = 11277 Ty->getAs<TemplateSpecializationType>()) { 11278 Template = dyn_cast_or_null<ClassTemplateDecl>( 11279 TST->getTemplateName().getAsTemplateDecl()); 11280 Arguments = TST->getArgs(); 11281 } 11282 if (!Template) 11283 return false; 11284 11285 if (!StdInitializerList) { 11286 // Haven't recognized std::initializer_list yet, maybe this is it. 11287 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 11288 if (TemplateClass->getIdentifier() != 11289 &PP.getIdentifierTable().get("initializer_list") || 11290 !getStdNamespace()->InEnclosingNamespaceSetOf( 11291 TemplateClass->getDeclContext())) 11292 return false; 11293 // This is a template called std::initializer_list, but is it the right 11294 // template? 11295 TemplateParameterList *Params = Template->getTemplateParameters(); 11296 if (Params->getMinRequiredArguments() != 1) 11297 return false; 11298 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 11299 return false; 11300 11301 // It's the right template. 11302 StdInitializerList = Template; 11303 } 11304 11305 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 11306 return false; 11307 11308 // This is an instance of std::initializer_list. Find the argument type. 11309 if (Element) 11310 *Element = Arguments[0].getAsType(); 11311 return true; 11312 } 11313 11314 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 11315 NamespaceDecl *Std = S.getStdNamespace(); 11316 if (!Std) { 11317 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11318 return nullptr; 11319 } 11320 11321 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 11322 Loc, Sema::LookupOrdinaryName); 11323 if (!S.LookupQualifiedName(Result, Std)) { 11324 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11325 return nullptr; 11326 } 11327 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 11328 if (!Template) { 11329 Result.suppressDiagnostics(); 11330 // We found something weird. Complain about the first thing we found. 11331 NamedDecl *Found = *Result.begin(); 11332 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 11333 return nullptr; 11334 } 11335 11336 // We found some template called std::initializer_list. Now verify that it's 11337 // correct. 11338 TemplateParameterList *Params = Template->getTemplateParameters(); 11339 if (Params->getMinRequiredArguments() != 1 || 11340 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 11341 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 11342 return nullptr; 11343 } 11344 11345 return Template; 11346 } 11347 11348 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 11349 if (!StdInitializerList) { 11350 StdInitializerList = LookupStdInitializerList(*this, Loc); 11351 if (!StdInitializerList) 11352 return QualType(); 11353 } 11354 11355 TemplateArgumentListInfo Args(Loc, Loc); 11356 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 11357 Context.getTrivialTypeSourceInfo(Element, 11358 Loc))); 11359 return Context.getCanonicalType( 11360 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 11361 } 11362 11363 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 11364 // C++ [dcl.init.list]p2: 11365 // A constructor is an initializer-list constructor if its first parameter 11366 // is of type std::initializer_list<E> or reference to possibly cv-qualified 11367 // std::initializer_list<E> for some type E, and either there are no other 11368 // parameters or else all other parameters have default arguments. 11369 if (!Ctor->hasOneParamOrDefaultArgs()) 11370 return false; 11371 11372 QualType ArgType = Ctor->getParamDecl(0)->getType(); 11373 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 11374 ArgType = RT->getPointeeType().getUnqualifiedType(); 11375 11376 return isStdInitializerList(ArgType, nullptr); 11377 } 11378 11379 /// Determine whether a using statement is in a context where it will be 11380 /// apply in all contexts. 11381 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 11382 switch (CurContext->getDeclKind()) { 11383 case Decl::TranslationUnit: 11384 return true; 11385 case Decl::LinkageSpec: 11386 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 11387 default: 11388 return false; 11389 } 11390 } 11391 11392 namespace { 11393 11394 // Callback to only accept typo corrections that are namespaces. 11395 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 11396 public: 11397 bool ValidateCandidate(const TypoCorrection &candidate) override { 11398 if (NamedDecl *ND = candidate.getCorrectionDecl()) 11399 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 11400 return false; 11401 } 11402 11403 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11404 return std::make_unique<NamespaceValidatorCCC>(*this); 11405 } 11406 }; 11407 11408 } 11409 11410 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 11411 CXXScopeSpec &SS, 11412 SourceLocation IdentLoc, 11413 IdentifierInfo *Ident) { 11414 R.clear(); 11415 NamespaceValidatorCCC CCC{}; 11416 if (TypoCorrection Corrected = 11417 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 11418 Sema::CTK_ErrorRecovery)) { 11419 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 11420 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 11421 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 11422 Ident->getName().equals(CorrectedStr); 11423 S.diagnoseTypo(Corrected, 11424 S.PDiag(diag::err_using_directive_member_suggest) 11425 << Ident << DC << DroppedSpecifier << SS.getRange(), 11426 S.PDiag(diag::note_namespace_defined_here)); 11427 } else { 11428 S.diagnoseTypo(Corrected, 11429 S.PDiag(diag::err_using_directive_suggest) << Ident, 11430 S.PDiag(diag::note_namespace_defined_here)); 11431 } 11432 R.addDecl(Corrected.getFoundDecl()); 11433 return true; 11434 } 11435 return false; 11436 } 11437 11438 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 11439 SourceLocation NamespcLoc, CXXScopeSpec &SS, 11440 SourceLocation IdentLoc, 11441 IdentifierInfo *NamespcName, 11442 const ParsedAttributesView &AttrList) { 11443 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11444 assert(NamespcName && "Invalid NamespcName."); 11445 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 11446 11447 // This can only happen along a recovery path. 11448 while (S->isTemplateParamScope()) 11449 S = S->getParent(); 11450 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11451 11452 UsingDirectiveDecl *UDir = nullptr; 11453 NestedNameSpecifier *Qualifier = nullptr; 11454 if (SS.isSet()) 11455 Qualifier = SS.getScopeRep(); 11456 11457 // Lookup namespace name. 11458 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 11459 LookupParsedName(R, S, &SS); 11460 if (R.isAmbiguous()) 11461 return nullptr; 11462 11463 if (R.empty()) { 11464 R.clear(); 11465 // Allow "using namespace std;" or "using namespace ::std;" even if 11466 // "std" hasn't been defined yet, for GCC compatibility. 11467 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11468 NamespcName->isStr("std")) { 11469 Diag(IdentLoc, diag::ext_using_undefined_std); 11470 R.addDecl(getOrCreateStdNamespace()); 11471 R.resolveKind(); 11472 } 11473 // Otherwise, attempt typo correction. 11474 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11475 } 11476 11477 if (!R.empty()) { 11478 NamedDecl *Named = R.getRepresentativeDecl(); 11479 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11480 assert(NS && "expected namespace decl"); 11481 11482 // The use of a nested name specifier may trigger deprecation warnings. 11483 DiagnoseUseOfDecl(Named, IdentLoc); 11484 11485 // C++ [namespace.udir]p1: 11486 // A using-directive specifies that the names in the nominated 11487 // namespace can be used in the scope in which the 11488 // using-directive appears after the using-directive. During 11489 // unqualified name lookup (3.4.1), the names appear as if they 11490 // were declared in the nearest enclosing namespace which 11491 // contains both the using-directive and the nominated 11492 // namespace. [Note: in this context, "contains" means "contains 11493 // directly or indirectly". ] 11494 11495 // Find enclosing context containing both using-directive and 11496 // nominated namespace. 11497 DeclContext *CommonAncestor = NS; 11498 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11499 CommonAncestor = CommonAncestor->getParent(); 11500 11501 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11502 SS.getWithLocInContext(Context), 11503 IdentLoc, Named, CommonAncestor); 11504 11505 if (IsUsingDirectiveInToplevelContext(CurContext) && 11506 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11507 Diag(IdentLoc, diag::warn_using_directive_in_header); 11508 } 11509 11510 PushUsingDirective(S, UDir); 11511 } else { 11512 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11513 } 11514 11515 if (UDir) 11516 ProcessDeclAttributeList(S, UDir, AttrList); 11517 11518 return UDir; 11519 } 11520 11521 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11522 // If the scope has an associated entity and the using directive is at 11523 // namespace or translation unit scope, add the UsingDirectiveDecl into 11524 // its lookup structure so qualified name lookup can find it. 11525 DeclContext *Ctx = S->getEntity(); 11526 if (Ctx && !Ctx->isFunctionOrMethod()) 11527 Ctx->addDecl(UDir); 11528 else 11529 // Otherwise, it is at block scope. The using-directives will affect lookup 11530 // only to the end of the scope. 11531 S->PushUsingDirective(UDir); 11532 } 11533 11534 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11535 SourceLocation UsingLoc, 11536 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11537 UnqualifiedId &Name, 11538 SourceLocation EllipsisLoc, 11539 const ParsedAttributesView &AttrList) { 11540 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11541 11542 if (SS.isEmpty()) { 11543 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11544 return nullptr; 11545 } 11546 11547 switch (Name.getKind()) { 11548 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11549 case UnqualifiedIdKind::IK_Identifier: 11550 case UnqualifiedIdKind::IK_OperatorFunctionId: 11551 case UnqualifiedIdKind::IK_LiteralOperatorId: 11552 case UnqualifiedIdKind::IK_ConversionFunctionId: 11553 break; 11554 11555 case UnqualifiedIdKind::IK_ConstructorName: 11556 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11557 // C++11 inheriting constructors. 11558 Diag(Name.getBeginLoc(), 11559 getLangOpts().CPlusPlus11 11560 ? diag::warn_cxx98_compat_using_decl_constructor 11561 : diag::err_using_decl_constructor) 11562 << SS.getRange(); 11563 11564 if (getLangOpts().CPlusPlus11) break; 11565 11566 return nullptr; 11567 11568 case UnqualifiedIdKind::IK_DestructorName: 11569 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11570 return nullptr; 11571 11572 case UnqualifiedIdKind::IK_TemplateId: 11573 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11574 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11575 return nullptr; 11576 11577 case UnqualifiedIdKind::IK_DeductionGuideName: 11578 llvm_unreachable("cannot parse qualified deduction guide name"); 11579 } 11580 11581 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11582 DeclarationName TargetName = TargetNameInfo.getName(); 11583 if (!TargetName) 11584 return nullptr; 11585 11586 // Warn about access declarations. 11587 if (UsingLoc.isInvalid()) { 11588 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11589 ? diag::err_access_decl 11590 : diag::warn_access_decl_deprecated) 11591 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11592 } 11593 11594 if (EllipsisLoc.isInvalid()) { 11595 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11596 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11597 return nullptr; 11598 } else { 11599 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11600 !TargetNameInfo.containsUnexpandedParameterPack()) { 11601 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11602 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11603 EllipsisLoc = SourceLocation(); 11604 } 11605 } 11606 11607 NamedDecl *UD = BuildUsingDeclaration( 11608 S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, SS, TargetNameInfo, 11609 EllipsisLoc, AttrList, 11610 /*IsInstantiation=*/false, 11611 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists)); 11612 if (UD) 11613 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11614 11615 return UD; 11616 } 11617 11618 /// Determine whether a using declaration considers the given 11619 /// declarations as "equivalent", e.g., if they are redeclarations of 11620 /// the same entity or are both typedefs of the same type. 11621 static bool 11622 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11623 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11624 return true; 11625 11626 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11627 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11628 return Context.hasSameType(TD1->getUnderlyingType(), 11629 TD2->getUnderlyingType()); 11630 11631 // Two using_if_exists using-declarations are equivalent if both are 11632 // unresolved. 11633 if (isa<UnresolvedUsingIfExistsDecl>(D1) && 11634 isa<UnresolvedUsingIfExistsDecl>(D2)) 11635 return true; 11636 11637 return false; 11638 } 11639 11640 11641 /// Determines whether to create a using shadow decl for a particular 11642 /// decl, given the set of decls existing prior to this using lookup. 11643 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 11644 const LookupResult &Previous, 11645 UsingShadowDecl *&PrevShadow) { 11646 // Diagnose finding a decl which is not from a base class of the 11647 // current class. We do this now because there are cases where this 11648 // function will silently decide not to build a shadow decl, which 11649 // will pre-empt further diagnostics. 11650 // 11651 // We don't need to do this in C++11 because we do the check once on 11652 // the qualifier. 11653 // 11654 // FIXME: diagnose the following if we care enough: 11655 // struct A { int foo; }; 11656 // struct B : A { using A::foo; }; 11657 // template <class T> struct C : A {}; 11658 // template <class T> struct D : C<T> { using B::foo; } // <--- 11659 // This is invalid (during instantiation) in C++03 because B::foo 11660 // resolves to the using decl in B, which is not a base class of D<T>. 11661 // We can't diagnose it immediately because C<T> is an unknown 11662 // specialization. The UsingShadowDecl in D<T> then points directly 11663 // to A::foo, which will look well-formed when we instantiate. 11664 // The right solution is to not collapse the shadow-decl chain. 11665 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 11666 DeclContext *OrigDC = Orig->getDeclContext(); 11667 11668 // Handle enums and anonymous structs. 11669 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 11670 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 11671 while (OrigRec->isAnonymousStructOrUnion()) 11672 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 11673 11674 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 11675 if (OrigDC == CurContext) { 11676 Diag(Using->getLocation(), 11677 diag::err_using_decl_nested_name_specifier_is_current_class) 11678 << Using->getQualifierLoc().getSourceRange(); 11679 Diag(Orig->getLocation(), diag::note_using_decl_target); 11680 Using->setInvalidDecl(); 11681 return true; 11682 } 11683 11684 Diag(Using->getQualifierLoc().getBeginLoc(), 11685 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11686 << Using->getQualifier() 11687 << cast<CXXRecordDecl>(CurContext) 11688 << Using->getQualifierLoc().getSourceRange(); 11689 Diag(Orig->getLocation(), diag::note_using_decl_target); 11690 Using->setInvalidDecl(); 11691 return true; 11692 } 11693 } 11694 11695 if (Previous.empty()) return false; 11696 11697 NamedDecl *Target = Orig; 11698 if (isa<UsingShadowDecl>(Target)) 11699 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11700 11701 // If the target happens to be one of the previous declarations, we 11702 // don't have a conflict. 11703 // 11704 // FIXME: but we might be increasing its access, in which case we 11705 // should redeclare it. 11706 NamedDecl *NonTag = nullptr, *Tag = nullptr; 11707 bool FoundEquivalentDecl = false; 11708 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 11709 I != E; ++I) { 11710 NamedDecl *D = (*I)->getUnderlyingDecl(); 11711 // We can have UsingDecls in our Previous results because we use the same 11712 // LookupResult for checking whether the UsingDecl itself is a valid 11713 // redeclaration. 11714 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 11715 continue; 11716 11717 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 11718 // C++ [class.mem]p19: 11719 // If T is the name of a class, then [every named member other than 11720 // a non-static data member] shall have a name different from T 11721 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11722 !isa<IndirectFieldDecl>(Target) && 11723 !isa<UnresolvedUsingValueDecl>(Target) && 11724 DiagnoseClassNameShadow( 11725 CurContext, 11726 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 11727 return true; 11728 } 11729 11730 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11731 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11732 PrevShadow = Shadow; 11733 FoundEquivalentDecl = true; 11734 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11735 // We don't conflict with an existing using shadow decl of an equivalent 11736 // declaration, but we're not a redeclaration of it. 11737 FoundEquivalentDecl = true; 11738 } 11739 11740 if (isVisible(D)) 11741 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11742 } 11743 11744 if (FoundEquivalentDecl) 11745 return false; 11746 11747 // Always emit a diagnostic for a mismatch between an unresolved 11748 // using_if_exists and a resolved using declaration in either direction. 11749 if (isa<UnresolvedUsingIfExistsDecl>(Target) != 11750 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) { 11751 if (!NonTag && !Tag) 11752 return false; 11753 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11754 Diag(Target->getLocation(), diag::note_using_decl_target); 11755 Diag((NonTag ? NonTag : Tag)->getLocation(), 11756 diag::note_using_decl_conflict); 11757 Using->setInvalidDecl(); 11758 return true; 11759 } 11760 11761 if (FunctionDecl *FD = Target->getAsFunction()) { 11762 NamedDecl *OldDecl = nullptr; 11763 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11764 /*IsForUsingDecl*/ true)) { 11765 case Ovl_Overload: 11766 return false; 11767 11768 case Ovl_NonFunction: 11769 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11770 break; 11771 11772 // We found a decl with the exact signature. 11773 case Ovl_Match: 11774 // If we're in a record, we want to hide the target, so we 11775 // return true (without a diagnostic) to tell the caller not to 11776 // build a shadow decl. 11777 if (CurContext->isRecord()) 11778 return true; 11779 11780 // If we're not in a record, this is an error. 11781 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11782 break; 11783 } 11784 11785 Diag(Target->getLocation(), diag::note_using_decl_target); 11786 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 11787 Using->setInvalidDecl(); 11788 return true; 11789 } 11790 11791 // Target is not a function. 11792 11793 if (isa<TagDecl>(Target)) { 11794 // No conflict between a tag and a non-tag. 11795 if (!Tag) return false; 11796 11797 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11798 Diag(Target->getLocation(), diag::note_using_decl_target); 11799 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 11800 Using->setInvalidDecl(); 11801 return true; 11802 } 11803 11804 // No conflict between a tag and a non-tag. 11805 if (!NonTag) return false; 11806 11807 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11808 Diag(Target->getLocation(), diag::note_using_decl_target); 11809 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 11810 Using->setInvalidDecl(); 11811 return true; 11812 } 11813 11814 /// Determine whether a direct base class is a virtual base class. 11815 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 11816 if (!Derived->getNumVBases()) 11817 return false; 11818 for (auto &B : Derived->bases()) 11819 if (B.getType()->getAsCXXRecordDecl() == Base) 11820 return B.isVirtual(); 11821 llvm_unreachable("not a direct base class"); 11822 } 11823 11824 /// Builds a shadow declaration corresponding to a 'using' declaration. 11825 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 11826 UsingDecl *UD, 11827 NamedDecl *Orig, 11828 UsingShadowDecl *PrevDecl) { 11829 // If we resolved to another shadow declaration, just coalesce them. 11830 NamedDecl *Target = Orig; 11831 if (isa<UsingShadowDecl>(Target)) { 11832 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11833 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 11834 } 11835 11836 NamedDecl *NonTemplateTarget = Target; 11837 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 11838 NonTemplateTarget = TargetTD->getTemplatedDecl(); 11839 11840 UsingShadowDecl *Shadow; 11841 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 11842 bool IsVirtualBase = 11843 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 11844 UD->getQualifier()->getAsRecordDecl()); 11845 Shadow = ConstructorUsingShadowDecl::Create( 11846 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 11847 } else { 11848 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 11849 Target); 11850 } 11851 UD->addShadowDecl(Shadow); 11852 11853 Shadow->setAccess(UD->getAccess()); 11854 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 11855 Shadow->setInvalidDecl(); 11856 11857 Shadow->setPreviousDecl(PrevDecl); 11858 11859 if (S) 11860 PushOnScopeChains(Shadow, S); 11861 else 11862 CurContext->addDecl(Shadow); 11863 11864 11865 return Shadow; 11866 } 11867 11868 /// Hides a using shadow declaration. This is required by the current 11869 /// using-decl implementation when a resolvable using declaration in a 11870 /// class is followed by a declaration which would hide or override 11871 /// one or more of the using decl's targets; for example: 11872 /// 11873 /// struct Base { void foo(int); }; 11874 /// struct Derived : Base { 11875 /// using Base::foo; 11876 /// void foo(int); 11877 /// }; 11878 /// 11879 /// The governing language is C++03 [namespace.udecl]p12: 11880 /// 11881 /// When a using-declaration brings names from a base class into a 11882 /// derived class scope, member functions in the derived class 11883 /// override and/or hide member functions with the same name and 11884 /// parameter types in a base class (rather than conflicting). 11885 /// 11886 /// There are two ways to implement this: 11887 /// (1) optimistically create shadow decls when they're not hidden 11888 /// by existing declarations, or 11889 /// (2) don't create any shadow decls (or at least don't make them 11890 /// visible) until we've fully parsed/instantiated the class. 11891 /// The problem with (1) is that we might have to retroactively remove 11892 /// a shadow decl, which requires several O(n) operations because the 11893 /// decl structures are (very reasonably) not designed for removal. 11894 /// (2) avoids this but is very fiddly and phase-dependent. 11895 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 11896 if (Shadow->getDeclName().getNameKind() == 11897 DeclarationName::CXXConversionFunctionName) 11898 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 11899 11900 // Remove it from the DeclContext... 11901 Shadow->getDeclContext()->removeDecl(Shadow); 11902 11903 // ...and the scope, if applicable... 11904 if (S) { 11905 S->RemoveDecl(Shadow); 11906 IdResolver.RemoveDecl(Shadow); 11907 } 11908 11909 // ...and the using decl. 11910 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 11911 11912 // TODO: complain somehow if Shadow was used. It shouldn't 11913 // be possible for this to happen, because...? 11914 } 11915 11916 /// Find the base specifier for a base class with the given type. 11917 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 11918 QualType DesiredBase, 11919 bool &AnyDependentBases) { 11920 // Check whether the named type is a direct base class. 11921 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 11922 .getUnqualifiedType(); 11923 for (auto &Base : Derived->bases()) { 11924 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 11925 if (CanonicalDesiredBase == BaseType) 11926 return &Base; 11927 if (BaseType->isDependentType()) 11928 AnyDependentBases = true; 11929 } 11930 return nullptr; 11931 } 11932 11933 namespace { 11934 class UsingValidatorCCC final : public CorrectionCandidateCallback { 11935 public: 11936 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 11937 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 11938 : HasTypenameKeyword(HasTypenameKeyword), 11939 IsInstantiation(IsInstantiation), OldNNS(NNS), 11940 RequireMemberOf(RequireMemberOf) {} 11941 11942 bool ValidateCandidate(const TypoCorrection &Candidate) override { 11943 NamedDecl *ND = Candidate.getCorrectionDecl(); 11944 11945 // Keywords are not valid here. 11946 if (!ND || isa<NamespaceDecl>(ND)) 11947 return false; 11948 11949 // Completely unqualified names are invalid for a 'using' declaration. 11950 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 11951 return false; 11952 11953 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 11954 // reject. 11955 11956 if (RequireMemberOf) { 11957 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11958 if (FoundRecord && FoundRecord->isInjectedClassName()) { 11959 // No-one ever wants a using-declaration to name an injected-class-name 11960 // of a base class, unless they're declaring an inheriting constructor. 11961 ASTContext &Ctx = ND->getASTContext(); 11962 if (!Ctx.getLangOpts().CPlusPlus11) 11963 return false; 11964 QualType FoundType = Ctx.getRecordType(FoundRecord); 11965 11966 // Check that the injected-class-name is named as a member of its own 11967 // type; we don't want to suggest 'using Derived::Base;', since that 11968 // means something else. 11969 NestedNameSpecifier *Specifier = 11970 Candidate.WillReplaceSpecifier() 11971 ? Candidate.getCorrectionSpecifier() 11972 : OldNNS; 11973 if (!Specifier->getAsType() || 11974 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 11975 return false; 11976 11977 // Check that this inheriting constructor declaration actually names a 11978 // direct base class of the current class. 11979 bool AnyDependentBases = false; 11980 if (!findDirectBaseWithType(RequireMemberOf, 11981 Ctx.getRecordType(FoundRecord), 11982 AnyDependentBases) && 11983 !AnyDependentBases) 11984 return false; 11985 } else { 11986 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 11987 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 11988 return false; 11989 11990 // FIXME: Check that the base class member is accessible? 11991 } 11992 } else { 11993 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11994 if (FoundRecord && FoundRecord->isInjectedClassName()) 11995 return false; 11996 } 11997 11998 if (isa<TypeDecl>(ND)) 11999 return HasTypenameKeyword || !IsInstantiation; 12000 12001 return !HasTypenameKeyword; 12002 } 12003 12004 std::unique_ptr<CorrectionCandidateCallback> clone() override { 12005 return std::make_unique<UsingValidatorCCC>(*this); 12006 } 12007 12008 private: 12009 bool HasTypenameKeyword; 12010 bool IsInstantiation; 12011 NestedNameSpecifier *OldNNS; 12012 CXXRecordDecl *RequireMemberOf; 12013 }; 12014 } // end anonymous namespace 12015 12016 /// Builds a using declaration. 12017 /// 12018 /// \param IsInstantiation - Whether this call arises from an 12019 /// instantiation of an unresolved using declaration. We treat 12020 /// the lookup differently for these declarations. 12021 NamedDecl *Sema::BuildUsingDeclaration( 12022 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 12023 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 12024 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 12025 const ParsedAttributesView &AttrList, bool IsInstantiation, 12026 bool IsUsingIfExists) { 12027 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 12028 SourceLocation IdentLoc = NameInfo.getLoc(); 12029 assert(IdentLoc.isValid() && "Invalid TargetName location."); 12030 12031 // FIXME: We ignore attributes for now. 12032 12033 // For an inheriting constructor declaration, the name of the using 12034 // declaration is the name of a constructor in this class, not in the 12035 // base class. 12036 DeclarationNameInfo UsingName = NameInfo; 12037 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 12038 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 12039 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12040 Context.getCanonicalType(Context.getRecordType(RD)))); 12041 12042 // Do the redeclaration lookup in the current scope. 12043 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 12044 ForVisibleRedeclaration); 12045 Previous.setHideTags(false); 12046 if (S) { 12047 LookupName(Previous, S); 12048 12049 // It is really dumb that we have to do this. 12050 LookupResult::Filter F = Previous.makeFilter(); 12051 while (F.hasNext()) { 12052 NamedDecl *D = F.next(); 12053 if (!isDeclInScope(D, CurContext, S)) 12054 F.erase(); 12055 // If we found a local extern declaration that's not ordinarily visible, 12056 // and this declaration is being added to a non-block scope, ignore it. 12057 // We're only checking for scope conflicts here, not also for violations 12058 // of the linkage rules. 12059 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 12060 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 12061 F.erase(); 12062 } 12063 F.done(); 12064 } else { 12065 assert(IsInstantiation && "no scope in non-instantiation"); 12066 if (CurContext->isRecord()) 12067 LookupQualifiedName(Previous, CurContext); 12068 else { 12069 // No redeclaration check is needed here; in non-member contexts we 12070 // diagnosed all possible conflicts with other using-declarations when 12071 // building the template: 12072 // 12073 // For a dependent non-type using declaration, the only valid case is 12074 // if we instantiate to a single enumerator. We check for conflicts 12075 // between shadow declarations we introduce, and we check in the template 12076 // definition for conflicts between a non-type using declaration and any 12077 // other declaration, which together covers all cases. 12078 // 12079 // A dependent typename using declaration will never successfully 12080 // instantiate, since it will always name a class member, so we reject 12081 // that in the template definition. 12082 } 12083 } 12084 12085 // Check for invalid redeclarations. 12086 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 12087 SS, IdentLoc, Previous)) 12088 return nullptr; 12089 12090 // Check for bad qualifiers. 12091 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 12092 IdentLoc)) 12093 return nullptr; 12094 12095 // 'using_if_exists' doesn't make sense on an inherited constructor. 12096 if (IsUsingIfExists && UsingName.getName().getNameKind() == 12097 DeclarationName::CXXConstructorName) { 12098 Diag(UsingLoc, diag::err_using_if_exists_on_ctor); 12099 return nullptr; 12100 } 12101 12102 DeclContext *LookupContext = computeDeclContext(SS); 12103 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12104 if (!LookupContext || EllipsisLoc.isValid()) { 12105 NamedDecl *D; 12106 if (HasTypenameKeyword) { 12107 // FIXME: not all declaration name kinds are legal here 12108 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 12109 UsingLoc, TypenameLoc, 12110 QualifierLoc, 12111 IdentLoc, NameInfo.getName(), 12112 EllipsisLoc); 12113 } else { 12114 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 12115 QualifierLoc, NameInfo, EllipsisLoc); 12116 } 12117 D->setAccess(AS); 12118 CurContext->addDecl(D); 12119 ProcessDeclAttributeList(S, D, AttrList); 12120 return D; 12121 } 12122 12123 auto Build = [&](bool Invalid) { 12124 UsingDecl *UD = 12125 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 12126 UsingName, HasTypenameKeyword); 12127 UD->setAccess(AS); 12128 CurContext->addDecl(UD); 12129 ProcessDeclAttributeList(S, UD, AttrList); 12130 UD->setInvalidDecl(Invalid); 12131 return UD; 12132 }; 12133 auto BuildInvalid = [&]{ return Build(true); }; 12134 auto BuildValid = [&]{ return Build(false); }; 12135 12136 if (RequireCompleteDeclContext(SS, LookupContext)) 12137 return BuildInvalid(); 12138 12139 // Look up the target name. 12140 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12141 12142 // Unlike most lookups, we don't always want to hide tag 12143 // declarations: tag names are visible through the using declaration 12144 // even if hidden by ordinary names, *except* in a dependent context 12145 // where it's important for the sanity of two-phase lookup. 12146 if (!IsInstantiation) 12147 R.setHideTags(false); 12148 12149 // For the purposes of this lookup, we have a base object type 12150 // equal to that of the current context. 12151 if (CurContext->isRecord()) { 12152 R.setBaseObjectType( 12153 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 12154 } 12155 12156 LookupQualifiedName(R, LookupContext); 12157 12158 if (R.empty() && IsUsingIfExists) 12159 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc, 12160 UsingName.getName()), 12161 AS_public); 12162 12163 // Try to correct typos if possible. If constructor name lookup finds no 12164 // results, that means the named class has no explicit constructors, and we 12165 // suppressed declaring implicit ones (probably because it's dependent or 12166 // invalid). 12167 if (R.empty() && 12168 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 12169 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of 12170 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where 12171 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later. 12172 auto *II = NameInfo.getName().getAsIdentifierInfo(); 12173 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 12174 CurContext->isStdNamespace() && 12175 isa<TranslationUnitDecl>(LookupContext) && 12176 getSourceManager().isInSystemHeader(UsingLoc)) 12177 return nullptr; 12178 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 12179 dyn_cast<CXXRecordDecl>(CurContext)); 12180 if (TypoCorrection Corrected = 12181 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 12182 CTK_ErrorRecovery)) { 12183 // We reject candidates where DroppedSpecifier == true, hence the 12184 // literal '0' below. 12185 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 12186 << NameInfo.getName() << LookupContext << 0 12187 << SS.getRange()); 12188 12189 // If we picked a correction with no attached Decl we can't do anything 12190 // useful with it, bail out. 12191 NamedDecl *ND = Corrected.getCorrectionDecl(); 12192 if (!ND) 12193 return BuildInvalid(); 12194 12195 // If we corrected to an inheriting constructor, handle it as one. 12196 auto *RD = dyn_cast<CXXRecordDecl>(ND); 12197 if (RD && RD->isInjectedClassName()) { 12198 // The parent of the injected class name is the class itself. 12199 RD = cast<CXXRecordDecl>(RD->getParent()); 12200 12201 // Fix up the information we'll use to build the using declaration. 12202 if (Corrected.WillReplaceSpecifier()) { 12203 NestedNameSpecifierLocBuilder Builder; 12204 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 12205 QualifierLoc.getSourceRange()); 12206 QualifierLoc = Builder.getWithLocInContext(Context); 12207 } 12208 12209 // In this case, the name we introduce is the name of a derived class 12210 // constructor. 12211 auto *CurClass = cast<CXXRecordDecl>(CurContext); 12212 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12213 Context.getCanonicalType(Context.getRecordType(CurClass)))); 12214 UsingName.setNamedTypeInfo(nullptr); 12215 for (auto *Ctor : LookupConstructors(RD)) 12216 R.addDecl(Ctor); 12217 R.resolveKind(); 12218 } else { 12219 // FIXME: Pick up all the declarations if we found an overloaded 12220 // function. 12221 UsingName.setName(ND->getDeclName()); 12222 R.addDecl(ND); 12223 } 12224 } else { 12225 Diag(IdentLoc, diag::err_no_member) 12226 << NameInfo.getName() << LookupContext << SS.getRange(); 12227 return BuildInvalid(); 12228 } 12229 } 12230 12231 if (R.isAmbiguous()) 12232 return BuildInvalid(); 12233 12234 if (HasTypenameKeyword) { 12235 // If we asked for a typename and got a non-type decl, error out. 12236 if (!R.getAsSingle<TypeDecl>() && 12237 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) { 12238 Diag(IdentLoc, diag::err_using_typename_non_type); 12239 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12240 Diag((*I)->getUnderlyingDecl()->getLocation(), 12241 diag::note_using_decl_target); 12242 return BuildInvalid(); 12243 } 12244 } else { 12245 // If we asked for a non-typename and we got a type, error out, 12246 // but only if this is an instantiation of an unresolved using 12247 // decl. Otherwise just silently find the type name. 12248 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 12249 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 12250 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 12251 return BuildInvalid(); 12252 } 12253 } 12254 12255 // C++14 [namespace.udecl]p6: 12256 // A using-declaration shall not name a namespace. 12257 if (R.getAsSingle<NamespaceDecl>()) { 12258 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 12259 << SS.getRange(); 12260 return BuildInvalid(); 12261 } 12262 12263 // C++14 [namespace.udecl]p7: 12264 // A using-declaration shall not name a scoped enumerator. 12265 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 12266 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 12267 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 12268 << SS.getRange(); 12269 return BuildInvalid(); 12270 } 12271 } 12272 12273 UsingDecl *UD = BuildValid(); 12274 12275 // Some additional rules apply to inheriting constructors. 12276 if (UsingName.getName().getNameKind() == 12277 DeclarationName::CXXConstructorName) { 12278 // Suppress access diagnostics; the access check is instead performed at the 12279 // point of use for an inheriting constructor. 12280 R.suppressDiagnostics(); 12281 if (CheckInheritingConstructorUsingDecl(UD)) 12282 return UD; 12283 } 12284 12285 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 12286 UsingShadowDecl *PrevDecl = nullptr; 12287 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 12288 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 12289 } 12290 12291 return UD; 12292 } 12293 12294 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 12295 ArrayRef<NamedDecl *> Expansions) { 12296 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 12297 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 12298 isa<UsingPackDecl>(InstantiatedFrom)); 12299 12300 auto *UPD = 12301 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 12302 UPD->setAccess(InstantiatedFrom->getAccess()); 12303 CurContext->addDecl(UPD); 12304 return UPD; 12305 } 12306 12307 /// Additional checks for a using declaration referring to a constructor name. 12308 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 12309 assert(!UD->hasTypename() && "expecting a constructor name"); 12310 12311 const Type *SourceType = UD->getQualifier()->getAsType(); 12312 assert(SourceType && 12313 "Using decl naming constructor doesn't have type in scope spec."); 12314 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 12315 12316 // Check whether the named type is a direct base class. 12317 bool AnyDependentBases = false; 12318 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 12319 AnyDependentBases); 12320 if (!Base && !AnyDependentBases) { 12321 Diag(UD->getUsingLoc(), 12322 diag::err_using_decl_constructor_not_in_direct_base) 12323 << UD->getNameInfo().getSourceRange() 12324 << QualType(SourceType, 0) << TargetClass; 12325 UD->setInvalidDecl(); 12326 return true; 12327 } 12328 12329 if (Base) 12330 Base->setInheritConstructors(); 12331 12332 return false; 12333 } 12334 12335 /// Checks that the given using declaration is not an invalid 12336 /// redeclaration. Note that this is checking only for the using decl 12337 /// itself, not for any ill-formedness among the UsingShadowDecls. 12338 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 12339 bool HasTypenameKeyword, 12340 const CXXScopeSpec &SS, 12341 SourceLocation NameLoc, 12342 const LookupResult &Prev) { 12343 NestedNameSpecifier *Qual = SS.getScopeRep(); 12344 12345 // C++03 [namespace.udecl]p8: 12346 // C++0x [namespace.udecl]p10: 12347 // A using-declaration is a declaration and can therefore be used 12348 // repeatedly where (and only where) multiple declarations are 12349 // allowed. 12350 // 12351 // That's in non-member contexts. 12352 if (!CurContext->getRedeclContext()->isRecord()) { 12353 // A dependent qualifier outside a class can only ever resolve to an 12354 // enumeration type. Therefore it conflicts with any other non-type 12355 // declaration in the same scope. 12356 // FIXME: How should we check for dependent type-type conflicts at block 12357 // scope? 12358 if (Qual->isDependent() && !HasTypenameKeyword) { 12359 for (auto *D : Prev) { 12360 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 12361 bool OldCouldBeEnumerator = 12362 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 12363 Diag(NameLoc, 12364 OldCouldBeEnumerator ? diag::err_redefinition 12365 : diag::err_redefinition_different_kind) 12366 << Prev.getLookupName(); 12367 Diag(D->getLocation(), diag::note_previous_definition); 12368 return true; 12369 } 12370 } 12371 } 12372 return false; 12373 } 12374 12375 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 12376 NamedDecl *D = *I; 12377 12378 bool DTypename; 12379 NestedNameSpecifier *DQual; 12380 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 12381 DTypename = UD->hasTypename(); 12382 DQual = UD->getQualifier(); 12383 } else if (UnresolvedUsingValueDecl *UD 12384 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 12385 DTypename = false; 12386 DQual = UD->getQualifier(); 12387 } else if (UnresolvedUsingTypenameDecl *UD 12388 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 12389 DTypename = true; 12390 DQual = UD->getQualifier(); 12391 } else continue; 12392 12393 // using decls differ if one says 'typename' and the other doesn't. 12394 // FIXME: non-dependent using decls? 12395 if (HasTypenameKeyword != DTypename) continue; 12396 12397 // using decls differ if they name different scopes (but note that 12398 // template instantiation can cause this check to trigger when it 12399 // didn't before instantiation). 12400 if (Context.getCanonicalNestedNameSpecifier(Qual) != 12401 Context.getCanonicalNestedNameSpecifier(DQual)) 12402 continue; 12403 12404 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 12405 Diag(D->getLocation(), diag::note_using_decl) << 1; 12406 return true; 12407 } 12408 12409 return false; 12410 } 12411 12412 12413 /// Checks that the given nested-name qualifier used in a using decl 12414 /// in the current context is appropriately related to the current 12415 /// scope. If an error is found, diagnoses it and returns true. 12416 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 12417 bool HasTypename, 12418 const CXXScopeSpec &SS, 12419 const DeclarationNameInfo &NameInfo, 12420 SourceLocation NameLoc) { 12421 DeclContext *NamedContext = computeDeclContext(SS); 12422 12423 if (!CurContext->isRecord()) { 12424 // C++03 [namespace.udecl]p3: 12425 // C++0x [namespace.udecl]p8: 12426 // A using-declaration for a class member shall be a member-declaration. 12427 12428 // If we weren't able to compute a valid scope, it might validly be a 12429 // dependent class scope or a dependent enumeration unscoped scope. If 12430 // we have a 'typename' keyword, the scope must resolve to a class type. 12431 if ((HasTypename && !NamedContext) || 12432 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 12433 auto *RD = NamedContext 12434 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 12435 : nullptr; 12436 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 12437 RD = nullptr; 12438 12439 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 12440 << SS.getRange(); 12441 12442 // If we have a complete, non-dependent source type, try to suggest a 12443 // way to get the same effect. 12444 if (!RD) 12445 return true; 12446 12447 // Find what this using-declaration was referring to. 12448 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12449 R.setHideTags(false); 12450 R.suppressDiagnostics(); 12451 LookupQualifiedName(R, RD); 12452 12453 if (R.getAsSingle<TypeDecl>()) { 12454 if (getLangOpts().CPlusPlus11) { 12455 // Convert 'using X::Y;' to 'using Y = X::Y;'. 12456 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 12457 << 0 // alias declaration 12458 << FixItHint::CreateInsertion(SS.getBeginLoc(), 12459 NameInfo.getName().getAsString() + 12460 " = "); 12461 } else { 12462 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 12463 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 12464 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 12465 << 1 // typedef declaration 12466 << FixItHint::CreateReplacement(UsingLoc, "typedef") 12467 << FixItHint::CreateInsertion( 12468 InsertLoc, " " + NameInfo.getName().getAsString()); 12469 } 12470 } else if (R.getAsSingle<VarDecl>()) { 12471 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12472 // repeating the type of the static data member here. 12473 FixItHint FixIt; 12474 if (getLangOpts().CPlusPlus11) { 12475 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12476 FixIt = FixItHint::CreateReplacement( 12477 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 12478 } 12479 12480 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12481 << 2 // reference declaration 12482 << FixIt; 12483 } else if (R.getAsSingle<EnumConstantDecl>()) { 12484 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12485 // repeating the type of the enumeration here, and we can't do so if 12486 // the type is anonymous. 12487 FixItHint FixIt; 12488 if (getLangOpts().CPlusPlus11) { 12489 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12490 FixIt = FixItHint::CreateReplacement( 12491 UsingLoc, 12492 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 12493 } 12494 12495 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12496 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 12497 << FixIt; 12498 } 12499 return true; 12500 } 12501 12502 // Otherwise, this might be valid. 12503 return false; 12504 } 12505 12506 // The current scope is a record. 12507 12508 // If the named context is dependent, we can't decide much. 12509 if (!NamedContext) { 12510 // FIXME: in C++0x, we can diagnose if we can prove that the 12511 // nested-name-specifier does not refer to a base class, which is 12512 // still possible in some cases. 12513 12514 // Otherwise we have to conservatively report that things might be 12515 // okay. 12516 return false; 12517 } 12518 12519 if (!NamedContext->isRecord()) { 12520 // Ideally this would point at the last name in the specifier, 12521 // but we don't have that level of source info. 12522 Diag(SS.getRange().getBegin(), 12523 diag::err_using_decl_nested_name_specifier_is_not_class) 12524 << SS.getScopeRep() << SS.getRange(); 12525 return true; 12526 } 12527 12528 if (!NamedContext->isDependentContext() && 12529 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 12530 return true; 12531 12532 if (getLangOpts().CPlusPlus11) { 12533 // C++11 [namespace.udecl]p3: 12534 // In a using-declaration used as a member-declaration, the 12535 // nested-name-specifier shall name a base class of the class 12536 // being defined. 12537 12538 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 12539 cast<CXXRecordDecl>(NamedContext))) { 12540 if (CurContext == NamedContext) { 12541 Diag(NameLoc, 12542 diag::err_using_decl_nested_name_specifier_is_current_class) 12543 << SS.getRange(); 12544 return true; 12545 } 12546 12547 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 12548 Diag(SS.getRange().getBegin(), 12549 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12550 << SS.getScopeRep() 12551 << cast<CXXRecordDecl>(CurContext) 12552 << SS.getRange(); 12553 } 12554 return true; 12555 } 12556 12557 return false; 12558 } 12559 12560 // C++03 [namespace.udecl]p4: 12561 // A using-declaration used as a member-declaration shall refer 12562 // to a member of a base class of the class being defined [etc.]. 12563 12564 // Salient point: SS doesn't have to name a base class as long as 12565 // lookup only finds members from base classes. Therefore we can 12566 // diagnose here only if we can prove that that can't happen, 12567 // i.e. if the class hierarchies provably don't intersect. 12568 12569 // TODO: it would be nice if "definitely valid" results were cached 12570 // in the UsingDecl and UsingShadowDecl so that these checks didn't 12571 // need to be repeated. 12572 12573 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 12574 auto Collect = [&Bases](const CXXRecordDecl *Base) { 12575 Bases.insert(Base); 12576 return true; 12577 }; 12578 12579 // Collect all bases. Return false if we find a dependent base. 12580 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 12581 return false; 12582 12583 // Returns true if the base is dependent or is one of the accumulated base 12584 // classes. 12585 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 12586 return !Bases.count(Base); 12587 }; 12588 12589 // Return false if the class has a dependent base or if it or one 12590 // of its bases is present in the base set of the current context. 12591 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 12592 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 12593 return false; 12594 12595 Diag(SS.getRange().getBegin(), 12596 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12597 << SS.getScopeRep() 12598 << cast<CXXRecordDecl>(CurContext) 12599 << SS.getRange(); 12600 12601 return true; 12602 } 12603 12604 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 12605 MultiTemplateParamsArg TemplateParamLists, 12606 SourceLocation UsingLoc, UnqualifiedId &Name, 12607 const ParsedAttributesView &AttrList, 12608 TypeResult Type, Decl *DeclFromDeclSpec) { 12609 // Skip up to the relevant declaration scope. 12610 while (S->isTemplateParamScope()) 12611 S = S->getParent(); 12612 assert((S->getFlags() & Scope::DeclScope) && 12613 "got alias-declaration outside of declaration scope"); 12614 12615 if (Type.isInvalid()) 12616 return nullptr; 12617 12618 bool Invalid = false; 12619 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 12620 TypeSourceInfo *TInfo = nullptr; 12621 GetTypeFromParser(Type.get(), &TInfo); 12622 12623 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 12624 return nullptr; 12625 12626 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 12627 UPPC_DeclarationType)) { 12628 Invalid = true; 12629 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12630 TInfo->getTypeLoc().getBeginLoc()); 12631 } 12632 12633 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12634 TemplateParamLists.size() 12635 ? forRedeclarationInCurContext() 12636 : ForVisibleRedeclaration); 12637 LookupName(Previous, S); 12638 12639 // Warn about shadowing the name of a template parameter. 12640 if (Previous.isSingleResult() && 12641 Previous.getFoundDecl()->isTemplateParameter()) { 12642 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 12643 Previous.clear(); 12644 } 12645 12646 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 12647 "name in alias declaration must be an identifier"); 12648 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 12649 Name.StartLocation, 12650 Name.Identifier, TInfo); 12651 12652 NewTD->setAccess(AS); 12653 12654 if (Invalid) 12655 NewTD->setInvalidDecl(); 12656 12657 ProcessDeclAttributeList(S, NewTD, AttrList); 12658 AddPragmaAttributes(S, NewTD); 12659 12660 CheckTypedefForVariablyModifiedType(S, NewTD); 12661 Invalid |= NewTD->isInvalidDecl(); 12662 12663 bool Redeclaration = false; 12664 12665 NamedDecl *NewND; 12666 if (TemplateParamLists.size()) { 12667 TypeAliasTemplateDecl *OldDecl = nullptr; 12668 TemplateParameterList *OldTemplateParams = nullptr; 12669 12670 if (TemplateParamLists.size() != 1) { 12671 Diag(UsingLoc, diag::err_alias_template_extra_headers) 12672 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 12673 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 12674 } 12675 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 12676 12677 // Check that we can declare a template here. 12678 if (CheckTemplateDeclScope(S, TemplateParams)) 12679 return nullptr; 12680 12681 // Only consider previous declarations in the same scope. 12682 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 12683 /*ExplicitInstantiationOrSpecialization*/false); 12684 if (!Previous.empty()) { 12685 Redeclaration = true; 12686 12687 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 12688 if (!OldDecl && !Invalid) { 12689 Diag(UsingLoc, diag::err_redefinition_different_kind) 12690 << Name.Identifier; 12691 12692 NamedDecl *OldD = Previous.getRepresentativeDecl(); 12693 if (OldD->getLocation().isValid()) 12694 Diag(OldD->getLocation(), diag::note_previous_definition); 12695 12696 Invalid = true; 12697 } 12698 12699 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 12700 if (TemplateParameterListsAreEqual(TemplateParams, 12701 OldDecl->getTemplateParameters(), 12702 /*Complain=*/true, 12703 TPL_TemplateMatch)) 12704 OldTemplateParams = 12705 OldDecl->getMostRecentDecl()->getTemplateParameters(); 12706 else 12707 Invalid = true; 12708 12709 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 12710 if (!Invalid && 12711 !Context.hasSameType(OldTD->getUnderlyingType(), 12712 NewTD->getUnderlyingType())) { 12713 // FIXME: The C++0x standard does not clearly say this is ill-formed, 12714 // but we can't reasonably accept it. 12715 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 12716 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 12717 if (OldTD->getLocation().isValid()) 12718 Diag(OldTD->getLocation(), diag::note_previous_definition); 12719 Invalid = true; 12720 } 12721 } 12722 } 12723 12724 // Merge any previous default template arguments into our parameters, 12725 // and check the parameter list. 12726 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 12727 TPC_TypeAliasTemplate)) 12728 return nullptr; 12729 12730 TypeAliasTemplateDecl *NewDecl = 12731 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 12732 Name.Identifier, TemplateParams, 12733 NewTD); 12734 NewTD->setDescribedAliasTemplate(NewDecl); 12735 12736 NewDecl->setAccess(AS); 12737 12738 if (Invalid) 12739 NewDecl->setInvalidDecl(); 12740 else if (OldDecl) { 12741 NewDecl->setPreviousDecl(OldDecl); 12742 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 12743 } 12744 12745 NewND = NewDecl; 12746 } else { 12747 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 12748 setTagNameForLinkagePurposes(TD, NewTD); 12749 handleTagNumbering(TD, S); 12750 } 12751 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 12752 NewND = NewTD; 12753 } 12754 12755 PushOnScopeChains(NewND, S); 12756 ActOnDocumentableDecl(NewND); 12757 return NewND; 12758 } 12759 12760 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 12761 SourceLocation AliasLoc, 12762 IdentifierInfo *Alias, CXXScopeSpec &SS, 12763 SourceLocation IdentLoc, 12764 IdentifierInfo *Ident) { 12765 12766 // Lookup the namespace name. 12767 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 12768 LookupParsedName(R, S, &SS); 12769 12770 if (R.isAmbiguous()) 12771 return nullptr; 12772 12773 if (R.empty()) { 12774 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 12775 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 12776 return nullptr; 12777 } 12778 } 12779 assert(!R.isAmbiguous() && !R.empty()); 12780 NamedDecl *ND = R.getRepresentativeDecl(); 12781 12782 // Check if we have a previous declaration with the same name. 12783 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 12784 ForVisibleRedeclaration); 12785 LookupName(PrevR, S); 12786 12787 // Check we're not shadowing a template parameter. 12788 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 12789 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 12790 PrevR.clear(); 12791 } 12792 12793 // Filter out any other lookup result from an enclosing scope. 12794 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 12795 /*AllowInlineNamespace*/false); 12796 12797 // Find the previous declaration and check that we can redeclare it. 12798 NamespaceAliasDecl *Prev = nullptr; 12799 if (PrevR.isSingleResult()) { 12800 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 12801 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 12802 // We already have an alias with the same name that points to the same 12803 // namespace; check that it matches. 12804 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 12805 Prev = AD; 12806 } else if (isVisible(PrevDecl)) { 12807 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 12808 << Alias; 12809 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 12810 << AD->getNamespace(); 12811 return nullptr; 12812 } 12813 } else if (isVisible(PrevDecl)) { 12814 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 12815 ? diag::err_redefinition 12816 : diag::err_redefinition_different_kind; 12817 Diag(AliasLoc, DiagID) << Alias; 12818 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12819 return nullptr; 12820 } 12821 } 12822 12823 // The use of a nested name specifier may trigger deprecation warnings. 12824 DiagnoseUseOfDecl(ND, IdentLoc); 12825 12826 NamespaceAliasDecl *AliasDecl = 12827 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 12828 Alias, SS.getWithLocInContext(Context), 12829 IdentLoc, ND); 12830 if (Prev) 12831 AliasDecl->setPreviousDecl(Prev); 12832 12833 PushOnScopeChains(AliasDecl, S); 12834 return AliasDecl; 12835 } 12836 12837 namespace { 12838 struct SpecialMemberExceptionSpecInfo 12839 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 12840 SourceLocation Loc; 12841 Sema::ImplicitExceptionSpecification ExceptSpec; 12842 12843 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 12844 Sema::CXXSpecialMember CSM, 12845 Sema::InheritedConstructorInfo *ICI, 12846 SourceLocation Loc) 12847 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 12848 12849 bool visitBase(CXXBaseSpecifier *Base); 12850 bool visitField(FieldDecl *FD); 12851 12852 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 12853 unsigned Quals); 12854 12855 void visitSubobjectCall(Subobject Subobj, 12856 Sema::SpecialMemberOverloadResult SMOR); 12857 }; 12858 } 12859 12860 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 12861 auto *RT = Base->getType()->getAs<RecordType>(); 12862 if (!RT) 12863 return false; 12864 12865 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 12866 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 12867 if (auto *BaseCtor = SMOR.getMethod()) { 12868 visitSubobjectCall(Base, BaseCtor); 12869 return false; 12870 } 12871 12872 visitClassSubobject(BaseClass, Base, 0); 12873 return false; 12874 } 12875 12876 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 12877 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 12878 Expr *E = FD->getInClassInitializer(); 12879 if (!E) 12880 // FIXME: It's a little wasteful to build and throw away a 12881 // CXXDefaultInitExpr here. 12882 // FIXME: We should have a single context note pointing at Loc, and 12883 // this location should be MD->getLocation() instead, since that's 12884 // the location where we actually use the default init expression. 12885 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 12886 if (E) 12887 ExceptSpec.CalledExpr(E); 12888 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 12889 ->getAs<RecordType>()) { 12890 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 12891 FD->getType().getCVRQualifiers()); 12892 } 12893 return false; 12894 } 12895 12896 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 12897 Subobject Subobj, 12898 unsigned Quals) { 12899 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 12900 bool IsMutable = Field && Field->isMutable(); 12901 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 12902 } 12903 12904 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 12905 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 12906 // Note, if lookup fails, it doesn't matter what exception specification we 12907 // choose because the special member will be deleted. 12908 if (CXXMethodDecl *MD = SMOR.getMethod()) 12909 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 12910 } 12911 12912 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 12913 llvm::APSInt Result; 12914 ExprResult Converted = CheckConvertedConstantExpression( 12915 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 12916 ExplicitSpec.setExpr(Converted.get()); 12917 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 12918 ExplicitSpec.setKind(Result.getBoolValue() 12919 ? ExplicitSpecKind::ResolvedTrue 12920 : ExplicitSpecKind::ResolvedFalse); 12921 return true; 12922 } 12923 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 12924 return false; 12925 } 12926 12927 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 12928 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 12929 if (!ExplicitExpr->isTypeDependent()) 12930 tryResolveExplicitSpecifier(ES); 12931 return ES; 12932 } 12933 12934 static Sema::ImplicitExceptionSpecification 12935 ComputeDefaultedSpecialMemberExceptionSpec( 12936 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 12937 Sema::InheritedConstructorInfo *ICI) { 12938 ComputingExceptionSpec CES(S, MD, Loc); 12939 12940 CXXRecordDecl *ClassDecl = MD->getParent(); 12941 12942 // C++ [except.spec]p14: 12943 // An implicitly declared special member function (Clause 12) shall have an 12944 // exception-specification. [...] 12945 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 12946 if (ClassDecl->isInvalidDecl()) 12947 return Info.ExceptSpec; 12948 12949 // FIXME: If this diagnostic fires, we're probably missing a check for 12950 // attempting to resolve an exception specification before it's known 12951 // at a higher level. 12952 if (S.RequireCompleteType(MD->getLocation(), 12953 S.Context.getRecordType(ClassDecl), 12954 diag::err_exception_spec_incomplete_type)) 12955 return Info.ExceptSpec; 12956 12957 // C++1z [except.spec]p7: 12958 // [Look for exceptions thrown by] a constructor selected [...] to 12959 // initialize a potentially constructed subobject, 12960 // C++1z [except.spec]p8: 12961 // The exception specification for an implicitly-declared destructor, or a 12962 // destructor without a noexcept-specifier, is potentially-throwing if and 12963 // only if any of the destructors for any of its potentially constructed 12964 // subojects is potentially throwing. 12965 // FIXME: We respect the first rule but ignore the "potentially constructed" 12966 // in the second rule to resolve a core issue (no number yet) that would have 12967 // us reject: 12968 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 12969 // struct B : A {}; 12970 // struct C : B { void f(); }; 12971 // ... due to giving B::~B() a non-throwing exception specification. 12972 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 12973 : Info.VisitAllBases); 12974 12975 return Info.ExceptSpec; 12976 } 12977 12978 namespace { 12979 /// RAII object to register a special member as being currently declared. 12980 struct DeclaringSpecialMember { 12981 Sema &S; 12982 Sema::SpecialMemberDecl D; 12983 Sema::ContextRAII SavedContext; 12984 bool WasAlreadyBeingDeclared; 12985 12986 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 12987 : S(S), D(RD, CSM), SavedContext(S, RD) { 12988 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 12989 if (WasAlreadyBeingDeclared) 12990 // This almost never happens, but if it does, ensure that our cache 12991 // doesn't contain a stale result. 12992 S.SpecialMemberCache.clear(); 12993 else { 12994 // Register a note to be produced if we encounter an error while 12995 // declaring the special member. 12996 Sema::CodeSynthesisContext Ctx; 12997 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 12998 // FIXME: We don't have a location to use here. Using the class's 12999 // location maintains the fiction that we declare all special members 13000 // with the class, but (1) it's not clear that lying about that helps our 13001 // users understand what's going on, and (2) there may be outer contexts 13002 // on the stack (some of which are relevant) and printing them exposes 13003 // our lies. 13004 Ctx.PointOfInstantiation = RD->getLocation(); 13005 Ctx.Entity = RD; 13006 Ctx.SpecialMember = CSM; 13007 S.pushCodeSynthesisContext(Ctx); 13008 } 13009 } 13010 ~DeclaringSpecialMember() { 13011 if (!WasAlreadyBeingDeclared) { 13012 S.SpecialMembersBeingDeclared.erase(D); 13013 S.popCodeSynthesisContext(); 13014 } 13015 } 13016 13017 /// Are we already trying to declare this special member? 13018 bool isAlreadyBeingDeclared() const { 13019 return WasAlreadyBeingDeclared; 13020 } 13021 }; 13022 } 13023 13024 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 13025 // Look up any existing declarations, but don't trigger declaration of all 13026 // implicit special members with this name. 13027 DeclarationName Name = FD->getDeclName(); 13028 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 13029 ForExternalRedeclaration); 13030 for (auto *D : FD->getParent()->lookup(Name)) 13031 if (auto *Acceptable = R.getAcceptableDecl(D)) 13032 R.addDecl(Acceptable); 13033 R.resolveKind(); 13034 R.suppressDiagnostics(); 13035 13036 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 13037 } 13038 13039 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 13040 QualType ResultTy, 13041 ArrayRef<QualType> Args) { 13042 // Build an exception specification pointing back at this constructor. 13043 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 13044 13045 LangAS AS = getDefaultCXXMethodAddrSpace(); 13046 if (AS != LangAS::Default) { 13047 EPI.TypeQuals.addAddressSpace(AS); 13048 } 13049 13050 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 13051 SpecialMem->setType(QT); 13052 } 13053 13054 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 13055 CXXRecordDecl *ClassDecl) { 13056 // C++ [class.ctor]p5: 13057 // A default constructor for a class X is a constructor of class X 13058 // that can be called without an argument. If there is no 13059 // user-declared constructor for class X, a default constructor is 13060 // implicitly declared. An implicitly-declared default constructor 13061 // is an inline public member of its class. 13062 assert(ClassDecl->needsImplicitDefaultConstructor() && 13063 "Should not build implicit default constructor!"); 13064 13065 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 13066 if (DSM.isAlreadyBeingDeclared()) 13067 return nullptr; 13068 13069 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13070 CXXDefaultConstructor, 13071 false); 13072 13073 // Create the actual constructor declaration. 13074 CanQualType ClassType 13075 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13076 SourceLocation ClassLoc = ClassDecl->getLocation(); 13077 DeclarationName Name 13078 = Context.DeclarationNames.getCXXConstructorName(ClassType); 13079 DeclarationNameInfo NameInfo(Name, ClassLoc); 13080 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 13081 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 13082 /*TInfo=*/nullptr, ExplicitSpecifier(), 13083 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 13084 Constexpr ? ConstexprSpecKind::Constexpr 13085 : ConstexprSpecKind::Unspecified); 13086 DefaultCon->setAccess(AS_public); 13087 DefaultCon->setDefaulted(); 13088 13089 if (getLangOpts().CUDA) { 13090 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 13091 DefaultCon, 13092 /* ConstRHS */ false, 13093 /* Diagnose */ false); 13094 } 13095 13096 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 13097 13098 // We don't need to use SpecialMemberIsTrivial here; triviality for default 13099 // constructors is easy to compute. 13100 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 13101 13102 // Note that we have declared this constructor. 13103 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 13104 13105 Scope *S = getScopeForContext(ClassDecl); 13106 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 13107 13108 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 13109 SetDeclDeleted(DefaultCon, ClassLoc); 13110 13111 if (S) 13112 PushOnScopeChains(DefaultCon, S, false); 13113 ClassDecl->addDecl(DefaultCon); 13114 13115 return DefaultCon; 13116 } 13117 13118 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 13119 CXXConstructorDecl *Constructor) { 13120 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 13121 !Constructor->doesThisDeclarationHaveABody() && 13122 !Constructor->isDeleted()) && 13123 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 13124 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13125 return; 13126 13127 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13128 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 13129 13130 SynthesizedFunctionScope Scope(*this, Constructor); 13131 13132 // The exception specification is needed because we are defining the 13133 // function. 13134 ResolveExceptionSpec(CurrentLocation, 13135 Constructor->getType()->castAs<FunctionProtoType>()); 13136 MarkVTableUsed(CurrentLocation, ClassDecl); 13137 13138 // Add a context note for diagnostics produced after this point. 13139 Scope.addContextNote(CurrentLocation); 13140 13141 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 13142 Constructor->setInvalidDecl(); 13143 return; 13144 } 13145 13146 SourceLocation Loc = Constructor->getEndLoc().isValid() 13147 ? Constructor->getEndLoc() 13148 : Constructor->getLocation(); 13149 Constructor->setBody(new (Context) CompoundStmt(Loc)); 13150 Constructor->markUsed(Context); 13151 13152 if (ASTMutationListener *L = getASTMutationListener()) { 13153 L->CompletedImplicitDefinition(Constructor); 13154 } 13155 13156 DiagnoseUninitializedFields(*this, Constructor); 13157 } 13158 13159 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 13160 // Perform any delayed checks on exception specifications. 13161 CheckDelayedMemberExceptionSpecs(); 13162 } 13163 13164 /// Find or create the fake constructor we synthesize to model constructing an 13165 /// object of a derived class via a constructor of a base class. 13166 CXXConstructorDecl * 13167 Sema::findInheritingConstructor(SourceLocation Loc, 13168 CXXConstructorDecl *BaseCtor, 13169 ConstructorUsingShadowDecl *Shadow) { 13170 CXXRecordDecl *Derived = Shadow->getParent(); 13171 SourceLocation UsingLoc = Shadow->getLocation(); 13172 13173 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 13174 // For now we use the name of the base class constructor as a member of the 13175 // derived class to indicate a (fake) inherited constructor name. 13176 DeclarationName Name = BaseCtor->getDeclName(); 13177 13178 // Check to see if we already have a fake constructor for this inherited 13179 // constructor call. 13180 for (NamedDecl *Ctor : Derived->lookup(Name)) 13181 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 13182 ->getInheritedConstructor() 13183 .getConstructor(), 13184 BaseCtor)) 13185 return cast<CXXConstructorDecl>(Ctor); 13186 13187 DeclarationNameInfo NameInfo(Name, UsingLoc); 13188 TypeSourceInfo *TInfo = 13189 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 13190 FunctionProtoTypeLoc ProtoLoc = 13191 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 13192 13193 // Check the inherited constructor is valid and find the list of base classes 13194 // from which it was inherited. 13195 InheritedConstructorInfo ICI(*this, Loc, Shadow); 13196 13197 bool Constexpr = 13198 BaseCtor->isConstexpr() && 13199 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 13200 false, BaseCtor, &ICI); 13201 13202 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 13203 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 13204 BaseCtor->getExplicitSpecifier(), /*isInline=*/true, 13205 /*isImplicitlyDeclared=*/true, 13206 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified, 13207 InheritedConstructor(Shadow, BaseCtor), 13208 BaseCtor->getTrailingRequiresClause()); 13209 if (Shadow->isInvalidDecl()) 13210 DerivedCtor->setInvalidDecl(); 13211 13212 // Build an unevaluated exception specification for this fake constructor. 13213 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 13214 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13215 EPI.ExceptionSpec.Type = EST_Unevaluated; 13216 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 13217 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 13218 FPT->getParamTypes(), EPI)); 13219 13220 // Build the parameter declarations. 13221 SmallVector<ParmVarDecl *, 16> ParamDecls; 13222 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 13223 TypeSourceInfo *TInfo = 13224 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 13225 ParmVarDecl *PD = ParmVarDecl::Create( 13226 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 13227 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 13228 PD->setScopeInfo(0, I); 13229 PD->setImplicit(); 13230 // Ensure attributes are propagated onto parameters (this matters for 13231 // format, pass_object_size, ...). 13232 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 13233 ParamDecls.push_back(PD); 13234 ProtoLoc.setParam(I, PD); 13235 } 13236 13237 // Set up the new constructor. 13238 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 13239 DerivedCtor->setAccess(BaseCtor->getAccess()); 13240 DerivedCtor->setParams(ParamDecls); 13241 Derived->addDecl(DerivedCtor); 13242 13243 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 13244 SetDeclDeleted(DerivedCtor, UsingLoc); 13245 13246 return DerivedCtor; 13247 } 13248 13249 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 13250 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 13251 Ctor->getInheritedConstructor().getShadowDecl()); 13252 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 13253 /*Diagnose*/true); 13254 } 13255 13256 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 13257 CXXConstructorDecl *Constructor) { 13258 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13259 assert(Constructor->getInheritedConstructor() && 13260 !Constructor->doesThisDeclarationHaveABody() && 13261 !Constructor->isDeleted()); 13262 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13263 return; 13264 13265 // Initializations are performed "as if by a defaulted default constructor", 13266 // so enter the appropriate scope. 13267 SynthesizedFunctionScope Scope(*this, Constructor); 13268 13269 // The exception specification is needed because we are defining the 13270 // function. 13271 ResolveExceptionSpec(CurrentLocation, 13272 Constructor->getType()->castAs<FunctionProtoType>()); 13273 MarkVTableUsed(CurrentLocation, ClassDecl); 13274 13275 // Add a context note for diagnostics produced after this point. 13276 Scope.addContextNote(CurrentLocation); 13277 13278 ConstructorUsingShadowDecl *Shadow = 13279 Constructor->getInheritedConstructor().getShadowDecl(); 13280 CXXConstructorDecl *InheritedCtor = 13281 Constructor->getInheritedConstructor().getConstructor(); 13282 13283 // [class.inhctor.init]p1: 13284 // initialization proceeds as if a defaulted default constructor is used to 13285 // initialize the D object and each base class subobject from which the 13286 // constructor was inherited 13287 13288 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 13289 CXXRecordDecl *RD = Shadow->getParent(); 13290 SourceLocation InitLoc = Shadow->getLocation(); 13291 13292 // Build explicit initializers for all base classes from which the 13293 // constructor was inherited. 13294 SmallVector<CXXCtorInitializer*, 8> Inits; 13295 for (bool VBase : {false, true}) { 13296 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 13297 if (B.isVirtual() != VBase) 13298 continue; 13299 13300 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 13301 if (!BaseRD) 13302 continue; 13303 13304 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 13305 if (!BaseCtor.first) 13306 continue; 13307 13308 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 13309 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 13310 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 13311 13312 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 13313 Inits.push_back(new (Context) CXXCtorInitializer( 13314 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 13315 SourceLocation())); 13316 } 13317 } 13318 13319 // We now proceed as if for a defaulted default constructor, with the relevant 13320 // initializers replaced. 13321 13322 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 13323 Constructor->setInvalidDecl(); 13324 return; 13325 } 13326 13327 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 13328 Constructor->markUsed(Context); 13329 13330 if (ASTMutationListener *L = getASTMutationListener()) { 13331 L->CompletedImplicitDefinition(Constructor); 13332 } 13333 13334 DiagnoseUninitializedFields(*this, Constructor); 13335 } 13336 13337 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 13338 // C++ [class.dtor]p2: 13339 // If a class has no user-declared destructor, a destructor is 13340 // declared implicitly. An implicitly-declared destructor is an 13341 // inline public member of its class. 13342 assert(ClassDecl->needsImplicitDestructor()); 13343 13344 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 13345 if (DSM.isAlreadyBeingDeclared()) 13346 return nullptr; 13347 13348 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13349 CXXDestructor, 13350 false); 13351 13352 // Create the actual destructor declaration. 13353 CanQualType ClassType 13354 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13355 SourceLocation ClassLoc = ClassDecl->getLocation(); 13356 DeclarationName Name 13357 = Context.DeclarationNames.getCXXDestructorName(ClassType); 13358 DeclarationNameInfo NameInfo(Name, ClassLoc); 13359 CXXDestructorDecl *Destructor = 13360 CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 13361 QualType(), nullptr, /*isInline=*/true, 13362 /*isImplicitlyDeclared=*/true, 13363 Constexpr ? ConstexprSpecKind::Constexpr 13364 : ConstexprSpecKind::Unspecified); 13365 Destructor->setAccess(AS_public); 13366 Destructor->setDefaulted(); 13367 13368 if (getLangOpts().CUDA) { 13369 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 13370 Destructor, 13371 /* ConstRHS */ false, 13372 /* Diagnose */ false); 13373 } 13374 13375 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 13376 13377 // We don't need to use SpecialMemberIsTrivial here; triviality for 13378 // destructors is easy to compute. 13379 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 13380 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 13381 ClassDecl->hasTrivialDestructorForCall()); 13382 13383 // Note that we have declared this destructor. 13384 ++getASTContext().NumImplicitDestructorsDeclared; 13385 13386 Scope *S = getScopeForContext(ClassDecl); 13387 CheckImplicitSpecialMemberDeclaration(S, Destructor); 13388 13389 // We can't check whether an implicit destructor is deleted before we complete 13390 // the definition of the class, because its validity depends on the alignment 13391 // of the class. We'll check this from ActOnFields once the class is complete. 13392 if (ClassDecl->isCompleteDefinition() && 13393 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 13394 SetDeclDeleted(Destructor, ClassLoc); 13395 13396 // Introduce this destructor into its scope. 13397 if (S) 13398 PushOnScopeChains(Destructor, S, false); 13399 ClassDecl->addDecl(Destructor); 13400 13401 return Destructor; 13402 } 13403 13404 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 13405 CXXDestructorDecl *Destructor) { 13406 assert((Destructor->isDefaulted() && 13407 !Destructor->doesThisDeclarationHaveABody() && 13408 !Destructor->isDeleted()) && 13409 "DefineImplicitDestructor - call it for implicit default dtor"); 13410 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 13411 return; 13412 13413 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13414 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 13415 13416 SynthesizedFunctionScope Scope(*this, Destructor); 13417 13418 // The exception specification is needed because we are defining the 13419 // function. 13420 ResolveExceptionSpec(CurrentLocation, 13421 Destructor->getType()->castAs<FunctionProtoType>()); 13422 MarkVTableUsed(CurrentLocation, ClassDecl); 13423 13424 // Add a context note for diagnostics produced after this point. 13425 Scope.addContextNote(CurrentLocation); 13426 13427 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13428 Destructor->getParent()); 13429 13430 if (CheckDestructor(Destructor)) { 13431 Destructor->setInvalidDecl(); 13432 return; 13433 } 13434 13435 SourceLocation Loc = Destructor->getEndLoc().isValid() 13436 ? Destructor->getEndLoc() 13437 : Destructor->getLocation(); 13438 Destructor->setBody(new (Context) CompoundStmt(Loc)); 13439 Destructor->markUsed(Context); 13440 13441 if (ASTMutationListener *L = getASTMutationListener()) { 13442 L->CompletedImplicitDefinition(Destructor); 13443 } 13444 } 13445 13446 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 13447 CXXDestructorDecl *Destructor) { 13448 if (Destructor->isInvalidDecl()) 13449 return; 13450 13451 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13452 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() && 13453 "implicit complete dtors unneeded outside MS ABI"); 13454 assert(ClassDecl->getNumVBases() > 0 && 13455 "complete dtor only exists for classes with vbases"); 13456 13457 SynthesizedFunctionScope Scope(*this, Destructor); 13458 13459 // Add a context note for diagnostics produced after this point. 13460 Scope.addContextNote(CurrentLocation); 13461 13462 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl); 13463 } 13464 13465 /// Perform any semantic analysis which needs to be delayed until all 13466 /// pending class member declarations have been parsed. 13467 void Sema::ActOnFinishCXXMemberDecls() { 13468 // If the context is an invalid C++ class, just suppress these checks. 13469 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 13470 if (Record->isInvalidDecl()) { 13471 DelayedOverridingExceptionSpecChecks.clear(); 13472 DelayedEquivalentExceptionSpecChecks.clear(); 13473 return; 13474 } 13475 checkForMultipleExportedDefaultConstructors(*this, Record); 13476 } 13477 } 13478 13479 void Sema::ActOnFinishCXXNonNestedClass() { 13480 referenceDLLExportedClassMethods(); 13481 13482 if (!DelayedDllExportMemberFunctions.empty()) { 13483 SmallVector<CXXMethodDecl*, 4> WorkList; 13484 std::swap(DelayedDllExportMemberFunctions, WorkList); 13485 for (CXXMethodDecl *M : WorkList) { 13486 DefineDefaultedFunction(*this, M, M->getLocation()); 13487 13488 // Pass the method to the consumer to get emitted. This is not necessary 13489 // for explicit instantiation definitions, as they will get emitted 13490 // anyway. 13491 if (M->getParent()->getTemplateSpecializationKind() != 13492 TSK_ExplicitInstantiationDefinition) 13493 ActOnFinishInlineFunctionDef(M); 13494 } 13495 } 13496 } 13497 13498 void Sema::referenceDLLExportedClassMethods() { 13499 if (!DelayedDllExportClasses.empty()) { 13500 // Calling ReferenceDllExportedMembers might cause the current function to 13501 // be called again, so use a local copy of DelayedDllExportClasses. 13502 SmallVector<CXXRecordDecl *, 4> WorkList; 13503 std::swap(DelayedDllExportClasses, WorkList); 13504 for (CXXRecordDecl *Class : WorkList) 13505 ReferenceDllExportedMembers(*this, Class); 13506 } 13507 } 13508 13509 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 13510 assert(getLangOpts().CPlusPlus11 && 13511 "adjusting dtor exception specs was introduced in c++11"); 13512 13513 if (Destructor->isDependentContext()) 13514 return; 13515 13516 // C++11 [class.dtor]p3: 13517 // A declaration of a destructor that does not have an exception- 13518 // specification is implicitly considered to have the same exception- 13519 // specification as an implicit declaration. 13520 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); 13521 if (DtorType->hasExceptionSpec()) 13522 return; 13523 13524 // Replace the destructor's type, building off the existing one. Fortunately, 13525 // the only thing of interest in the destructor type is its extended info. 13526 // The return and arguments are fixed. 13527 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 13528 EPI.ExceptionSpec.Type = EST_Unevaluated; 13529 EPI.ExceptionSpec.SourceDecl = Destructor; 13530 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 13531 13532 // FIXME: If the destructor has a body that could throw, and the newly created 13533 // spec doesn't allow exceptions, we should emit a warning, because this 13534 // change in behavior can break conforming C++03 programs at runtime. 13535 // However, we don't have a body or an exception specification yet, so it 13536 // needs to be done somewhere else. 13537 } 13538 13539 namespace { 13540 /// An abstract base class for all helper classes used in building the 13541 // copy/move operators. These classes serve as factory functions and help us 13542 // avoid using the same Expr* in the AST twice. 13543 class ExprBuilder { 13544 ExprBuilder(const ExprBuilder&) = delete; 13545 ExprBuilder &operator=(const ExprBuilder&) = delete; 13546 13547 protected: 13548 static Expr *assertNotNull(Expr *E) { 13549 assert(E && "Expression construction must not fail."); 13550 return E; 13551 } 13552 13553 public: 13554 ExprBuilder() {} 13555 virtual ~ExprBuilder() {} 13556 13557 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 13558 }; 13559 13560 class RefBuilder: public ExprBuilder { 13561 VarDecl *Var; 13562 QualType VarType; 13563 13564 public: 13565 Expr *build(Sema &S, SourceLocation Loc) const override { 13566 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 13567 } 13568 13569 RefBuilder(VarDecl *Var, QualType VarType) 13570 : Var(Var), VarType(VarType) {} 13571 }; 13572 13573 class ThisBuilder: public ExprBuilder { 13574 public: 13575 Expr *build(Sema &S, SourceLocation Loc) const override { 13576 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 13577 } 13578 }; 13579 13580 class CastBuilder: public ExprBuilder { 13581 const ExprBuilder &Builder; 13582 QualType Type; 13583 ExprValueKind Kind; 13584 const CXXCastPath &Path; 13585 13586 public: 13587 Expr *build(Sema &S, SourceLocation Loc) const override { 13588 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 13589 CK_UncheckedDerivedToBase, Kind, 13590 &Path).get()); 13591 } 13592 13593 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 13594 const CXXCastPath &Path) 13595 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 13596 }; 13597 13598 class DerefBuilder: public ExprBuilder { 13599 const ExprBuilder &Builder; 13600 13601 public: 13602 Expr *build(Sema &S, SourceLocation Loc) const override { 13603 return assertNotNull( 13604 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 13605 } 13606 13607 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13608 }; 13609 13610 class MemberBuilder: public ExprBuilder { 13611 const ExprBuilder &Builder; 13612 QualType Type; 13613 CXXScopeSpec SS; 13614 bool IsArrow; 13615 LookupResult &MemberLookup; 13616 13617 public: 13618 Expr *build(Sema &S, SourceLocation Loc) const override { 13619 return assertNotNull(S.BuildMemberReferenceExpr( 13620 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 13621 nullptr, MemberLookup, nullptr, nullptr).get()); 13622 } 13623 13624 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 13625 LookupResult &MemberLookup) 13626 : Builder(Builder), Type(Type), IsArrow(IsArrow), 13627 MemberLookup(MemberLookup) {} 13628 }; 13629 13630 class MoveCastBuilder: public ExprBuilder { 13631 const ExprBuilder &Builder; 13632 13633 public: 13634 Expr *build(Sema &S, SourceLocation Loc) const override { 13635 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 13636 } 13637 13638 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13639 }; 13640 13641 class LvalueConvBuilder: public ExprBuilder { 13642 const ExprBuilder &Builder; 13643 13644 public: 13645 Expr *build(Sema &S, SourceLocation Loc) const override { 13646 return assertNotNull( 13647 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 13648 } 13649 13650 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13651 }; 13652 13653 class SubscriptBuilder: public ExprBuilder { 13654 const ExprBuilder &Base; 13655 const ExprBuilder &Index; 13656 13657 public: 13658 Expr *build(Sema &S, SourceLocation Loc) const override { 13659 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 13660 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 13661 } 13662 13663 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 13664 : Base(Base), Index(Index) {} 13665 }; 13666 13667 } // end anonymous namespace 13668 13669 /// When generating a defaulted copy or move assignment operator, if a field 13670 /// should be copied with __builtin_memcpy rather than via explicit assignments, 13671 /// do so. This optimization only applies for arrays of scalars, and for arrays 13672 /// of class type where the selected copy/move-assignment operator is trivial. 13673 static StmtResult 13674 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 13675 const ExprBuilder &ToB, const ExprBuilder &FromB) { 13676 // Compute the size of the memory buffer to be copied. 13677 QualType SizeType = S.Context.getSizeType(); 13678 llvm::APInt Size(S.Context.getTypeSize(SizeType), 13679 S.Context.getTypeSizeInChars(T).getQuantity()); 13680 13681 // Take the address of the field references for "from" and "to". We 13682 // directly construct UnaryOperators here because semantic analysis 13683 // does not permit us to take the address of an xvalue. 13684 Expr *From = FromB.build(S, Loc); 13685 From = UnaryOperator::Create( 13686 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()), 13687 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13688 Expr *To = ToB.build(S, Loc); 13689 To = UnaryOperator::Create( 13690 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()), 13691 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13692 13693 const Type *E = T->getBaseElementTypeUnsafe(); 13694 bool NeedsCollectableMemCpy = 13695 E->isRecordType() && 13696 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 13697 13698 // Create a reference to the __builtin_objc_memmove_collectable function 13699 StringRef MemCpyName = NeedsCollectableMemCpy ? 13700 "__builtin_objc_memmove_collectable" : 13701 "__builtin_memcpy"; 13702 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 13703 Sema::LookupOrdinaryName); 13704 S.LookupName(R, S.TUScope, true); 13705 13706 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 13707 if (!MemCpy) 13708 // Something went horribly wrong earlier, and we will have complained 13709 // about it. 13710 return StmtError(); 13711 13712 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 13713 VK_RValue, Loc, nullptr); 13714 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 13715 13716 Expr *CallArgs[] = { 13717 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 13718 }; 13719 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 13720 Loc, CallArgs, Loc); 13721 13722 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 13723 return Call.getAs<Stmt>(); 13724 } 13725 13726 /// Builds a statement that copies/moves the given entity from \p From to 13727 /// \c To. 13728 /// 13729 /// This routine is used to copy/move the members of a class with an 13730 /// implicitly-declared copy/move assignment operator. When the entities being 13731 /// copied are arrays, this routine builds for loops to copy them. 13732 /// 13733 /// \param S The Sema object used for type-checking. 13734 /// 13735 /// \param Loc The location where the implicit copy/move is being generated. 13736 /// 13737 /// \param T The type of the expressions being copied/moved. Both expressions 13738 /// must have this type. 13739 /// 13740 /// \param To The expression we are copying/moving to. 13741 /// 13742 /// \param From The expression we are copying/moving from. 13743 /// 13744 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 13745 /// Otherwise, it's a non-static member subobject. 13746 /// 13747 /// \param Copying Whether we're copying or moving. 13748 /// 13749 /// \param Depth Internal parameter recording the depth of the recursion. 13750 /// 13751 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 13752 /// if a memcpy should be used instead. 13753 static StmtResult 13754 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 13755 const ExprBuilder &To, const ExprBuilder &From, 13756 bool CopyingBaseSubobject, bool Copying, 13757 unsigned Depth = 0) { 13758 // C++11 [class.copy]p28: 13759 // Each subobject is assigned in the manner appropriate to its type: 13760 // 13761 // - if the subobject is of class type, as if by a call to operator= with 13762 // the subobject as the object expression and the corresponding 13763 // subobject of x as a single function argument (as if by explicit 13764 // qualification; that is, ignoring any possible virtual overriding 13765 // functions in more derived classes); 13766 // 13767 // C++03 [class.copy]p13: 13768 // - if the subobject is of class type, the copy assignment operator for 13769 // the class is used (as if by explicit qualification; that is, 13770 // ignoring any possible virtual overriding functions in more derived 13771 // classes); 13772 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 13773 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 13774 13775 // Look for operator=. 13776 DeclarationName Name 13777 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13778 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 13779 S.LookupQualifiedName(OpLookup, ClassDecl, false); 13780 13781 // Prior to C++11, filter out any result that isn't a copy/move-assignment 13782 // operator. 13783 if (!S.getLangOpts().CPlusPlus11) { 13784 LookupResult::Filter F = OpLookup.makeFilter(); 13785 while (F.hasNext()) { 13786 NamedDecl *D = F.next(); 13787 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 13788 if (Method->isCopyAssignmentOperator() || 13789 (!Copying && Method->isMoveAssignmentOperator())) 13790 continue; 13791 13792 F.erase(); 13793 } 13794 F.done(); 13795 } 13796 13797 // Suppress the protected check (C++ [class.protected]) for each of the 13798 // assignment operators we found. This strange dance is required when 13799 // we're assigning via a base classes's copy-assignment operator. To 13800 // ensure that we're getting the right base class subobject (without 13801 // ambiguities), we need to cast "this" to that subobject type; to 13802 // ensure that we don't go through the virtual call mechanism, we need 13803 // to qualify the operator= name with the base class (see below). However, 13804 // this means that if the base class has a protected copy assignment 13805 // operator, the protected member access check will fail. So, we 13806 // rewrite "protected" access to "public" access in this case, since we 13807 // know by construction that we're calling from a derived class. 13808 if (CopyingBaseSubobject) { 13809 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 13810 L != LEnd; ++L) { 13811 if (L.getAccess() == AS_protected) 13812 L.setAccess(AS_public); 13813 } 13814 } 13815 13816 // Create the nested-name-specifier that will be used to qualify the 13817 // reference to operator=; this is required to suppress the virtual 13818 // call mechanism. 13819 CXXScopeSpec SS; 13820 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 13821 SS.MakeTrivial(S.Context, 13822 NestedNameSpecifier::Create(S.Context, nullptr, false, 13823 CanonicalT), 13824 Loc); 13825 13826 // Create the reference to operator=. 13827 ExprResult OpEqualRef 13828 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 13829 SS, /*TemplateKWLoc=*/SourceLocation(), 13830 /*FirstQualifierInScope=*/nullptr, 13831 OpLookup, 13832 /*TemplateArgs=*/nullptr, /*S*/nullptr, 13833 /*SuppressQualifierCheck=*/true); 13834 if (OpEqualRef.isInvalid()) 13835 return StmtError(); 13836 13837 // Build the call to the assignment operator. 13838 13839 Expr *FromInst = From.build(S, Loc); 13840 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 13841 OpEqualRef.getAs<Expr>(), 13842 Loc, FromInst, Loc); 13843 if (Call.isInvalid()) 13844 return StmtError(); 13845 13846 // If we built a call to a trivial 'operator=' while copying an array, 13847 // bail out. We'll replace the whole shebang with a memcpy. 13848 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 13849 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 13850 return StmtResult((Stmt*)nullptr); 13851 13852 // Convert to an expression-statement, and clean up any produced 13853 // temporaries. 13854 return S.ActOnExprStmt(Call); 13855 } 13856 13857 // - if the subobject is of scalar type, the built-in assignment 13858 // operator is used. 13859 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 13860 if (!ArrayTy) { 13861 ExprResult Assignment = S.CreateBuiltinBinOp( 13862 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 13863 if (Assignment.isInvalid()) 13864 return StmtError(); 13865 return S.ActOnExprStmt(Assignment); 13866 } 13867 13868 // - if the subobject is an array, each element is assigned, in the 13869 // manner appropriate to the element type; 13870 13871 // Construct a loop over the array bounds, e.g., 13872 // 13873 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 13874 // 13875 // that will copy each of the array elements. 13876 QualType SizeType = S.Context.getSizeType(); 13877 13878 // Create the iteration variable. 13879 IdentifierInfo *IterationVarName = nullptr; 13880 { 13881 SmallString<8> Str; 13882 llvm::raw_svector_ostream OS(Str); 13883 OS << "__i" << Depth; 13884 IterationVarName = &S.Context.Idents.get(OS.str()); 13885 } 13886 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 13887 IterationVarName, SizeType, 13888 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 13889 SC_None); 13890 13891 // Initialize the iteration variable to zero. 13892 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 13893 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 13894 13895 // Creates a reference to the iteration variable. 13896 RefBuilder IterationVarRef(IterationVar, SizeType); 13897 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 13898 13899 // Create the DeclStmt that holds the iteration variable. 13900 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 13901 13902 // Subscript the "from" and "to" expressions with the iteration variable. 13903 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 13904 MoveCastBuilder FromIndexMove(FromIndexCopy); 13905 const ExprBuilder *FromIndex; 13906 if (Copying) 13907 FromIndex = &FromIndexCopy; 13908 else 13909 FromIndex = &FromIndexMove; 13910 13911 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 13912 13913 // Build the copy/move for an individual element of the array. 13914 StmtResult Copy = 13915 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 13916 ToIndex, *FromIndex, CopyingBaseSubobject, 13917 Copying, Depth + 1); 13918 // Bail out if copying fails or if we determined that we should use memcpy. 13919 if (Copy.isInvalid() || !Copy.get()) 13920 return Copy; 13921 13922 // Create the comparison against the array bound. 13923 llvm::APInt Upper 13924 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 13925 Expr *Comparison = BinaryOperator::Create( 13926 S.Context, IterationVarRefRVal.build(S, Loc), 13927 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE, 13928 S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides()); 13929 13930 // Create the pre-increment of the iteration variable. We can determine 13931 // whether the increment will overflow based on the value of the array 13932 // bound. 13933 Expr *Increment = UnaryOperator::Create( 13934 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue, 13935 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides()); 13936 13937 // Construct the loop that copies all elements of this array. 13938 return S.ActOnForStmt( 13939 Loc, Loc, InitStmt, 13940 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 13941 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 13942 } 13943 13944 static StmtResult 13945 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 13946 const ExprBuilder &To, const ExprBuilder &From, 13947 bool CopyingBaseSubobject, bool Copying) { 13948 // Maybe we should use a memcpy? 13949 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 13950 T.isTriviallyCopyableType(S.Context)) 13951 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13952 13953 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 13954 CopyingBaseSubobject, 13955 Copying, 0)); 13956 13957 // If we ended up picking a trivial assignment operator for an array of a 13958 // non-trivially-copyable class type, just emit a memcpy. 13959 if (!Result.isInvalid() && !Result.get()) 13960 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13961 13962 return Result; 13963 } 13964 13965 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 13966 // Note: The following rules are largely analoguous to the copy 13967 // constructor rules. Note that virtual bases are not taken into account 13968 // for determining the argument type of the operator. Note also that 13969 // operators taking an object instead of a reference are allowed. 13970 assert(ClassDecl->needsImplicitCopyAssignment()); 13971 13972 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 13973 if (DSM.isAlreadyBeingDeclared()) 13974 return nullptr; 13975 13976 QualType ArgType = Context.getTypeDeclType(ClassDecl); 13977 LangAS AS = getDefaultCXXMethodAddrSpace(); 13978 if (AS != LangAS::Default) 13979 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 13980 QualType RetType = Context.getLValueReferenceType(ArgType); 13981 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 13982 if (Const) 13983 ArgType = ArgType.withConst(); 13984 13985 ArgType = Context.getLValueReferenceType(ArgType); 13986 13987 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13988 CXXCopyAssignment, 13989 Const); 13990 13991 // An implicitly-declared copy assignment operator is an inline public 13992 // member of its class. 13993 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13994 SourceLocation ClassLoc = ClassDecl->getLocation(); 13995 DeclarationNameInfo NameInfo(Name, ClassLoc); 13996 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 13997 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 13998 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 13999 /*isInline=*/true, 14000 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14001 SourceLocation()); 14002 CopyAssignment->setAccess(AS_public); 14003 CopyAssignment->setDefaulted(); 14004 CopyAssignment->setImplicit(); 14005 14006 if (getLangOpts().CUDA) { 14007 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 14008 CopyAssignment, 14009 /* ConstRHS */ Const, 14010 /* Diagnose */ false); 14011 } 14012 14013 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 14014 14015 // Add the parameter to the operator. 14016 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 14017 ClassLoc, ClassLoc, 14018 /*Id=*/nullptr, ArgType, 14019 /*TInfo=*/nullptr, SC_None, 14020 nullptr); 14021 CopyAssignment->setParams(FromParam); 14022 14023 CopyAssignment->setTrivial( 14024 ClassDecl->needsOverloadResolutionForCopyAssignment() 14025 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 14026 : ClassDecl->hasTrivialCopyAssignment()); 14027 14028 // Note that we have added this copy-assignment operator. 14029 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 14030 14031 Scope *S = getScopeForContext(ClassDecl); 14032 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 14033 14034 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) { 14035 ClassDecl->setImplicitCopyAssignmentIsDeleted(); 14036 SetDeclDeleted(CopyAssignment, ClassLoc); 14037 } 14038 14039 if (S) 14040 PushOnScopeChains(CopyAssignment, S, false); 14041 ClassDecl->addDecl(CopyAssignment); 14042 14043 return CopyAssignment; 14044 } 14045 14046 /// Diagnose an implicit copy operation for a class which is odr-used, but 14047 /// which is deprecated because the class has a user-declared copy constructor, 14048 /// copy assignment operator, or destructor. 14049 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 14050 assert(CopyOp->isImplicit()); 14051 14052 CXXRecordDecl *RD = CopyOp->getParent(); 14053 CXXMethodDecl *UserDeclaredOperation = nullptr; 14054 14055 // In Microsoft mode, assignment operations don't affect constructors and 14056 // vice versa. 14057 if (RD->hasUserDeclaredDestructor()) { 14058 UserDeclaredOperation = RD->getDestructor(); 14059 } else if (!isa<CXXConstructorDecl>(CopyOp) && 14060 RD->hasUserDeclaredCopyConstructor() && 14061 !S.getLangOpts().MSVCCompat) { 14062 // Find any user-declared copy constructor. 14063 for (auto *I : RD->ctors()) { 14064 if (I->isCopyConstructor()) { 14065 UserDeclaredOperation = I; 14066 break; 14067 } 14068 } 14069 assert(UserDeclaredOperation); 14070 } else if (isa<CXXConstructorDecl>(CopyOp) && 14071 RD->hasUserDeclaredCopyAssignment() && 14072 !S.getLangOpts().MSVCCompat) { 14073 // Find any user-declared move assignment operator. 14074 for (auto *I : RD->methods()) { 14075 if (I->isCopyAssignmentOperator()) { 14076 UserDeclaredOperation = I; 14077 break; 14078 } 14079 } 14080 assert(UserDeclaredOperation); 14081 } 14082 14083 if (UserDeclaredOperation) { 14084 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided(); 14085 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation); 14086 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp); 14087 unsigned DiagID = 14088 (UDOIsUserProvided && UDOIsDestructor) 14089 ? diag::warn_deprecated_copy_with_user_provided_dtor 14090 : (UDOIsUserProvided && !UDOIsDestructor) 14091 ? diag::warn_deprecated_copy_with_user_provided_copy 14092 : (!UDOIsUserProvided && UDOIsDestructor) 14093 ? diag::warn_deprecated_copy_with_dtor 14094 : diag::warn_deprecated_copy; 14095 S.Diag(UserDeclaredOperation->getLocation(), DiagID) 14096 << RD << IsCopyAssignment; 14097 } 14098 } 14099 14100 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 14101 CXXMethodDecl *CopyAssignOperator) { 14102 assert((CopyAssignOperator->isDefaulted() && 14103 CopyAssignOperator->isOverloadedOperator() && 14104 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 14105 !CopyAssignOperator->doesThisDeclarationHaveABody() && 14106 !CopyAssignOperator->isDeleted()) && 14107 "DefineImplicitCopyAssignment called for wrong function"); 14108 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 14109 return; 14110 14111 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 14112 if (ClassDecl->isInvalidDecl()) { 14113 CopyAssignOperator->setInvalidDecl(); 14114 return; 14115 } 14116 14117 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 14118 14119 // The exception specification is needed because we are defining the 14120 // function. 14121 ResolveExceptionSpec(CurrentLocation, 14122 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 14123 14124 // Add a context note for diagnostics produced after this point. 14125 Scope.addContextNote(CurrentLocation); 14126 14127 // C++11 [class.copy]p18: 14128 // The [definition of an implicitly declared copy assignment operator] is 14129 // deprecated if the class has a user-declared copy constructor or a 14130 // user-declared destructor. 14131 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 14132 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 14133 14134 // C++0x [class.copy]p30: 14135 // The implicitly-defined or explicitly-defaulted copy assignment operator 14136 // for a non-union class X performs memberwise copy assignment of its 14137 // subobjects. The direct base classes of X are assigned first, in the 14138 // order of their declaration in the base-specifier-list, and then the 14139 // immediate non-static data members of X are assigned, in the order in 14140 // which they were declared in the class definition. 14141 14142 // The statements that form the synthesized function body. 14143 SmallVector<Stmt*, 8> Statements; 14144 14145 // The parameter for the "other" object, which we are copying from. 14146 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 14147 Qualifiers OtherQuals = Other->getType().getQualifiers(); 14148 QualType OtherRefType = Other->getType(); 14149 if (const LValueReferenceType *OtherRef 14150 = OtherRefType->getAs<LValueReferenceType>()) { 14151 OtherRefType = OtherRef->getPointeeType(); 14152 OtherQuals = OtherRefType.getQualifiers(); 14153 } 14154 14155 // Our location for everything implicitly-generated. 14156 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 14157 ? CopyAssignOperator->getEndLoc() 14158 : CopyAssignOperator->getLocation(); 14159 14160 // Builds a DeclRefExpr for the "other" object. 14161 RefBuilder OtherRef(Other, OtherRefType); 14162 14163 // Builds the "this" pointer. 14164 ThisBuilder This; 14165 14166 // Assign base classes. 14167 bool Invalid = false; 14168 for (auto &Base : ClassDecl->bases()) { 14169 // Form the assignment: 14170 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 14171 QualType BaseType = Base.getType().getUnqualifiedType(); 14172 if (!BaseType->isRecordType()) { 14173 Invalid = true; 14174 continue; 14175 } 14176 14177 CXXCastPath BasePath; 14178 BasePath.push_back(&Base); 14179 14180 // Construct the "from" expression, which is an implicit cast to the 14181 // appropriately-qualified base type. 14182 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 14183 VK_LValue, BasePath); 14184 14185 // Dereference "this". 14186 DerefBuilder DerefThis(This); 14187 CastBuilder To(DerefThis, 14188 Context.getQualifiedType( 14189 BaseType, CopyAssignOperator->getMethodQualifiers()), 14190 VK_LValue, BasePath); 14191 14192 // Build the copy. 14193 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 14194 To, From, 14195 /*CopyingBaseSubobject=*/true, 14196 /*Copying=*/true); 14197 if (Copy.isInvalid()) { 14198 CopyAssignOperator->setInvalidDecl(); 14199 return; 14200 } 14201 14202 // Success! Record the copy. 14203 Statements.push_back(Copy.getAs<Expr>()); 14204 } 14205 14206 // Assign non-static members. 14207 for (auto *Field : ClassDecl->fields()) { 14208 // FIXME: We should form some kind of AST representation for the implied 14209 // memcpy in a union copy operation. 14210 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14211 continue; 14212 14213 if (Field->isInvalidDecl()) { 14214 Invalid = true; 14215 continue; 14216 } 14217 14218 // Check for members of reference type; we can't copy those. 14219 if (Field->getType()->isReferenceType()) { 14220 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14221 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14222 Diag(Field->getLocation(), diag::note_declared_at); 14223 Invalid = true; 14224 continue; 14225 } 14226 14227 // Check for members of const-qualified, non-class type. 14228 QualType BaseType = Context.getBaseElementType(Field->getType()); 14229 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14230 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14231 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14232 Diag(Field->getLocation(), diag::note_declared_at); 14233 Invalid = true; 14234 continue; 14235 } 14236 14237 // Suppress assigning zero-width bitfields. 14238 if (Field->isZeroLengthBitField(Context)) 14239 continue; 14240 14241 QualType FieldType = Field->getType().getNonReferenceType(); 14242 if (FieldType->isIncompleteArrayType()) { 14243 assert(ClassDecl->hasFlexibleArrayMember() && 14244 "Incomplete array type is not valid"); 14245 continue; 14246 } 14247 14248 // Build references to the field in the object we're copying from and to. 14249 CXXScopeSpec SS; // Intentionally empty 14250 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14251 LookupMemberName); 14252 MemberLookup.addDecl(Field); 14253 MemberLookup.resolveKind(); 14254 14255 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 14256 14257 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 14258 14259 // Build the copy of this field. 14260 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 14261 To, From, 14262 /*CopyingBaseSubobject=*/false, 14263 /*Copying=*/true); 14264 if (Copy.isInvalid()) { 14265 CopyAssignOperator->setInvalidDecl(); 14266 return; 14267 } 14268 14269 // Success! Record the copy. 14270 Statements.push_back(Copy.getAs<Stmt>()); 14271 } 14272 14273 if (!Invalid) { 14274 // Add a "return *this;" 14275 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14276 14277 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14278 if (Return.isInvalid()) 14279 Invalid = true; 14280 else 14281 Statements.push_back(Return.getAs<Stmt>()); 14282 } 14283 14284 if (Invalid) { 14285 CopyAssignOperator->setInvalidDecl(); 14286 return; 14287 } 14288 14289 StmtResult Body; 14290 { 14291 CompoundScopeRAII CompoundScope(*this); 14292 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14293 /*isStmtExpr=*/false); 14294 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14295 } 14296 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 14297 CopyAssignOperator->markUsed(Context); 14298 14299 if (ASTMutationListener *L = getASTMutationListener()) { 14300 L->CompletedImplicitDefinition(CopyAssignOperator); 14301 } 14302 } 14303 14304 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 14305 assert(ClassDecl->needsImplicitMoveAssignment()); 14306 14307 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 14308 if (DSM.isAlreadyBeingDeclared()) 14309 return nullptr; 14310 14311 // Note: The following rules are largely analoguous to the move 14312 // constructor rules. 14313 14314 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14315 LangAS AS = getDefaultCXXMethodAddrSpace(); 14316 if (AS != LangAS::Default) 14317 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14318 QualType RetType = Context.getLValueReferenceType(ArgType); 14319 ArgType = Context.getRValueReferenceType(ArgType); 14320 14321 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14322 CXXMoveAssignment, 14323 false); 14324 14325 // An implicitly-declared move assignment operator is an inline public 14326 // member of its class. 14327 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14328 SourceLocation ClassLoc = ClassDecl->getLocation(); 14329 DeclarationNameInfo NameInfo(Name, ClassLoc); 14330 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 14331 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14332 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14333 /*isInline=*/true, 14334 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14335 SourceLocation()); 14336 MoveAssignment->setAccess(AS_public); 14337 MoveAssignment->setDefaulted(); 14338 MoveAssignment->setImplicit(); 14339 14340 if (getLangOpts().CUDA) { 14341 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 14342 MoveAssignment, 14343 /* ConstRHS */ false, 14344 /* Diagnose */ false); 14345 } 14346 14347 // Build an exception specification pointing back at this member. 14348 FunctionProtoType::ExtProtoInfo EPI = 14349 getImplicitMethodEPI(*this, MoveAssignment); 14350 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 14351 14352 // Add the parameter to the operator. 14353 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 14354 ClassLoc, ClassLoc, 14355 /*Id=*/nullptr, ArgType, 14356 /*TInfo=*/nullptr, SC_None, 14357 nullptr); 14358 MoveAssignment->setParams(FromParam); 14359 14360 MoveAssignment->setTrivial( 14361 ClassDecl->needsOverloadResolutionForMoveAssignment() 14362 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 14363 : ClassDecl->hasTrivialMoveAssignment()); 14364 14365 // Note that we have added this copy-assignment operator. 14366 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 14367 14368 Scope *S = getScopeForContext(ClassDecl); 14369 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 14370 14371 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 14372 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 14373 SetDeclDeleted(MoveAssignment, ClassLoc); 14374 } 14375 14376 if (S) 14377 PushOnScopeChains(MoveAssignment, S, false); 14378 ClassDecl->addDecl(MoveAssignment); 14379 14380 return MoveAssignment; 14381 } 14382 14383 /// Check if we're implicitly defining a move assignment operator for a class 14384 /// with virtual bases. Such a move assignment might move-assign the virtual 14385 /// base multiple times. 14386 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 14387 SourceLocation CurrentLocation) { 14388 assert(!Class->isDependentContext() && "should not define dependent move"); 14389 14390 // Only a virtual base could get implicitly move-assigned multiple times. 14391 // Only a non-trivial move assignment can observe this. We only want to 14392 // diagnose if we implicitly define an assignment operator that assigns 14393 // two base classes, both of which move-assign the same virtual base. 14394 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 14395 Class->getNumBases() < 2) 14396 return; 14397 14398 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 14399 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 14400 VBaseMap VBases; 14401 14402 for (auto &BI : Class->bases()) { 14403 Worklist.push_back(&BI); 14404 while (!Worklist.empty()) { 14405 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 14406 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 14407 14408 // If the base has no non-trivial move assignment operators, 14409 // we don't care about moves from it. 14410 if (!Base->hasNonTrivialMoveAssignment()) 14411 continue; 14412 14413 // If there's nothing virtual here, skip it. 14414 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 14415 continue; 14416 14417 // If we're not actually going to call a move assignment for this base, 14418 // or the selected move assignment is trivial, skip it. 14419 Sema::SpecialMemberOverloadResult SMOR = 14420 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 14421 /*ConstArg*/false, /*VolatileArg*/false, 14422 /*RValueThis*/true, /*ConstThis*/false, 14423 /*VolatileThis*/false); 14424 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 14425 !SMOR.getMethod()->isMoveAssignmentOperator()) 14426 continue; 14427 14428 if (BaseSpec->isVirtual()) { 14429 // We're going to move-assign this virtual base, and its move 14430 // assignment operator is not trivial. If this can happen for 14431 // multiple distinct direct bases of Class, diagnose it. (If it 14432 // only happens in one base, we'll diagnose it when synthesizing 14433 // that base class's move assignment operator.) 14434 CXXBaseSpecifier *&Existing = 14435 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 14436 .first->second; 14437 if (Existing && Existing != &BI) { 14438 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 14439 << Class << Base; 14440 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 14441 << (Base->getCanonicalDecl() == 14442 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14443 << Base << Existing->getType() << Existing->getSourceRange(); 14444 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 14445 << (Base->getCanonicalDecl() == 14446 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14447 << Base << BI.getType() << BaseSpec->getSourceRange(); 14448 14449 // Only diagnose each vbase once. 14450 Existing = nullptr; 14451 } 14452 } else { 14453 // Only walk over bases that have defaulted move assignment operators. 14454 // We assume that any user-provided move assignment operator handles 14455 // the multiple-moves-of-vbase case itself somehow. 14456 if (!SMOR.getMethod()->isDefaulted()) 14457 continue; 14458 14459 // We're going to move the base classes of Base. Add them to the list. 14460 for (auto &BI : Base->bases()) 14461 Worklist.push_back(&BI); 14462 } 14463 } 14464 } 14465 } 14466 14467 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 14468 CXXMethodDecl *MoveAssignOperator) { 14469 assert((MoveAssignOperator->isDefaulted() && 14470 MoveAssignOperator->isOverloadedOperator() && 14471 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 14472 !MoveAssignOperator->doesThisDeclarationHaveABody() && 14473 !MoveAssignOperator->isDeleted()) && 14474 "DefineImplicitMoveAssignment called for wrong function"); 14475 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 14476 return; 14477 14478 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 14479 if (ClassDecl->isInvalidDecl()) { 14480 MoveAssignOperator->setInvalidDecl(); 14481 return; 14482 } 14483 14484 // C++0x [class.copy]p28: 14485 // The implicitly-defined or move assignment operator for a non-union class 14486 // X performs memberwise move assignment of its subobjects. The direct base 14487 // classes of X are assigned first, in the order of their declaration in the 14488 // base-specifier-list, and then the immediate non-static data members of X 14489 // are assigned, in the order in which they were declared in the class 14490 // definition. 14491 14492 // Issue a warning if our implicit move assignment operator will move 14493 // from a virtual base more than once. 14494 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 14495 14496 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 14497 14498 // The exception specification is needed because we are defining the 14499 // function. 14500 ResolveExceptionSpec(CurrentLocation, 14501 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 14502 14503 // Add a context note for diagnostics produced after this point. 14504 Scope.addContextNote(CurrentLocation); 14505 14506 // The statements that form the synthesized function body. 14507 SmallVector<Stmt*, 8> Statements; 14508 14509 // The parameter for the "other" object, which we are move from. 14510 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 14511 QualType OtherRefType = 14512 Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); 14513 14514 // Our location for everything implicitly-generated. 14515 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 14516 ? MoveAssignOperator->getEndLoc() 14517 : MoveAssignOperator->getLocation(); 14518 14519 // Builds a reference to the "other" object. 14520 RefBuilder OtherRef(Other, OtherRefType); 14521 // Cast to rvalue. 14522 MoveCastBuilder MoveOther(OtherRef); 14523 14524 // Builds the "this" pointer. 14525 ThisBuilder This; 14526 14527 // Assign base classes. 14528 bool Invalid = false; 14529 for (auto &Base : ClassDecl->bases()) { 14530 // C++11 [class.copy]p28: 14531 // It is unspecified whether subobjects representing virtual base classes 14532 // are assigned more than once by the implicitly-defined copy assignment 14533 // operator. 14534 // FIXME: Do not assign to a vbase that will be assigned by some other base 14535 // class. For a move-assignment, this can result in the vbase being moved 14536 // multiple times. 14537 14538 // Form the assignment: 14539 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 14540 QualType BaseType = Base.getType().getUnqualifiedType(); 14541 if (!BaseType->isRecordType()) { 14542 Invalid = true; 14543 continue; 14544 } 14545 14546 CXXCastPath BasePath; 14547 BasePath.push_back(&Base); 14548 14549 // Construct the "from" expression, which is an implicit cast to the 14550 // appropriately-qualified base type. 14551 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 14552 14553 // Dereference "this". 14554 DerefBuilder DerefThis(This); 14555 14556 // Implicitly cast "this" to the appropriately-qualified base type. 14557 CastBuilder To(DerefThis, 14558 Context.getQualifiedType( 14559 BaseType, MoveAssignOperator->getMethodQualifiers()), 14560 VK_LValue, BasePath); 14561 14562 // Build the move. 14563 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 14564 To, From, 14565 /*CopyingBaseSubobject=*/true, 14566 /*Copying=*/false); 14567 if (Move.isInvalid()) { 14568 MoveAssignOperator->setInvalidDecl(); 14569 return; 14570 } 14571 14572 // Success! Record the move. 14573 Statements.push_back(Move.getAs<Expr>()); 14574 } 14575 14576 // Assign non-static members. 14577 for (auto *Field : ClassDecl->fields()) { 14578 // FIXME: We should form some kind of AST representation for the implied 14579 // memcpy in a union copy operation. 14580 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14581 continue; 14582 14583 if (Field->isInvalidDecl()) { 14584 Invalid = true; 14585 continue; 14586 } 14587 14588 // Check for members of reference type; we can't move those. 14589 if (Field->getType()->isReferenceType()) { 14590 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14591 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14592 Diag(Field->getLocation(), diag::note_declared_at); 14593 Invalid = true; 14594 continue; 14595 } 14596 14597 // Check for members of const-qualified, non-class type. 14598 QualType BaseType = Context.getBaseElementType(Field->getType()); 14599 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14600 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14601 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14602 Diag(Field->getLocation(), diag::note_declared_at); 14603 Invalid = true; 14604 continue; 14605 } 14606 14607 // Suppress assigning zero-width bitfields. 14608 if (Field->isZeroLengthBitField(Context)) 14609 continue; 14610 14611 QualType FieldType = Field->getType().getNonReferenceType(); 14612 if (FieldType->isIncompleteArrayType()) { 14613 assert(ClassDecl->hasFlexibleArrayMember() && 14614 "Incomplete array type is not valid"); 14615 continue; 14616 } 14617 14618 // Build references to the field in the object we're copying from and to. 14619 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14620 LookupMemberName); 14621 MemberLookup.addDecl(Field); 14622 MemberLookup.resolveKind(); 14623 MemberBuilder From(MoveOther, OtherRefType, 14624 /*IsArrow=*/false, MemberLookup); 14625 MemberBuilder To(This, getCurrentThisType(), 14626 /*IsArrow=*/true, MemberLookup); 14627 14628 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 14629 "Member reference with rvalue base must be rvalue except for reference " 14630 "members, which aren't allowed for move assignment."); 14631 14632 // Build the move of this field. 14633 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 14634 To, From, 14635 /*CopyingBaseSubobject=*/false, 14636 /*Copying=*/false); 14637 if (Move.isInvalid()) { 14638 MoveAssignOperator->setInvalidDecl(); 14639 return; 14640 } 14641 14642 // Success! Record the copy. 14643 Statements.push_back(Move.getAs<Stmt>()); 14644 } 14645 14646 if (!Invalid) { 14647 // Add a "return *this;" 14648 ExprResult ThisObj = 14649 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14650 14651 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14652 if (Return.isInvalid()) 14653 Invalid = true; 14654 else 14655 Statements.push_back(Return.getAs<Stmt>()); 14656 } 14657 14658 if (Invalid) { 14659 MoveAssignOperator->setInvalidDecl(); 14660 return; 14661 } 14662 14663 StmtResult Body; 14664 { 14665 CompoundScopeRAII CompoundScope(*this); 14666 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14667 /*isStmtExpr=*/false); 14668 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14669 } 14670 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 14671 MoveAssignOperator->markUsed(Context); 14672 14673 if (ASTMutationListener *L = getASTMutationListener()) { 14674 L->CompletedImplicitDefinition(MoveAssignOperator); 14675 } 14676 } 14677 14678 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 14679 CXXRecordDecl *ClassDecl) { 14680 // C++ [class.copy]p4: 14681 // If the class definition does not explicitly declare a copy 14682 // constructor, one is declared implicitly. 14683 assert(ClassDecl->needsImplicitCopyConstructor()); 14684 14685 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 14686 if (DSM.isAlreadyBeingDeclared()) 14687 return nullptr; 14688 14689 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14690 QualType ArgType = ClassType; 14691 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 14692 if (Const) 14693 ArgType = ArgType.withConst(); 14694 14695 LangAS AS = getDefaultCXXMethodAddrSpace(); 14696 if (AS != LangAS::Default) 14697 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14698 14699 ArgType = Context.getLValueReferenceType(ArgType); 14700 14701 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14702 CXXCopyConstructor, 14703 Const); 14704 14705 DeclarationName Name 14706 = Context.DeclarationNames.getCXXConstructorName( 14707 Context.getCanonicalType(ClassType)); 14708 SourceLocation ClassLoc = ClassDecl->getLocation(); 14709 DeclarationNameInfo NameInfo(Name, ClassLoc); 14710 14711 // An implicitly-declared copy constructor is an inline public 14712 // member of its class. 14713 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 14714 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14715 ExplicitSpecifier(), 14716 /*isInline=*/true, 14717 /*isImplicitlyDeclared=*/true, 14718 Constexpr ? ConstexprSpecKind::Constexpr 14719 : ConstexprSpecKind::Unspecified); 14720 CopyConstructor->setAccess(AS_public); 14721 CopyConstructor->setDefaulted(); 14722 14723 if (getLangOpts().CUDA) { 14724 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 14725 CopyConstructor, 14726 /* ConstRHS */ Const, 14727 /* Diagnose */ false); 14728 } 14729 14730 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 14731 14732 // Add the parameter to the constructor. 14733 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 14734 ClassLoc, ClassLoc, 14735 /*IdentifierInfo=*/nullptr, 14736 ArgType, /*TInfo=*/nullptr, 14737 SC_None, nullptr); 14738 CopyConstructor->setParams(FromParam); 14739 14740 CopyConstructor->setTrivial( 14741 ClassDecl->needsOverloadResolutionForCopyConstructor() 14742 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 14743 : ClassDecl->hasTrivialCopyConstructor()); 14744 14745 CopyConstructor->setTrivialForCall( 14746 ClassDecl->hasAttr<TrivialABIAttr>() || 14747 (ClassDecl->needsOverloadResolutionForCopyConstructor() 14748 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 14749 TAH_ConsiderTrivialABI) 14750 : ClassDecl->hasTrivialCopyConstructorForCall())); 14751 14752 // Note that we have declared this constructor. 14753 ++getASTContext().NumImplicitCopyConstructorsDeclared; 14754 14755 Scope *S = getScopeForContext(ClassDecl); 14756 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 14757 14758 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 14759 ClassDecl->setImplicitCopyConstructorIsDeleted(); 14760 SetDeclDeleted(CopyConstructor, ClassLoc); 14761 } 14762 14763 if (S) 14764 PushOnScopeChains(CopyConstructor, S, false); 14765 ClassDecl->addDecl(CopyConstructor); 14766 14767 return CopyConstructor; 14768 } 14769 14770 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 14771 CXXConstructorDecl *CopyConstructor) { 14772 assert((CopyConstructor->isDefaulted() && 14773 CopyConstructor->isCopyConstructor() && 14774 !CopyConstructor->doesThisDeclarationHaveABody() && 14775 !CopyConstructor->isDeleted()) && 14776 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 14777 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 14778 return; 14779 14780 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 14781 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 14782 14783 SynthesizedFunctionScope Scope(*this, CopyConstructor); 14784 14785 // The exception specification is needed because we are defining the 14786 // function. 14787 ResolveExceptionSpec(CurrentLocation, 14788 CopyConstructor->getType()->castAs<FunctionProtoType>()); 14789 MarkVTableUsed(CurrentLocation, ClassDecl); 14790 14791 // Add a context note for diagnostics produced after this point. 14792 Scope.addContextNote(CurrentLocation); 14793 14794 // C++11 [class.copy]p7: 14795 // The [definition of an implicitly declared copy constructor] is 14796 // deprecated if the class has a user-declared copy assignment operator 14797 // or a user-declared destructor. 14798 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 14799 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 14800 14801 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 14802 CopyConstructor->setInvalidDecl(); 14803 } else { 14804 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 14805 ? CopyConstructor->getEndLoc() 14806 : CopyConstructor->getLocation(); 14807 Sema::CompoundScopeRAII CompoundScope(*this); 14808 CopyConstructor->setBody( 14809 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 14810 CopyConstructor->markUsed(Context); 14811 } 14812 14813 if (ASTMutationListener *L = getASTMutationListener()) { 14814 L->CompletedImplicitDefinition(CopyConstructor); 14815 } 14816 } 14817 14818 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 14819 CXXRecordDecl *ClassDecl) { 14820 assert(ClassDecl->needsImplicitMoveConstructor()); 14821 14822 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 14823 if (DSM.isAlreadyBeingDeclared()) 14824 return nullptr; 14825 14826 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14827 14828 QualType ArgType = ClassType; 14829 LangAS AS = getDefaultCXXMethodAddrSpace(); 14830 if (AS != LangAS::Default) 14831 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 14832 ArgType = Context.getRValueReferenceType(ArgType); 14833 14834 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14835 CXXMoveConstructor, 14836 false); 14837 14838 DeclarationName Name 14839 = Context.DeclarationNames.getCXXConstructorName( 14840 Context.getCanonicalType(ClassType)); 14841 SourceLocation ClassLoc = ClassDecl->getLocation(); 14842 DeclarationNameInfo NameInfo(Name, ClassLoc); 14843 14844 // C++11 [class.copy]p11: 14845 // An implicitly-declared copy/move constructor is an inline public 14846 // member of its class. 14847 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 14848 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14849 ExplicitSpecifier(), 14850 /*isInline=*/true, 14851 /*isImplicitlyDeclared=*/true, 14852 Constexpr ? ConstexprSpecKind::Constexpr 14853 : ConstexprSpecKind::Unspecified); 14854 MoveConstructor->setAccess(AS_public); 14855 MoveConstructor->setDefaulted(); 14856 14857 if (getLangOpts().CUDA) { 14858 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 14859 MoveConstructor, 14860 /* ConstRHS */ false, 14861 /* Diagnose */ false); 14862 } 14863 14864 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 14865 14866 // Add the parameter to the constructor. 14867 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 14868 ClassLoc, ClassLoc, 14869 /*IdentifierInfo=*/nullptr, 14870 ArgType, /*TInfo=*/nullptr, 14871 SC_None, nullptr); 14872 MoveConstructor->setParams(FromParam); 14873 14874 MoveConstructor->setTrivial( 14875 ClassDecl->needsOverloadResolutionForMoveConstructor() 14876 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 14877 : ClassDecl->hasTrivialMoveConstructor()); 14878 14879 MoveConstructor->setTrivialForCall( 14880 ClassDecl->hasAttr<TrivialABIAttr>() || 14881 (ClassDecl->needsOverloadResolutionForMoveConstructor() 14882 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 14883 TAH_ConsiderTrivialABI) 14884 : ClassDecl->hasTrivialMoveConstructorForCall())); 14885 14886 // Note that we have declared this constructor. 14887 ++getASTContext().NumImplicitMoveConstructorsDeclared; 14888 14889 Scope *S = getScopeForContext(ClassDecl); 14890 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 14891 14892 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 14893 ClassDecl->setImplicitMoveConstructorIsDeleted(); 14894 SetDeclDeleted(MoveConstructor, ClassLoc); 14895 } 14896 14897 if (S) 14898 PushOnScopeChains(MoveConstructor, S, false); 14899 ClassDecl->addDecl(MoveConstructor); 14900 14901 return MoveConstructor; 14902 } 14903 14904 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 14905 CXXConstructorDecl *MoveConstructor) { 14906 assert((MoveConstructor->isDefaulted() && 14907 MoveConstructor->isMoveConstructor() && 14908 !MoveConstructor->doesThisDeclarationHaveABody() && 14909 !MoveConstructor->isDeleted()) && 14910 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 14911 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 14912 return; 14913 14914 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 14915 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 14916 14917 SynthesizedFunctionScope Scope(*this, MoveConstructor); 14918 14919 // The exception specification is needed because we are defining the 14920 // function. 14921 ResolveExceptionSpec(CurrentLocation, 14922 MoveConstructor->getType()->castAs<FunctionProtoType>()); 14923 MarkVTableUsed(CurrentLocation, ClassDecl); 14924 14925 // Add a context note for diagnostics produced after this point. 14926 Scope.addContextNote(CurrentLocation); 14927 14928 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 14929 MoveConstructor->setInvalidDecl(); 14930 } else { 14931 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 14932 ? MoveConstructor->getEndLoc() 14933 : MoveConstructor->getLocation(); 14934 Sema::CompoundScopeRAII CompoundScope(*this); 14935 MoveConstructor->setBody(ActOnCompoundStmt( 14936 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 14937 MoveConstructor->markUsed(Context); 14938 } 14939 14940 if (ASTMutationListener *L = getASTMutationListener()) { 14941 L->CompletedImplicitDefinition(MoveConstructor); 14942 } 14943 } 14944 14945 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 14946 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 14947 } 14948 14949 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 14950 SourceLocation CurrentLocation, 14951 CXXConversionDecl *Conv) { 14952 SynthesizedFunctionScope Scope(*this, Conv); 14953 assert(!Conv->getReturnType()->isUndeducedType()); 14954 14955 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType(); 14956 CallingConv CC = 14957 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv(); 14958 14959 CXXRecordDecl *Lambda = Conv->getParent(); 14960 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 14961 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC); 14962 14963 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 14964 CallOp = InstantiateFunctionDeclaration( 14965 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14966 if (!CallOp) 14967 return; 14968 14969 Invoker = InstantiateFunctionDeclaration( 14970 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14971 if (!Invoker) 14972 return; 14973 } 14974 14975 if (CallOp->isInvalidDecl()) 14976 return; 14977 14978 // Mark the call operator referenced (and add to pending instantiations 14979 // if necessary). 14980 // For both the conversion and static-invoker template specializations 14981 // we construct their body's in this function, so no need to add them 14982 // to the PendingInstantiations. 14983 MarkFunctionReferenced(CurrentLocation, CallOp); 14984 14985 // Fill in the __invoke function with a dummy implementation. IR generation 14986 // will fill in the actual details. Update its type in case it contained 14987 // an 'auto'. 14988 Invoker->markUsed(Context); 14989 Invoker->setReferenced(); 14990 Invoker->setType(Conv->getReturnType()->getPointeeType()); 14991 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 14992 14993 // Construct the body of the conversion function { return __invoke; }. 14994 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 14995 VK_LValue, Conv->getLocation()); 14996 assert(FunctionRef && "Can't refer to __invoke function?"); 14997 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 14998 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 14999 Conv->getLocation())); 15000 Conv->markUsed(Context); 15001 Conv->setReferenced(); 15002 15003 if (ASTMutationListener *L = getASTMutationListener()) { 15004 L->CompletedImplicitDefinition(Conv); 15005 L->CompletedImplicitDefinition(Invoker); 15006 } 15007 } 15008 15009 15010 15011 void Sema::DefineImplicitLambdaToBlockPointerConversion( 15012 SourceLocation CurrentLocation, 15013 CXXConversionDecl *Conv) 15014 { 15015 assert(!Conv->getParent()->isGenericLambda()); 15016 15017 SynthesizedFunctionScope Scope(*this, Conv); 15018 15019 // Copy-initialize the lambda object as needed to capture it. 15020 Expr *This = ActOnCXXThis(CurrentLocation).get(); 15021 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 15022 15023 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 15024 Conv->getLocation(), 15025 Conv, DerefThis); 15026 15027 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 15028 // behavior. Note that only the general conversion function does this 15029 // (since it's unusable otherwise); in the case where we inline the 15030 // block literal, it has block literal lifetime semantics. 15031 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 15032 BuildBlock = ImplicitCastExpr::Create( 15033 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject, 15034 BuildBlock.get(), nullptr, VK_RValue, FPOptionsOverride()); 15035 15036 if (BuildBlock.isInvalid()) { 15037 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15038 Conv->setInvalidDecl(); 15039 return; 15040 } 15041 15042 // Create the return statement that returns the block from the conversion 15043 // function. 15044 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 15045 if (Return.isInvalid()) { 15046 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15047 Conv->setInvalidDecl(); 15048 return; 15049 } 15050 15051 // Set the body of the conversion function. 15052 Stmt *ReturnS = Return.get(); 15053 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 15054 Conv->getLocation())); 15055 Conv->markUsed(Context); 15056 15057 // We're done; notify the mutation listener, if any. 15058 if (ASTMutationListener *L = getASTMutationListener()) { 15059 L->CompletedImplicitDefinition(Conv); 15060 } 15061 } 15062 15063 /// Determine whether the given list arguments contains exactly one 15064 /// "real" (non-default) argument. 15065 static bool hasOneRealArgument(MultiExprArg Args) { 15066 switch (Args.size()) { 15067 case 0: 15068 return false; 15069 15070 default: 15071 if (!Args[1]->isDefaultArgument()) 15072 return false; 15073 15074 LLVM_FALLTHROUGH; 15075 case 1: 15076 return !Args[0]->isDefaultArgument(); 15077 } 15078 15079 return false; 15080 } 15081 15082 ExprResult 15083 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15084 NamedDecl *FoundDecl, 15085 CXXConstructorDecl *Constructor, 15086 MultiExprArg ExprArgs, 15087 bool HadMultipleCandidates, 15088 bool IsListInitialization, 15089 bool IsStdInitListInitialization, 15090 bool RequiresZeroInit, 15091 unsigned ConstructKind, 15092 SourceRange ParenRange) { 15093 bool Elidable = false; 15094 15095 // C++0x [class.copy]p34: 15096 // When certain criteria are met, an implementation is allowed to 15097 // omit the copy/move construction of a class object, even if the 15098 // copy/move constructor and/or destructor for the object have 15099 // side effects. [...] 15100 // - when a temporary class object that has not been bound to a 15101 // reference (12.2) would be copied/moved to a class object 15102 // with the same cv-unqualified type, the copy/move operation 15103 // can be omitted by constructing the temporary object 15104 // directly into the target of the omitted copy/move 15105 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 15106 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 15107 Expr *SubExpr = ExprArgs[0]; 15108 Elidable = SubExpr->isTemporaryObject( 15109 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 15110 } 15111 15112 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 15113 FoundDecl, Constructor, 15114 Elidable, ExprArgs, HadMultipleCandidates, 15115 IsListInitialization, 15116 IsStdInitListInitialization, RequiresZeroInit, 15117 ConstructKind, ParenRange); 15118 } 15119 15120 ExprResult 15121 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15122 NamedDecl *FoundDecl, 15123 CXXConstructorDecl *Constructor, 15124 bool Elidable, 15125 MultiExprArg ExprArgs, 15126 bool HadMultipleCandidates, 15127 bool IsListInitialization, 15128 bool IsStdInitListInitialization, 15129 bool RequiresZeroInit, 15130 unsigned ConstructKind, 15131 SourceRange ParenRange) { 15132 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 15133 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 15134 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 15135 return ExprError(); 15136 } 15137 15138 return BuildCXXConstructExpr( 15139 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 15140 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 15141 RequiresZeroInit, ConstructKind, ParenRange); 15142 } 15143 15144 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 15145 /// including handling of its default argument expressions. 15146 ExprResult 15147 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15148 CXXConstructorDecl *Constructor, 15149 bool Elidable, 15150 MultiExprArg ExprArgs, 15151 bool HadMultipleCandidates, 15152 bool IsListInitialization, 15153 bool IsStdInitListInitialization, 15154 bool RequiresZeroInit, 15155 unsigned ConstructKind, 15156 SourceRange ParenRange) { 15157 assert(declaresSameEntity( 15158 Constructor->getParent(), 15159 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 15160 "given constructor for wrong type"); 15161 MarkFunctionReferenced(ConstructLoc, Constructor); 15162 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 15163 return ExprError(); 15164 if (getLangOpts().SYCLIsDevice && 15165 !checkSYCLDeviceFunction(ConstructLoc, Constructor)) 15166 return ExprError(); 15167 15168 return CheckForImmediateInvocation( 15169 CXXConstructExpr::Create( 15170 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 15171 HadMultipleCandidates, IsListInitialization, 15172 IsStdInitListInitialization, RequiresZeroInit, 15173 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 15174 ParenRange), 15175 Constructor); 15176 } 15177 15178 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 15179 assert(Field->hasInClassInitializer()); 15180 15181 // If we already have the in-class initializer nothing needs to be done. 15182 if (Field->getInClassInitializer()) 15183 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15184 15185 // If we might have already tried and failed to instantiate, don't try again. 15186 if (Field->isInvalidDecl()) 15187 return ExprError(); 15188 15189 // Maybe we haven't instantiated the in-class initializer. Go check the 15190 // pattern FieldDecl to see if it has one. 15191 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 15192 15193 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 15194 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 15195 DeclContext::lookup_result Lookup = 15196 ClassPattern->lookup(Field->getDeclName()); 15197 15198 FieldDecl *Pattern = nullptr; 15199 for (auto L : Lookup) { 15200 if (isa<FieldDecl>(L)) { 15201 Pattern = cast<FieldDecl>(L); 15202 break; 15203 } 15204 } 15205 assert(Pattern && "We must have set the Pattern!"); 15206 15207 if (!Pattern->hasInClassInitializer() || 15208 InstantiateInClassInitializer(Loc, Field, Pattern, 15209 getTemplateInstantiationArgs(Field))) { 15210 // Don't diagnose this again. 15211 Field->setInvalidDecl(); 15212 return ExprError(); 15213 } 15214 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15215 } 15216 15217 // DR1351: 15218 // If the brace-or-equal-initializer of a non-static data member 15219 // invokes a defaulted default constructor of its class or of an 15220 // enclosing class in a potentially evaluated subexpression, the 15221 // program is ill-formed. 15222 // 15223 // This resolution is unworkable: the exception specification of the 15224 // default constructor can be needed in an unevaluated context, in 15225 // particular, in the operand of a noexcept-expression, and we can be 15226 // unable to compute an exception specification for an enclosed class. 15227 // 15228 // Any attempt to resolve the exception specification of a defaulted default 15229 // constructor before the initializer is lexically complete will ultimately 15230 // come here at which point we can diagnose it. 15231 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 15232 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed) 15233 << OutermostClass << Field; 15234 Diag(Field->getEndLoc(), 15235 diag::note_default_member_initializer_not_yet_parsed); 15236 // Recover by marking the field invalid, unless we're in a SFINAE context. 15237 if (!isSFINAEContext()) 15238 Field->setInvalidDecl(); 15239 return ExprError(); 15240 } 15241 15242 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 15243 if (VD->isInvalidDecl()) return; 15244 // If initializing the variable failed, don't also diagnose problems with 15245 // the desctructor, they're likely related. 15246 if (VD->getInit() && VD->getInit()->containsErrors()) 15247 return; 15248 15249 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 15250 if (ClassDecl->isInvalidDecl()) return; 15251 if (ClassDecl->hasIrrelevantDestructor()) return; 15252 if (ClassDecl->isDependentContext()) return; 15253 15254 if (VD->isNoDestroy(getASTContext())) 15255 return; 15256 15257 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15258 15259 // If this is an array, we'll require the destructor during initialization, so 15260 // we can skip over this. We still want to emit exit-time destructor warnings 15261 // though. 15262 if (!VD->getType()->isArrayType()) { 15263 MarkFunctionReferenced(VD->getLocation(), Destructor); 15264 CheckDestructorAccess(VD->getLocation(), Destructor, 15265 PDiag(diag::err_access_dtor_var) 15266 << VD->getDeclName() << VD->getType()); 15267 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 15268 } 15269 15270 if (Destructor->isTrivial()) return; 15271 15272 // If the destructor is constexpr, check whether the variable has constant 15273 // destruction now. 15274 if (Destructor->isConstexpr()) { 15275 bool HasConstantInit = false; 15276 if (VD->getInit() && !VD->getInit()->isValueDependent()) 15277 HasConstantInit = VD->evaluateValue(); 15278 SmallVector<PartialDiagnosticAt, 8> Notes; 15279 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && 15280 HasConstantInit) { 15281 Diag(VD->getLocation(), 15282 diag::err_constexpr_var_requires_const_destruction) << VD; 15283 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 15284 Diag(Notes[I].first, Notes[I].second); 15285 } 15286 } 15287 15288 if (!VD->hasGlobalStorage()) return; 15289 15290 // Emit warning for non-trivial dtor in global scope (a real global, 15291 // class-static, function-static). 15292 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 15293 15294 // TODO: this should be re-enabled for static locals by !CXAAtExit 15295 if (!VD->isStaticLocal()) 15296 Diag(VD->getLocation(), diag::warn_global_destructor); 15297 } 15298 15299 /// Given a constructor and the set of arguments provided for the 15300 /// constructor, convert the arguments and add any required default arguments 15301 /// to form a proper call to this constructor. 15302 /// 15303 /// \returns true if an error occurred, false otherwise. 15304 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 15305 QualType DeclInitType, MultiExprArg ArgsPtr, 15306 SourceLocation Loc, 15307 SmallVectorImpl<Expr *> &ConvertedArgs, 15308 bool AllowExplicit, 15309 bool IsListInitialization) { 15310 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 15311 unsigned NumArgs = ArgsPtr.size(); 15312 Expr **Args = ArgsPtr.data(); 15313 15314 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); 15315 unsigned NumParams = Proto->getNumParams(); 15316 15317 // If too few arguments are available, we'll fill in the rest with defaults. 15318 if (NumArgs < NumParams) 15319 ConvertedArgs.reserve(NumParams); 15320 else 15321 ConvertedArgs.reserve(NumArgs); 15322 15323 VariadicCallType CallType = 15324 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 15325 SmallVector<Expr *, 8> AllArgs; 15326 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 15327 Proto, 0, 15328 llvm::makeArrayRef(Args, NumArgs), 15329 AllArgs, 15330 CallType, AllowExplicit, 15331 IsListInitialization); 15332 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 15333 15334 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 15335 15336 CheckConstructorCall(Constructor, DeclInitType, 15337 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 15338 Proto, Loc); 15339 15340 return Invalid; 15341 } 15342 15343 static inline bool 15344 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 15345 const FunctionDecl *FnDecl) { 15346 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 15347 if (isa<NamespaceDecl>(DC)) { 15348 return SemaRef.Diag(FnDecl->getLocation(), 15349 diag::err_operator_new_delete_declared_in_namespace) 15350 << FnDecl->getDeclName(); 15351 } 15352 15353 if (isa<TranslationUnitDecl>(DC) && 15354 FnDecl->getStorageClass() == SC_Static) { 15355 return SemaRef.Diag(FnDecl->getLocation(), 15356 diag::err_operator_new_delete_declared_static) 15357 << FnDecl->getDeclName(); 15358 } 15359 15360 return false; 15361 } 15362 15363 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, 15364 const PointerType *PtrTy) { 15365 auto &Ctx = SemaRef.Context; 15366 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers(); 15367 PtrQuals.removeAddressSpace(); 15368 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType( 15369 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals))); 15370 } 15371 15372 static inline bool 15373 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 15374 CanQualType ExpectedResultType, 15375 CanQualType ExpectedFirstParamType, 15376 unsigned DependentParamTypeDiag, 15377 unsigned InvalidParamTypeDiag) { 15378 QualType ResultType = 15379 FnDecl->getType()->castAs<FunctionType>()->getReturnType(); 15380 15381 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15382 // The operator is valid on any address space for OpenCL. 15383 // Drop address space from actual and expected result types. 15384 if (const auto *PtrTy = ResultType->getAs<PointerType>()) 15385 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15386 15387 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>()) 15388 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15389 } 15390 15391 // Check that the result type is what we expect. 15392 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) { 15393 // Reject even if the type is dependent; an operator delete function is 15394 // required to have a non-dependent result type. 15395 return SemaRef.Diag( 15396 FnDecl->getLocation(), 15397 ResultType->isDependentType() 15398 ? diag::err_operator_new_delete_dependent_result_type 15399 : diag::err_operator_new_delete_invalid_result_type) 15400 << FnDecl->getDeclName() << ExpectedResultType; 15401 } 15402 15403 // A function template must have at least 2 parameters. 15404 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 15405 return SemaRef.Diag(FnDecl->getLocation(), 15406 diag::err_operator_new_delete_template_too_few_parameters) 15407 << FnDecl->getDeclName(); 15408 15409 // The function decl must have at least 1 parameter. 15410 if (FnDecl->getNumParams() == 0) 15411 return SemaRef.Diag(FnDecl->getLocation(), 15412 diag::err_operator_new_delete_too_few_parameters) 15413 << FnDecl->getDeclName(); 15414 15415 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 15416 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15417 // The operator is valid on any address space for OpenCL. 15418 // Drop address space from actual and expected first parameter types. 15419 if (const auto *PtrTy = 15420 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) 15421 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15422 15423 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>()) 15424 ExpectedFirstParamType = 15425 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15426 } 15427 15428 // Check that the first parameter type is what we expect. 15429 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 15430 ExpectedFirstParamType) { 15431 // The first parameter type is not allowed to be dependent. As a tentative 15432 // DR resolution, we allow a dependent parameter type if it is the right 15433 // type anyway, to allow destroying operator delete in class templates. 15434 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType() 15435 ? DependentParamTypeDiag 15436 : InvalidParamTypeDiag) 15437 << FnDecl->getDeclName() << ExpectedFirstParamType; 15438 } 15439 15440 return false; 15441 } 15442 15443 static bool 15444 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 15445 // C++ [basic.stc.dynamic.allocation]p1: 15446 // A program is ill-formed if an allocation function is declared in a 15447 // namespace scope other than global scope or declared static in global 15448 // scope. 15449 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15450 return true; 15451 15452 CanQualType SizeTy = 15453 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 15454 15455 // C++ [basic.stc.dynamic.allocation]p1: 15456 // The return type shall be void*. The first parameter shall have type 15457 // std::size_t. 15458 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 15459 SizeTy, 15460 diag::err_operator_new_dependent_param_type, 15461 diag::err_operator_new_param_type)) 15462 return true; 15463 15464 // C++ [basic.stc.dynamic.allocation]p1: 15465 // The first parameter shall not have an associated default argument. 15466 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 15467 return SemaRef.Diag(FnDecl->getLocation(), 15468 diag::err_operator_new_default_arg) 15469 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 15470 15471 return false; 15472 } 15473 15474 static bool 15475 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 15476 // C++ [basic.stc.dynamic.deallocation]p1: 15477 // A program is ill-formed if deallocation functions are declared in a 15478 // namespace scope other than global scope or declared static in global 15479 // scope. 15480 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15481 return true; 15482 15483 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 15484 15485 // C++ P0722: 15486 // Within a class C, the first parameter of a destroying operator delete 15487 // shall be of type C *. The first parameter of any other deallocation 15488 // function shall be of type void *. 15489 CanQualType ExpectedFirstParamType = 15490 MD && MD->isDestroyingOperatorDelete() 15491 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 15492 SemaRef.Context.getRecordType(MD->getParent()))) 15493 : SemaRef.Context.VoidPtrTy; 15494 15495 // C++ [basic.stc.dynamic.deallocation]p2: 15496 // Each deallocation function shall return void 15497 if (CheckOperatorNewDeleteTypes( 15498 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 15499 diag::err_operator_delete_dependent_param_type, 15500 diag::err_operator_delete_param_type)) 15501 return true; 15502 15503 // C++ P0722: 15504 // A destroying operator delete shall be a usual deallocation function. 15505 if (MD && !MD->getParent()->isDependentContext() && 15506 MD->isDestroyingOperatorDelete() && 15507 !SemaRef.isUsualDeallocationFunction(MD)) { 15508 SemaRef.Diag(MD->getLocation(), 15509 diag::err_destroying_operator_delete_not_usual); 15510 return true; 15511 } 15512 15513 return false; 15514 } 15515 15516 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 15517 /// of this overloaded operator is well-formed. If so, returns false; 15518 /// otherwise, emits appropriate diagnostics and returns true. 15519 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 15520 assert(FnDecl && FnDecl->isOverloadedOperator() && 15521 "Expected an overloaded operator declaration"); 15522 15523 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 15524 15525 // C++ [over.oper]p5: 15526 // The allocation and deallocation functions, operator new, 15527 // operator new[], operator delete and operator delete[], are 15528 // described completely in 3.7.3. The attributes and restrictions 15529 // found in the rest of this subclause do not apply to them unless 15530 // explicitly stated in 3.7.3. 15531 if (Op == OO_Delete || Op == OO_Array_Delete) 15532 return CheckOperatorDeleteDeclaration(*this, FnDecl); 15533 15534 if (Op == OO_New || Op == OO_Array_New) 15535 return CheckOperatorNewDeclaration(*this, FnDecl); 15536 15537 // C++ [over.oper]p6: 15538 // An operator function shall either be a non-static member 15539 // function or be a non-member function and have at least one 15540 // parameter whose type is a class, a reference to a class, an 15541 // enumeration, or a reference to an enumeration. 15542 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 15543 if (MethodDecl->isStatic()) 15544 return Diag(FnDecl->getLocation(), 15545 diag::err_operator_overload_static) << FnDecl->getDeclName(); 15546 } else { 15547 bool ClassOrEnumParam = false; 15548 for (auto Param : FnDecl->parameters()) { 15549 QualType ParamType = Param->getType().getNonReferenceType(); 15550 if (ParamType->isDependentType() || ParamType->isRecordType() || 15551 ParamType->isEnumeralType()) { 15552 ClassOrEnumParam = true; 15553 break; 15554 } 15555 } 15556 15557 if (!ClassOrEnumParam) 15558 return Diag(FnDecl->getLocation(), 15559 diag::err_operator_overload_needs_class_or_enum) 15560 << FnDecl->getDeclName(); 15561 } 15562 15563 // C++ [over.oper]p8: 15564 // An operator function cannot have default arguments (8.3.6), 15565 // except where explicitly stated below. 15566 // 15567 // Only the function-call operator allows default arguments 15568 // (C++ [over.call]p1). 15569 if (Op != OO_Call) { 15570 for (auto Param : FnDecl->parameters()) { 15571 if (Param->hasDefaultArg()) 15572 return Diag(Param->getLocation(), 15573 diag::err_operator_overload_default_arg) 15574 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 15575 } 15576 } 15577 15578 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 15579 { false, false, false } 15580 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 15581 , { Unary, Binary, MemberOnly } 15582 #include "clang/Basic/OperatorKinds.def" 15583 }; 15584 15585 bool CanBeUnaryOperator = OperatorUses[Op][0]; 15586 bool CanBeBinaryOperator = OperatorUses[Op][1]; 15587 bool MustBeMemberOperator = OperatorUses[Op][2]; 15588 15589 // C++ [over.oper]p8: 15590 // [...] Operator functions cannot have more or fewer parameters 15591 // than the number required for the corresponding operator, as 15592 // described in the rest of this subclause. 15593 unsigned NumParams = FnDecl->getNumParams() 15594 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 15595 if (Op != OO_Call && 15596 ((NumParams == 1 && !CanBeUnaryOperator) || 15597 (NumParams == 2 && !CanBeBinaryOperator) || 15598 (NumParams < 1) || (NumParams > 2))) { 15599 // We have the wrong number of parameters. 15600 unsigned ErrorKind; 15601 if (CanBeUnaryOperator && CanBeBinaryOperator) { 15602 ErrorKind = 2; // 2 -> unary or binary. 15603 } else if (CanBeUnaryOperator) { 15604 ErrorKind = 0; // 0 -> unary 15605 } else { 15606 assert(CanBeBinaryOperator && 15607 "All non-call overloaded operators are unary or binary!"); 15608 ErrorKind = 1; // 1 -> binary 15609 } 15610 15611 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 15612 << FnDecl->getDeclName() << NumParams << ErrorKind; 15613 } 15614 15615 // Overloaded operators other than operator() cannot be variadic. 15616 if (Op != OO_Call && 15617 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { 15618 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 15619 << FnDecl->getDeclName(); 15620 } 15621 15622 // Some operators must be non-static member functions. 15623 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 15624 return Diag(FnDecl->getLocation(), 15625 diag::err_operator_overload_must_be_member) 15626 << FnDecl->getDeclName(); 15627 } 15628 15629 // C++ [over.inc]p1: 15630 // The user-defined function called operator++ implements the 15631 // prefix and postfix ++ operator. If this function is a member 15632 // function with no parameters, or a non-member function with one 15633 // parameter of class or enumeration type, it defines the prefix 15634 // increment operator ++ for objects of that type. If the function 15635 // is a member function with one parameter (which shall be of type 15636 // int) or a non-member function with two parameters (the second 15637 // of which shall be of type int), it defines the postfix 15638 // increment operator ++ for objects of that type. 15639 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 15640 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 15641 QualType ParamType = LastParam->getType(); 15642 15643 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 15644 !ParamType->isDependentType()) 15645 return Diag(LastParam->getLocation(), 15646 diag::err_operator_overload_post_incdec_must_be_int) 15647 << LastParam->getType() << (Op == OO_MinusMinus); 15648 } 15649 15650 return false; 15651 } 15652 15653 static bool 15654 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 15655 FunctionTemplateDecl *TpDecl) { 15656 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 15657 15658 // Must have one or two template parameters. 15659 if (TemplateParams->size() == 1) { 15660 NonTypeTemplateParmDecl *PmDecl = 15661 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 15662 15663 // The template parameter must be a char parameter pack. 15664 if (PmDecl && PmDecl->isTemplateParameterPack() && 15665 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 15666 return false; 15667 15668 // C++20 [over.literal]p5: 15669 // A string literal operator template is a literal operator template 15670 // whose template-parameter-list comprises a single non-type 15671 // template-parameter of class type. 15672 // 15673 // As a DR resolution, we also allow placeholders for deduced class 15674 // template specializations. 15675 if (SemaRef.getLangOpts().CPlusPlus20 && 15676 !PmDecl->isTemplateParameterPack() && 15677 (PmDecl->getType()->isRecordType() || 15678 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>())) 15679 return false; 15680 } else if (TemplateParams->size() == 2) { 15681 TemplateTypeParmDecl *PmType = 15682 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 15683 NonTypeTemplateParmDecl *PmArgs = 15684 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 15685 15686 // The second template parameter must be a parameter pack with the 15687 // first template parameter as its type. 15688 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 15689 PmArgs->isTemplateParameterPack()) { 15690 const TemplateTypeParmType *TArgs = 15691 PmArgs->getType()->getAs<TemplateTypeParmType>(); 15692 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 15693 TArgs->getIndex() == PmType->getIndex()) { 15694 if (!SemaRef.inTemplateInstantiation()) 15695 SemaRef.Diag(TpDecl->getLocation(), 15696 diag::ext_string_literal_operator_template); 15697 return false; 15698 } 15699 } 15700 } 15701 15702 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 15703 diag::err_literal_operator_template) 15704 << TpDecl->getTemplateParameters()->getSourceRange(); 15705 return true; 15706 } 15707 15708 /// CheckLiteralOperatorDeclaration - Check whether the declaration 15709 /// of this literal operator function is well-formed. If so, returns 15710 /// false; otherwise, emits appropriate diagnostics and returns true. 15711 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 15712 if (isa<CXXMethodDecl>(FnDecl)) { 15713 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 15714 << FnDecl->getDeclName(); 15715 return true; 15716 } 15717 15718 if (FnDecl->isExternC()) { 15719 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 15720 if (const LinkageSpecDecl *LSD = 15721 FnDecl->getDeclContext()->getExternCContext()) 15722 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 15723 return true; 15724 } 15725 15726 // This might be the definition of a literal operator template. 15727 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 15728 15729 // This might be a specialization of a literal operator template. 15730 if (!TpDecl) 15731 TpDecl = FnDecl->getPrimaryTemplate(); 15732 15733 // template <char...> type operator "" name() and 15734 // template <class T, T...> type operator "" name() are the only valid 15735 // template signatures, and the only valid signatures with no parameters. 15736 // 15737 // C++20 also allows template <SomeClass T> type operator "" name(). 15738 if (TpDecl) { 15739 if (FnDecl->param_size() != 0) { 15740 Diag(FnDecl->getLocation(), 15741 diag::err_literal_operator_template_with_params); 15742 return true; 15743 } 15744 15745 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 15746 return true; 15747 15748 } else if (FnDecl->param_size() == 1) { 15749 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 15750 15751 QualType ParamType = Param->getType().getUnqualifiedType(); 15752 15753 // Only unsigned long long int, long double, any character type, and const 15754 // char * are allowed as the only parameters. 15755 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 15756 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 15757 Context.hasSameType(ParamType, Context.CharTy) || 15758 Context.hasSameType(ParamType, Context.WideCharTy) || 15759 Context.hasSameType(ParamType, Context.Char8Ty) || 15760 Context.hasSameType(ParamType, Context.Char16Ty) || 15761 Context.hasSameType(ParamType, Context.Char32Ty)) { 15762 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 15763 QualType InnerType = Ptr->getPointeeType(); 15764 15765 // Pointer parameter must be a const char *. 15766 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 15767 Context.CharTy) && 15768 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 15769 Diag(Param->getSourceRange().getBegin(), 15770 diag::err_literal_operator_param) 15771 << ParamType << "'const char *'" << Param->getSourceRange(); 15772 return true; 15773 } 15774 15775 } else if (ParamType->isRealFloatingType()) { 15776 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15777 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 15778 return true; 15779 15780 } else if (ParamType->isIntegerType()) { 15781 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15782 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 15783 return true; 15784 15785 } else { 15786 Diag(Param->getSourceRange().getBegin(), 15787 diag::err_literal_operator_invalid_param) 15788 << ParamType << Param->getSourceRange(); 15789 return true; 15790 } 15791 15792 } else if (FnDecl->param_size() == 2) { 15793 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 15794 15795 // First, verify that the first parameter is correct. 15796 15797 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 15798 15799 // Two parameter function must have a pointer to const as a 15800 // first parameter; let's strip those qualifiers. 15801 const PointerType *PT = FirstParamType->getAs<PointerType>(); 15802 15803 if (!PT) { 15804 Diag((*Param)->getSourceRange().getBegin(), 15805 diag::err_literal_operator_param) 15806 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15807 return true; 15808 } 15809 15810 QualType PointeeType = PT->getPointeeType(); 15811 // First parameter must be const 15812 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 15813 Diag((*Param)->getSourceRange().getBegin(), 15814 diag::err_literal_operator_param) 15815 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15816 return true; 15817 } 15818 15819 QualType InnerType = PointeeType.getUnqualifiedType(); 15820 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 15821 // const char32_t* are allowed as the first parameter to a two-parameter 15822 // function 15823 if (!(Context.hasSameType(InnerType, Context.CharTy) || 15824 Context.hasSameType(InnerType, Context.WideCharTy) || 15825 Context.hasSameType(InnerType, Context.Char8Ty) || 15826 Context.hasSameType(InnerType, Context.Char16Ty) || 15827 Context.hasSameType(InnerType, Context.Char32Ty))) { 15828 Diag((*Param)->getSourceRange().getBegin(), 15829 diag::err_literal_operator_param) 15830 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15831 return true; 15832 } 15833 15834 // Move on to the second and final parameter. 15835 ++Param; 15836 15837 // The second parameter must be a std::size_t. 15838 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 15839 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 15840 Diag((*Param)->getSourceRange().getBegin(), 15841 diag::err_literal_operator_param) 15842 << SecondParamType << Context.getSizeType() 15843 << (*Param)->getSourceRange(); 15844 return true; 15845 } 15846 } else { 15847 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 15848 return true; 15849 } 15850 15851 // Parameters are good. 15852 15853 // A parameter-declaration-clause containing a default argument is not 15854 // equivalent to any of the permitted forms. 15855 for (auto Param : FnDecl->parameters()) { 15856 if (Param->hasDefaultArg()) { 15857 Diag(Param->getDefaultArgRange().getBegin(), 15858 diag::err_literal_operator_default_argument) 15859 << Param->getDefaultArgRange(); 15860 break; 15861 } 15862 } 15863 15864 StringRef LiteralName 15865 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 15866 if (LiteralName[0] != '_' && 15867 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 15868 // C++11 [usrlit.suffix]p1: 15869 // Literal suffix identifiers that do not start with an underscore 15870 // are reserved for future standardization. 15871 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 15872 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 15873 } 15874 15875 return false; 15876 } 15877 15878 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 15879 /// linkage specification, including the language and (if present) 15880 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 15881 /// language string literal. LBraceLoc, if valid, provides the location of 15882 /// the '{' brace. Otherwise, this linkage specification does not 15883 /// have any braces. 15884 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 15885 Expr *LangStr, 15886 SourceLocation LBraceLoc) { 15887 StringLiteral *Lit = cast<StringLiteral>(LangStr); 15888 if (!Lit->isAscii()) { 15889 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 15890 << LangStr->getSourceRange(); 15891 return nullptr; 15892 } 15893 15894 StringRef Lang = Lit->getString(); 15895 LinkageSpecDecl::LanguageIDs Language; 15896 if (Lang == "C") 15897 Language = LinkageSpecDecl::lang_c; 15898 else if (Lang == "C++") 15899 Language = LinkageSpecDecl::lang_cxx; 15900 else { 15901 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 15902 << LangStr->getSourceRange(); 15903 return nullptr; 15904 } 15905 15906 // FIXME: Add all the various semantics of linkage specifications 15907 15908 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 15909 LangStr->getExprLoc(), Language, 15910 LBraceLoc.isValid()); 15911 CurContext->addDecl(D); 15912 PushDeclContext(S, D); 15913 return D; 15914 } 15915 15916 /// ActOnFinishLinkageSpecification - Complete the definition of 15917 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 15918 /// valid, it's the position of the closing '}' brace in a linkage 15919 /// specification that uses braces. 15920 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 15921 Decl *LinkageSpec, 15922 SourceLocation RBraceLoc) { 15923 if (RBraceLoc.isValid()) { 15924 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 15925 LSDecl->setRBraceLoc(RBraceLoc); 15926 } 15927 PopDeclContext(); 15928 return LinkageSpec; 15929 } 15930 15931 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 15932 const ParsedAttributesView &AttrList, 15933 SourceLocation SemiLoc) { 15934 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 15935 // Attribute declarations appertain to empty declaration so we handle 15936 // them here. 15937 ProcessDeclAttributeList(S, ED, AttrList); 15938 15939 CurContext->addDecl(ED); 15940 return ED; 15941 } 15942 15943 /// Perform semantic analysis for the variable declaration that 15944 /// occurs within a C++ catch clause, returning the newly-created 15945 /// variable. 15946 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 15947 TypeSourceInfo *TInfo, 15948 SourceLocation StartLoc, 15949 SourceLocation Loc, 15950 IdentifierInfo *Name) { 15951 bool Invalid = false; 15952 QualType ExDeclType = TInfo->getType(); 15953 15954 // Arrays and functions decay. 15955 if (ExDeclType->isArrayType()) 15956 ExDeclType = Context.getArrayDecayedType(ExDeclType); 15957 else if (ExDeclType->isFunctionType()) 15958 ExDeclType = Context.getPointerType(ExDeclType); 15959 15960 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 15961 // The exception-declaration shall not denote a pointer or reference to an 15962 // incomplete type, other than [cv] void*. 15963 // N2844 forbids rvalue references. 15964 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 15965 Diag(Loc, diag::err_catch_rvalue_ref); 15966 Invalid = true; 15967 } 15968 15969 if (ExDeclType->isVariablyModifiedType()) { 15970 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 15971 Invalid = true; 15972 } 15973 15974 QualType BaseType = ExDeclType; 15975 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 15976 unsigned DK = diag::err_catch_incomplete; 15977 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 15978 BaseType = Ptr->getPointeeType(); 15979 Mode = 1; 15980 DK = diag::err_catch_incomplete_ptr; 15981 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 15982 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 15983 BaseType = Ref->getPointeeType(); 15984 Mode = 2; 15985 DK = diag::err_catch_incomplete_ref; 15986 } 15987 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 15988 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 15989 Invalid = true; 15990 15991 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) { 15992 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType; 15993 Invalid = true; 15994 } 15995 15996 if (!Invalid && !ExDeclType->isDependentType() && 15997 RequireNonAbstractType(Loc, ExDeclType, 15998 diag::err_abstract_type_in_decl, 15999 AbstractVariableType)) 16000 Invalid = true; 16001 16002 // Only the non-fragile NeXT runtime currently supports C++ catches 16003 // of ObjC types, and no runtime supports catching ObjC types by value. 16004 if (!Invalid && getLangOpts().ObjC) { 16005 QualType T = ExDeclType; 16006 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 16007 T = RT->getPointeeType(); 16008 16009 if (T->isObjCObjectType()) { 16010 Diag(Loc, diag::err_objc_object_catch); 16011 Invalid = true; 16012 } else if (T->isObjCObjectPointerType()) { 16013 // FIXME: should this be a test for macosx-fragile specifically? 16014 if (getLangOpts().ObjCRuntime.isFragile()) 16015 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 16016 } 16017 } 16018 16019 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 16020 ExDeclType, TInfo, SC_None); 16021 ExDecl->setExceptionVariable(true); 16022 16023 // In ARC, infer 'retaining' for variables of retainable type. 16024 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 16025 Invalid = true; 16026 16027 if (!Invalid && !ExDeclType->isDependentType()) { 16028 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 16029 // Insulate this from anything else we might currently be parsing. 16030 EnterExpressionEvaluationContext scope( 16031 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 16032 16033 // C++ [except.handle]p16: 16034 // The object declared in an exception-declaration or, if the 16035 // exception-declaration does not specify a name, a temporary (12.2) is 16036 // copy-initialized (8.5) from the exception object. [...] 16037 // The object is destroyed when the handler exits, after the destruction 16038 // of any automatic objects initialized within the handler. 16039 // 16040 // We just pretend to initialize the object with itself, then make sure 16041 // it can be destroyed later. 16042 QualType initType = Context.getExceptionObjectType(ExDeclType); 16043 16044 InitializedEntity entity = 16045 InitializedEntity::InitializeVariable(ExDecl); 16046 InitializationKind initKind = 16047 InitializationKind::CreateCopy(Loc, SourceLocation()); 16048 16049 Expr *opaqueValue = 16050 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 16051 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 16052 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 16053 if (result.isInvalid()) 16054 Invalid = true; 16055 else { 16056 // If the constructor used was non-trivial, set this as the 16057 // "initializer". 16058 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 16059 if (!construct->getConstructor()->isTrivial()) { 16060 Expr *init = MaybeCreateExprWithCleanups(construct); 16061 ExDecl->setInit(init); 16062 } 16063 16064 // And make sure it's destructable. 16065 FinalizeVarWithDestructor(ExDecl, recordType); 16066 } 16067 } 16068 } 16069 16070 if (Invalid) 16071 ExDecl->setInvalidDecl(); 16072 16073 return ExDecl; 16074 } 16075 16076 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 16077 /// handler. 16078 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 16079 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16080 bool Invalid = D.isInvalidType(); 16081 16082 // Check for unexpanded parameter packs. 16083 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16084 UPPC_ExceptionType)) { 16085 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 16086 D.getIdentifierLoc()); 16087 Invalid = true; 16088 } 16089 16090 IdentifierInfo *II = D.getIdentifier(); 16091 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 16092 LookupOrdinaryName, 16093 ForVisibleRedeclaration)) { 16094 // The scope should be freshly made just for us. There is just no way 16095 // it contains any previous declaration, except for function parameters in 16096 // a function-try-block's catch statement. 16097 assert(!S->isDeclScope(PrevDecl)); 16098 if (isDeclInScope(PrevDecl, CurContext, S)) { 16099 Diag(D.getIdentifierLoc(), diag::err_redefinition) 16100 << D.getIdentifier(); 16101 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 16102 Invalid = true; 16103 } else if (PrevDecl->isTemplateParameter()) 16104 // Maybe we will complain about the shadowed template parameter. 16105 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16106 } 16107 16108 if (D.getCXXScopeSpec().isSet() && !Invalid) { 16109 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 16110 << D.getCXXScopeSpec().getRange(); 16111 Invalid = true; 16112 } 16113 16114 VarDecl *ExDecl = BuildExceptionDeclaration( 16115 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 16116 if (Invalid) 16117 ExDecl->setInvalidDecl(); 16118 16119 // Add the exception declaration into this scope. 16120 if (II) 16121 PushOnScopeChains(ExDecl, S); 16122 else 16123 CurContext->addDecl(ExDecl); 16124 16125 ProcessDeclAttributes(S, ExDecl, D); 16126 return ExDecl; 16127 } 16128 16129 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16130 Expr *AssertExpr, 16131 Expr *AssertMessageExpr, 16132 SourceLocation RParenLoc) { 16133 StringLiteral *AssertMessage = 16134 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 16135 16136 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 16137 return nullptr; 16138 16139 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 16140 AssertMessage, RParenLoc, false); 16141 } 16142 16143 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16144 Expr *AssertExpr, 16145 StringLiteral *AssertMessage, 16146 SourceLocation RParenLoc, 16147 bool Failed) { 16148 assert(AssertExpr != nullptr && "Expected non-null condition"); 16149 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 16150 !Failed) { 16151 // In a static_assert-declaration, the constant-expression shall be a 16152 // constant expression that can be contextually converted to bool. 16153 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 16154 if (Converted.isInvalid()) 16155 Failed = true; 16156 16157 ExprResult FullAssertExpr = 16158 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 16159 /*DiscardedValue*/ false, 16160 /*IsConstexpr*/ true); 16161 if (FullAssertExpr.isInvalid()) 16162 Failed = true; 16163 else 16164 AssertExpr = FullAssertExpr.get(); 16165 16166 llvm::APSInt Cond; 16167 if (!Failed && VerifyIntegerConstantExpression( 16168 AssertExpr, &Cond, 16169 diag::err_static_assert_expression_is_not_constant) 16170 .isInvalid()) 16171 Failed = true; 16172 16173 if (!Failed && !Cond) { 16174 SmallString<256> MsgBuffer; 16175 llvm::raw_svector_ostream Msg(MsgBuffer); 16176 if (AssertMessage) 16177 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 16178 16179 Expr *InnerCond = nullptr; 16180 std::string InnerCondDescription; 16181 std::tie(InnerCond, InnerCondDescription) = 16182 findFailedBooleanCondition(Converted.get()); 16183 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 16184 // Drill down into concept specialization expressions to see why they 16185 // weren't satisfied. 16186 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16187 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16188 ConstraintSatisfaction Satisfaction; 16189 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 16190 DiagnoseUnsatisfiedConstraint(Satisfaction); 16191 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 16192 && !isa<IntegerLiteral>(InnerCond)) { 16193 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 16194 << InnerCondDescription << !AssertMessage 16195 << Msg.str() << InnerCond->getSourceRange(); 16196 } else { 16197 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16198 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16199 } 16200 Failed = true; 16201 } 16202 } else { 16203 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 16204 /*DiscardedValue*/false, 16205 /*IsConstexpr*/true); 16206 if (FullAssertExpr.isInvalid()) 16207 Failed = true; 16208 else 16209 AssertExpr = FullAssertExpr.get(); 16210 } 16211 16212 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 16213 AssertExpr, AssertMessage, RParenLoc, 16214 Failed); 16215 16216 CurContext->addDecl(Decl); 16217 return Decl; 16218 } 16219 16220 /// Perform semantic analysis of the given friend type declaration. 16221 /// 16222 /// \returns A friend declaration that. 16223 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 16224 SourceLocation FriendLoc, 16225 TypeSourceInfo *TSInfo) { 16226 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 16227 16228 QualType T = TSInfo->getType(); 16229 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 16230 16231 // C++03 [class.friend]p2: 16232 // An elaborated-type-specifier shall be used in a friend declaration 16233 // for a class.* 16234 // 16235 // * The class-key of the elaborated-type-specifier is required. 16236 if (!CodeSynthesisContexts.empty()) { 16237 // Do not complain about the form of friend template types during any kind 16238 // of code synthesis. For template instantiation, we will have complained 16239 // when the template was defined. 16240 } else { 16241 if (!T->isElaboratedTypeSpecifier()) { 16242 // If we evaluated the type to a record type, suggest putting 16243 // a tag in front. 16244 if (const RecordType *RT = T->getAs<RecordType>()) { 16245 RecordDecl *RD = RT->getDecl(); 16246 16247 SmallString<16> InsertionText(" "); 16248 InsertionText += RD->getKindName(); 16249 16250 Diag(TypeRange.getBegin(), 16251 getLangOpts().CPlusPlus11 ? 16252 diag::warn_cxx98_compat_unelaborated_friend_type : 16253 diag::ext_unelaborated_friend_type) 16254 << (unsigned) RD->getTagKind() 16255 << T 16256 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 16257 InsertionText); 16258 } else { 16259 Diag(FriendLoc, 16260 getLangOpts().CPlusPlus11 ? 16261 diag::warn_cxx98_compat_nonclass_type_friend : 16262 diag::ext_nonclass_type_friend) 16263 << T 16264 << TypeRange; 16265 } 16266 } else if (T->getAs<EnumType>()) { 16267 Diag(FriendLoc, 16268 getLangOpts().CPlusPlus11 ? 16269 diag::warn_cxx98_compat_enum_friend : 16270 diag::ext_enum_friend) 16271 << T 16272 << TypeRange; 16273 } 16274 16275 // C++11 [class.friend]p3: 16276 // A friend declaration that does not declare a function shall have one 16277 // of the following forms: 16278 // friend elaborated-type-specifier ; 16279 // friend simple-type-specifier ; 16280 // friend typename-specifier ; 16281 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 16282 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 16283 } 16284 16285 // If the type specifier in a friend declaration designates a (possibly 16286 // cv-qualified) class type, that class is declared as a friend; otherwise, 16287 // the friend declaration is ignored. 16288 return FriendDecl::Create(Context, CurContext, 16289 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 16290 FriendLoc); 16291 } 16292 16293 /// Handle a friend tag declaration where the scope specifier was 16294 /// templated. 16295 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 16296 unsigned TagSpec, SourceLocation TagLoc, 16297 CXXScopeSpec &SS, IdentifierInfo *Name, 16298 SourceLocation NameLoc, 16299 const ParsedAttributesView &Attr, 16300 MultiTemplateParamsArg TempParamLists) { 16301 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16302 16303 bool IsMemberSpecialization = false; 16304 bool Invalid = false; 16305 16306 if (TemplateParameterList *TemplateParams = 16307 MatchTemplateParametersToScopeSpecifier( 16308 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 16309 IsMemberSpecialization, Invalid)) { 16310 if (TemplateParams->size() > 0) { 16311 // This is a declaration of a class template. 16312 if (Invalid) 16313 return nullptr; 16314 16315 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 16316 NameLoc, Attr, TemplateParams, AS_public, 16317 /*ModulePrivateLoc=*/SourceLocation(), 16318 FriendLoc, TempParamLists.size() - 1, 16319 TempParamLists.data()).get(); 16320 } else { 16321 // The "template<>" header is extraneous. 16322 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16323 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16324 IsMemberSpecialization = true; 16325 } 16326 } 16327 16328 if (Invalid) return nullptr; 16329 16330 bool isAllExplicitSpecializations = true; 16331 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 16332 if (TempParamLists[I]->size()) { 16333 isAllExplicitSpecializations = false; 16334 break; 16335 } 16336 } 16337 16338 // FIXME: don't ignore attributes. 16339 16340 // If it's explicit specializations all the way down, just forget 16341 // about the template header and build an appropriate non-templated 16342 // friend. TODO: for source fidelity, remember the headers. 16343 if (isAllExplicitSpecializations) { 16344 if (SS.isEmpty()) { 16345 bool Owned = false; 16346 bool IsDependent = false; 16347 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 16348 Attr, AS_public, 16349 /*ModulePrivateLoc=*/SourceLocation(), 16350 MultiTemplateParamsArg(), Owned, IsDependent, 16351 /*ScopedEnumKWLoc=*/SourceLocation(), 16352 /*ScopedEnumUsesClassTag=*/false, 16353 /*UnderlyingType=*/TypeResult(), 16354 /*IsTypeSpecifier=*/false, 16355 /*IsTemplateParamOrArg=*/false); 16356 } 16357 16358 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 16359 ElaboratedTypeKeyword Keyword 16360 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16361 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 16362 *Name, NameLoc); 16363 if (T.isNull()) 16364 return nullptr; 16365 16366 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16367 if (isa<DependentNameType>(T)) { 16368 DependentNameTypeLoc TL = 16369 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16370 TL.setElaboratedKeywordLoc(TagLoc); 16371 TL.setQualifierLoc(QualifierLoc); 16372 TL.setNameLoc(NameLoc); 16373 } else { 16374 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 16375 TL.setElaboratedKeywordLoc(TagLoc); 16376 TL.setQualifierLoc(QualifierLoc); 16377 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 16378 } 16379 16380 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16381 TSI, FriendLoc, TempParamLists); 16382 Friend->setAccess(AS_public); 16383 CurContext->addDecl(Friend); 16384 return Friend; 16385 } 16386 16387 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 16388 16389 16390 16391 // Handle the case of a templated-scope friend class. e.g. 16392 // template <class T> class A<T>::B; 16393 // FIXME: we don't support these right now. 16394 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 16395 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 16396 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16397 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 16398 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16399 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16400 TL.setElaboratedKeywordLoc(TagLoc); 16401 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 16402 TL.setNameLoc(NameLoc); 16403 16404 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16405 TSI, FriendLoc, TempParamLists); 16406 Friend->setAccess(AS_public); 16407 Friend->setUnsupportedFriend(true); 16408 CurContext->addDecl(Friend); 16409 return Friend; 16410 } 16411 16412 /// Handle a friend type declaration. This works in tandem with 16413 /// ActOnTag. 16414 /// 16415 /// Notes on friend class templates: 16416 /// 16417 /// We generally treat friend class declarations as if they were 16418 /// declaring a class. So, for example, the elaborated type specifier 16419 /// in a friend declaration is required to obey the restrictions of a 16420 /// class-head (i.e. no typedefs in the scope chain), template 16421 /// parameters are required to match up with simple template-ids, &c. 16422 /// However, unlike when declaring a template specialization, it's 16423 /// okay to refer to a template specialization without an empty 16424 /// template parameter declaration, e.g. 16425 /// friend class A<T>::B<unsigned>; 16426 /// We permit this as a special case; if there are any template 16427 /// parameters present at all, require proper matching, i.e. 16428 /// template <> template \<class T> friend class A<int>::B; 16429 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 16430 MultiTemplateParamsArg TempParams) { 16431 SourceLocation Loc = DS.getBeginLoc(); 16432 16433 assert(DS.isFriendSpecified()); 16434 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16435 16436 // C++ [class.friend]p3: 16437 // A friend declaration that does not declare a function shall have one of 16438 // the following forms: 16439 // friend elaborated-type-specifier ; 16440 // friend simple-type-specifier ; 16441 // friend typename-specifier ; 16442 // 16443 // Any declaration with a type qualifier does not have that form. (It's 16444 // legal to specify a qualified type as a friend, you just can't write the 16445 // keywords.) 16446 if (DS.getTypeQualifiers()) { 16447 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 16448 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 16449 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 16450 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 16451 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 16452 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 16453 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 16454 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 16455 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 16456 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 16457 } 16458 16459 // Try to convert the decl specifier to a type. This works for 16460 // friend templates because ActOnTag never produces a ClassTemplateDecl 16461 // for a TUK_Friend. 16462 Declarator TheDeclarator(DS, DeclaratorContext::Member); 16463 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 16464 QualType T = TSI->getType(); 16465 if (TheDeclarator.isInvalidType()) 16466 return nullptr; 16467 16468 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 16469 return nullptr; 16470 16471 // This is definitely an error in C++98. It's probably meant to 16472 // be forbidden in C++0x, too, but the specification is just 16473 // poorly written. 16474 // 16475 // The problem is with declarations like the following: 16476 // template <T> friend A<T>::foo; 16477 // where deciding whether a class C is a friend or not now hinges 16478 // on whether there exists an instantiation of A that causes 16479 // 'foo' to equal C. There are restrictions on class-heads 16480 // (which we declare (by fiat) elaborated friend declarations to 16481 // be) that makes this tractable. 16482 // 16483 // FIXME: handle "template <> friend class A<T>;", which 16484 // is possibly well-formed? Who even knows? 16485 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 16486 Diag(Loc, diag::err_tagless_friend_type_template) 16487 << DS.getSourceRange(); 16488 return nullptr; 16489 } 16490 16491 // C++98 [class.friend]p1: A friend of a class is a function 16492 // or class that is not a member of the class . . . 16493 // This is fixed in DR77, which just barely didn't make the C++03 16494 // deadline. It's also a very silly restriction that seriously 16495 // affects inner classes and which nobody else seems to implement; 16496 // thus we never diagnose it, not even in -pedantic. 16497 // 16498 // But note that we could warn about it: it's always useless to 16499 // friend one of your own members (it's not, however, worthless to 16500 // friend a member of an arbitrary specialization of your template). 16501 16502 Decl *D; 16503 if (!TempParams.empty()) 16504 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 16505 TempParams, 16506 TSI, 16507 DS.getFriendSpecLoc()); 16508 else 16509 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 16510 16511 if (!D) 16512 return nullptr; 16513 16514 D->setAccess(AS_public); 16515 CurContext->addDecl(D); 16516 16517 return D; 16518 } 16519 16520 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 16521 MultiTemplateParamsArg TemplateParams) { 16522 const DeclSpec &DS = D.getDeclSpec(); 16523 16524 assert(DS.isFriendSpecified()); 16525 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16526 16527 SourceLocation Loc = D.getIdentifierLoc(); 16528 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16529 16530 // C++ [class.friend]p1 16531 // A friend of a class is a function or class.... 16532 // Note that this sees through typedefs, which is intended. 16533 // It *doesn't* see through dependent types, which is correct 16534 // according to [temp.arg.type]p3: 16535 // If a declaration acquires a function type through a 16536 // type dependent on a template-parameter and this causes 16537 // a declaration that does not use the syntactic form of a 16538 // function declarator to have a function type, the program 16539 // is ill-formed. 16540 if (!TInfo->getType()->isFunctionType()) { 16541 Diag(Loc, diag::err_unexpected_friend); 16542 16543 // It might be worthwhile to try to recover by creating an 16544 // appropriate declaration. 16545 return nullptr; 16546 } 16547 16548 // C++ [namespace.memdef]p3 16549 // - If a friend declaration in a non-local class first declares a 16550 // class or function, the friend class or function is a member 16551 // of the innermost enclosing namespace. 16552 // - The name of the friend is not found by simple name lookup 16553 // until a matching declaration is provided in that namespace 16554 // scope (either before or after the class declaration granting 16555 // friendship). 16556 // - If a friend function is called, its name may be found by the 16557 // name lookup that considers functions from namespaces and 16558 // classes associated with the types of the function arguments. 16559 // - When looking for a prior declaration of a class or a function 16560 // declared as a friend, scopes outside the innermost enclosing 16561 // namespace scope are not considered. 16562 16563 CXXScopeSpec &SS = D.getCXXScopeSpec(); 16564 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 16565 assert(NameInfo.getName()); 16566 16567 // Check for unexpanded parameter packs. 16568 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 16569 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 16570 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 16571 return nullptr; 16572 16573 // The context we found the declaration in, or in which we should 16574 // create the declaration. 16575 DeclContext *DC; 16576 Scope *DCScope = S; 16577 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 16578 ForExternalRedeclaration); 16579 16580 // There are five cases here. 16581 // - There's no scope specifier and we're in a local class. Only look 16582 // for functions declared in the immediately-enclosing block scope. 16583 // We recover from invalid scope qualifiers as if they just weren't there. 16584 FunctionDecl *FunctionContainingLocalClass = nullptr; 16585 if ((SS.isInvalid() || !SS.isSet()) && 16586 (FunctionContainingLocalClass = 16587 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 16588 // C++11 [class.friend]p11: 16589 // If a friend declaration appears in a local class and the name 16590 // specified is an unqualified name, a prior declaration is 16591 // looked up without considering scopes that are outside the 16592 // innermost enclosing non-class scope. For a friend function 16593 // declaration, if there is no prior declaration, the program is 16594 // ill-formed. 16595 16596 // Find the innermost enclosing non-class scope. This is the block 16597 // scope containing the local class definition (or for a nested class, 16598 // the outer local class). 16599 DCScope = S->getFnParent(); 16600 16601 // Look up the function name in the scope. 16602 Previous.clear(LookupLocalFriendName); 16603 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 16604 16605 if (!Previous.empty()) { 16606 // All possible previous declarations must have the same context: 16607 // either they were declared at block scope or they are members of 16608 // one of the enclosing local classes. 16609 DC = Previous.getRepresentativeDecl()->getDeclContext(); 16610 } else { 16611 // This is ill-formed, but provide the context that we would have 16612 // declared the function in, if we were permitted to, for error recovery. 16613 DC = FunctionContainingLocalClass; 16614 } 16615 adjustContextForLocalExternDecl(DC); 16616 16617 // C++ [class.friend]p6: 16618 // A function can be defined in a friend declaration of a class if and 16619 // only if the class is a non-local class (9.8), the function name is 16620 // unqualified, and the function has namespace scope. 16621 if (D.isFunctionDefinition()) { 16622 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 16623 } 16624 16625 // - There's no scope specifier, in which case we just go to the 16626 // appropriate scope and look for a function or function template 16627 // there as appropriate. 16628 } else if (SS.isInvalid() || !SS.isSet()) { 16629 // C++11 [namespace.memdef]p3: 16630 // If the name in a friend declaration is neither qualified nor 16631 // a template-id and the declaration is a function or an 16632 // elaborated-type-specifier, the lookup to determine whether 16633 // the entity has been previously declared shall not consider 16634 // any scopes outside the innermost enclosing namespace. 16635 bool isTemplateId = 16636 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 16637 16638 // Find the appropriate context according to the above. 16639 DC = CurContext; 16640 16641 // Skip class contexts. If someone can cite chapter and verse 16642 // for this behavior, that would be nice --- it's what GCC and 16643 // EDG do, and it seems like a reasonable intent, but the spec 16644 // really only says that checks for unqualified existing 16645 // declarations should stop at the nearest enclosing namespace, 16646 // not that they should only consider the nearest enclosing 16647 // namespace. 16648 while (DC->isRecord()) 16649 DC = DC->getParent(); 16650 16651 DeclContext *LookupDC = DC; 16652 while (LookupDC->isTransparentContext()) 16653 LookupDC = LookupDC->getParent(); 16654 16655 while (true) { 16656 LookupQualifiedName(Previous, LookupDC); 16657 16658 if (!Previous.empty()) { 16659 DC = LookupDC; 16660 break; 16661 } 16662 16663 if (isTemplateId) { 16664 if (isa<TranslationUnitDecl>(LookupDC)) break; 16665 } else { 16666 if (LookupDC->isFileContext()) break; 16667 } 16668 LookupDC = LookupDC->getParent(); 16669 } 16670 16671 DCScope = getScopeForDeclContext(S, DC); 16672 16673 // - There's a non-dependent scope specifier, in which case we 16674 // compute it and do a previous lookup there for a function 16675 // or function template. 16676 } else if (!SS.getScopeRep()->isDependent()) { 16677 DC = computeDeclContext(SS); 16678 if (!DC) return nullptr; 16679 16680 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 16681 16682 LookupQualifiedName(Previous, DC); 16683 16684 // C++ [class.friend]p1: A friend of a class is a function or 16685 // class that is not a member of the class . . . 16686 if (DC->Equals(CurContext)) 16687 Diag(DS.getFriendSpecLoc(), 16688 getLangOpts().CPlusPlus11 ? 16689 diag::warn_cxx98_compat_friend_is_member : 16690 diag::err_friend_is_member); 16691 16692 if (D.isFunctionDefinition()) { 16693 // C++ [class.friend]p6: 16694 // A function can be defined in a friend declaration of a class if and 16695 // only if the class is a non-local class (9.8), the function name is 16696 // unqualified, and the function has namespace scope. 16697 // 16698 // FIXME: We should only do this if the scope specifier names the 16699 // innermost enclosing namespace; otherwise the fixit changes the 16700 // meaning of the code. 16701 SemaDiagnosticBuilder DB 16702 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 16703 16704 DB << SS.getScopeRep(); 16705 if (DC->isFileContext()) 16706 DB << FixItHint::CreateRemoval(SS.getRange()); 16707 SS.clear(); 16708 } 16709 16710 // - There's a scope specifier that does not match any template 16711 // parameter lists, in which case we use some arbitrary context, 16712 // create a method or method template, and wait for instantiation. 16713 // - There's a scope specifier that does match some template 16714 // parameter lists, which we don't handle right now. 16715 } else { 16716 if (D.isFunctionDefinition()) { 16717 // C++ [class.friend]p6: 16718 // A function can be defined in a friend declaration of a class if and 16719 // only if the class is a non-local class (9.8), the function name is 16720 // unqualified, and the function has namespace scope. 16721 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 16722 << SS.getScopeRep(); 16723 } 16724 16725 DC = CurContext; 16726 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 16727 } 16728 16729 if (!DC->isRecord()) { 16730 int DiagArg = -1; 16731 switch (D.getName().getKind()) { 16732 case UnqualifiedIdKind::IK_ConstructorTemplateId: 16733 case UnqualifiedIdKind::IK_ConstructorName: 16734 DiagArg = 0; 16735 break; 16736 case UnqualifiedIdKind::IK_DestructorName: 16737 DiagArg = 1; 16738 break; 16739 case UnqualifiedIdKind::IK_ConversionFunctionId: 16740 DiagArg = 2; 16741 break; 16742 case UnqualifiedIdKind::IK_DeductionGuideName: 16743 DiagArg = 3; 16744 break; 16745 case UnqualifiedIdKind::IK_Identifier: 16746 case UnqualifiedIdKind::IK_ImplicitSelfParam: 16747 case UnqualifiedIdKind::IK_LiteralOperatorId: 16748 case UnqualifiedIdKind::IK_OperatorFunctionId: 16749 case UnqualifiedIdKind::IK_TemplateId: 16750 break; 16751 } 16752 // This implies that it has to be an operator or function. 16753 if (DiagArg >= 0) { 16754 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 16755 return nullptr; 16756 } 16757 } 16758 16759 // FIXME: This is an egregious hack to cope with cases where the scope stack 16760 // does not contain the declaration context, i.e., in an out-of-line 16761 // definition of a class. 16762 Scope FakeDCScope(S, Scope::DeclScope, Diags); 16763 if (!DCScope) { 16764 FakeDCScope.setEntity(DC); 16765 DCScope = &FakeDCScope; 16766 } 16767 16768 bool AddToScope = true; 16769 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 16770 TemplateParams, AddToScope); 16771 if (!ND) return nullptr; 16772 16773 assert(ND->getLexicalDeclContext() == CurContext); 16774 16775 // If we performed typo correction, we might have added a scope specifier 16776 // and changed the decl context. 16777 DC = ND->getDeclContext(); 16778 16779 // Add the function declaration to the appropriate lookup tables, 16780 // adjusting the redeclarations list as necessary. We don't 16781 // want to do this yet if the friending class is dependent. 16782 // 16783 // Also update the scope-based lookup if the target context's 16784 // lookup context is in lexical scope. 16785 if (!CurContext->isDependentContext()) { 16786 DC = DC->getRedeclContext(); 16787 DC->makeDeclVisibleInContext(ND); 16788 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16789 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 16790 } 16791 16792 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 16793 D.getIdentifierLoc(), ND, 16794 DS.getFriendSpecLoc()); 16795 FrD->setAccess(AS_public); 16796 CurContext->addDecl(FrD); 16797 16798 if (ND->isInvalidDecl()) { 16799 FrD->setInvalidDecl(); 16800 } else { 16801 if (DC->isRecord()) CheckFriendAccess(ND); 16802 16803 FunctionDecl *FD; 16804 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 16805 FD = FTD->getTemplatedDecl(); 16806 else 16807 FD = cast<FunctionDecl>(ND); 16808 16809 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 16810 // default argument expression, that declaration shall be a definition 16811 // and shall be the only declaration of the function or function 16812 // template in the translation unit. 16813 if (functionDeclHasDefaultArgument(FD)) { 16814 // We can't look at FD->getPreviousDecl() because it may not have been set 16815 // if we're in a dependent context. If the function is known to be a 16816 // redeclaration, we will have narrowed Previous down to the right decl. 16817 if (D.isRedeclaration()) { 16818 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 16819 Diag(Previous.getRepresentativeDecl()->getLocation(), 16820 diag::note_previous_declaration); 16821 } else if (!D.isFunctionDefinition()) 16822 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 16823 } 16824 16825 // Mark templated-scope function declarations as unsupported. 16826 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 16827 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 16828 << SS.getScopeRep() << SS.getRange() 16829 << cast<CXXRecordDecl>(CurContext); 16830 FrD->setUnsupportedFriend(true); 16831 } 16832 } 16833 16834 warnOnReservedIdentifier(ND); 16835 16836 return ND; 16837 } 16838 16839 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 16840 AdjustDeclIfTemplate(Dcl); 16841 16842 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 16843 if (!Fn) { 16844 Diag(DelLoc, diag::err_deleted_non_function); 16845 return; 16846 } 16847 16848 // Deleted function does not have a body. 16849 Fn->setWillHaveBody(false); 16850 16851 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 16852 // Don't consider the implicit declaration we generate for explicit 16853 // specializations. FIXME: Do not generate these implicit declarations. 16854 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 16855 Prev->getPreviousDecl()) && 16856 !Prev->isDefined()) { 16857 Diag(DelLoc, diag::err_deleted_decl_not_first); 16858 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 16859 Prev->isImplicit() ? diag::note_previous_implicit_declaration 16860 : diag::note_previous_declaration); 16861 // We can't recover from this; the declaration might have already 16862 // been used. 16863 Fn->setInvalidDecl(); 16864 return; 16865 } 16866 16867 // To maintain the invariant that functions are only deleted on their first 16868 // declaration, mark the implicitly-instantiated declaration of the 16869 // explicitly-specialized function as deleted instead of marking the 16870 // instantiated redeclaration. 16871 Fn = Fn->getCanonicalDecl(); 16872 } 16873 16874 // dllimport/dllexport cannot be deleted. 16875 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 16876 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 16877 Fn->setInvalidDecl(); 16878 } 16879 16880 // C++11 [basic.start.main]p3: 16881 // A program that defines main as deleted [...] is ill-formed. 16882 if (Fn->isMain()) 16883 Diag(DelLoc, diag::err_deleted_main); 16884 16885 // C++11 [dcl.fct.def.delete]p4: 16886 // A deleted function is implicitly inline. 16887 Fn->setImplicitlyInline(); 16888 Fn->setDeletedAsWritten(); 16889 } 16890 16891 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 16892 if (!Dcl || Dcl->isInvalidDecl()) 16893 return; 16894 16895 auto *FD = dyn_cast<FunctionDecl>(Dcl); 16896 if (!FD) { 16897 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 16898 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 16899 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 16900 return; 16901 } 16902 } 16903 16904 Diag(DefaultLoc, diag::err_default_special_members) 16905 << getLangOpts().CPlusPlus20; 16906 return; 16907 } 16908 16909 // Reject if this can't possibly be a defaultable function. 16910 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 16911 if (!DefKind && 16912 // A dependent function that doesn't locally look defaultable can 16913 // still instantiate to a defaultable function if it's a constructor 16914 // or assignment operator. 16915 (!FD->isDependentContext() || 16916 (!isa<CXXConstructorDecl>(FD) && 16917 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 16918 Diag(DefaultLoc, diag::err_default_special_members) 16919 << getLangOpts().CPlusPlus20; 16920 return; 16921 } 16922 16923 if (DefKind.isComparison() && 16924 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 16925 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class) 16926 << (int)DefKind.asComparison(); 16927 return; 16928 } 16929 16930 // Issue compatibility warning. We already warned if the operator is 16931 // 'operator<=>' when parsing the '<=>' token. 16932 if (DefKind.isComparison() && 16933 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 16934 Diag(DefaultLoc, getLangOpts().CPlusPlus20 16935 ? diag::warn_cxx17_compat_defaulted_comparison 16936 : diag::ext_defaulted_comparison); 16937 } 16938 16939 FD->setDefaulted(); 16940 FD->setExplicitlyDefaulted(); 16941 16942 // Defer checking functions that are defaulted in a dependent context. 16943 if (FD->isDependentContext()) 16944 return; 16945 16946 // Unset that we will have a body for this function. We might not, 16947 // if it turns out to be trivial, and we don't need this marking now 16948 // that we've marked it as defaulted. 16949 FD->setWillHaveBody(false); 16950 16951 // If this definition appears within the record, do the checking when 16952 // the record is complete. This is always the case for a defaulted 16953 // comparison. 16954 if (DefKind.isComparison()) 16955 return; 16956 auto *MD = cast<CXXMethodDecl>(FD); 16957 16958 const FunctionDecl *Primary = FD; 16959 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 16960 // Ask the template instantiation pattern that actually had the 16961 // '= default' on it. 16962 Primary = Pattern; 16963 16964 // If the method was defaulted on its first declaration, we will have 16965 // already performed the checking in CheckCompletedCXXClass. Such a 16966 // declaration doesn't trigger an implicit definition. 16967 if (Primary->getCanonicalDecl()->isDefaulted()) 16968 return; 16969 16970 // FIXME: Once we support defining comparisons out of class, check for a 16971 // defaulted comparison here. 16972 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 16973 MD->setInvalidDecl(); 16974 else 16975 DefineDefaultedFunction(*this, MD, DefaultLoc); 16976 } 16977 16978 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 16979 for (Stmt *SubStmt : S->children()) { 16980 if (!SubStmt) 16981 continue; 16982 if (isa<ReturnStmt>(SubStmt)) 16983 Self.Diag(SubStmt->getBeginLoc(), 16984 diag::err_return_in_constructor_handler); 16985 if (!isa<Expr>(SubStmt)) 16986 SearchForReturnInStmt(Self, SubStmt); 16987 } 16988 } 16989 16990 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 16991 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 16992 CXXCatchStmt *Handler = TryBlock->getHandler(I); 16993 SearchForReturnInStmt(*this, Handler); 16994 } 16995 } 16996 16997 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 16998 const CXXMethodDecl *Old) { 16999 const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); 17000 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); 17001 17002 if (OldFT->hasExtParameterInfos()) { 17003 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 17004 // A parameter of the overriding method should be annotated with noescape 17005 // if the corresponding parameter of the overridden method is annotated. 17006 if (OldFT->getExtParameterInfo(I).isNoEscape() && 17007 !NewFT->getExtParameterInfo(I).isNoEscape()) { 17008 Diag(New->getParamDecl(I)->getLocation(), 17009 diag::warn_overriding_method_missing_noescape); 17010 Diag(Old->getParamDecl(I)->getLocation(), 17011 diag::note_overridden_marked_noescape); 17012 } 17013 } 17014 17015 // Virtual overrides must have the same code_seg. 17016 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 17017 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 17018 if ((NewCSA || OldCSA) && 17019 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 17020 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 17021 Diag(Old->getLocation(), diag::note_previous_declaration); 17022 return true; 17023 } 17024 17025 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 17026 17027 // If the calling conventions match, everything is fine 17028 if (NewCC == OldCC) 17029 return false; 17030 17031 // If the calling conventions mismatch because the new function is static, 17032 // suppress the calling convention mismatch error; the error about static 17033 // function override (err_static_overrides_virtual from 17034 // Sema::CheckFunctionDeclaration) is more clear. 17035 if (New->getStorageClass() == SC_Static) 17036 return false; 17037 17038 Diag(New->getLocation(), 17039 diag::err_conflicting_overriding_cc_attributes) 17040 << New->getDeclName() << New->getType() << Old->getType(); 17041 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 17042 return true; 17043 } 17044 17045 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 17046 const CXXMethodDecl *Old) { 17047 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); 17048 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); 17049 17050 if (Context.hasSameType(NewTy, OldTy) || 17051 NewTy->isDependentType() || OldTy->isDependentType()) 17052 return false; 17053 17054 // Check if the return types are covariant 17055 QualType NewClassTy, OldClassTy; 17056 17057 /// Both types must be pointers or references to classes. 17058 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 17059 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 17060 NewClassTy = NewPT->getPointeeType(); 17061 OldClassTy = OldPT->getPointeeType(); 17062 } 17063 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 17064 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 17065 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 17066 NewClassTy = NewRT->getPointeeType(); 17067 OldClassTy = OldRT->getPointeeType(); 17068 } 17069 } 17070 } 17071 17072 // The return types aren't either both pointers or references to a class type. 17073 if (NewClassTy.isNull()) { 17074 Diag(New->getLocation(), 17075 diag::err_different_return_type_for_overriding_virtual_function) 17076 << New->getDeclName() << NewTy << OldTy 17077 << New->getReturnTypeSourceRange(); 17078 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17079 << Old->getReturnTypeSourceRange(); 17080 17081 return true; 17082 } 17083 17084 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 17085 // C++14 [class.virtual]p8: 17086 // If the class type in the covariant return type of D::f differs from 17087 // that of B::f, the class type in the return type of D::f shall be 17088 // complete at the point of declaration of D::f or shall be the class 17089 // type D. 17090 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 17091 if (!RT->isBeingDefined() && 17092 RequireCompleteType(New->getLocation(), NewClassTy, 17093 diag::err_covariant_return_incomplete, 17094 New->getDeclName())) 17095 return true; 17096 } 17097 17098 // Check if the new class derives from the old class. 17099 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 17100 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 17101 << New->getDeclName() << NewTy << OldTy 17102 << New->getReturnTypeSourceRange(); 17103 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17104 << Old->getReturnTypeSourceRange(); 17105 return true; 17106 } 17107 17108 // Check if we the conversion from derived to base is valid. 17109 if (CheckDerivedToBaseConversion( 17110 NewClassTy, OldClassTy, 17111 diag::err_covariant_return_inaccessible_base, 17112 diag::err_covariant_return_ambiguous_derived_to_base_conv, 17113 New->getLocation(), New->getReturnTypeSourceRange(), 17114 New->getDeclName(), nullptr)) { 17115 // FIXME: this note won't trigger for delayed access control 17116 // diagnostics, and it's impossible to get an undelayed error 17117 // here from access control during the original parse because 17118 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 17119 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17120 << Old->getReturnTypeSourceRange(); 17121 return true; 17122 } 17123 } 17124 17125 // The qualifiers of the return types must be the same. 17126 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 17127 Diag(New->getLocation(), 17128 diag::err_covariant_return_type_different_qualifications) 17129 << New->getDeclName() << NewTy << OldTy 17130 << New->getReturnTypeSourceRange(); 17131 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17132 << Old->getReturnTypeSourceRange(); 17133 return true; 17134 } 17135 17136 17137 // The new class type must have the same or less qualifiers as the old type. 17138 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 17139 Diag(New->getLocation(), 17140 diag::err_covariant_return_type_class_type_more_qualified) 17141 << New->getDeclName() << NewTy << OldTy 17142 << New->getReturnTypeSourceRange(); 17143 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17144 << Old->getReturnTypeSourceRange(); 17145 return true; 17146 } 17147 17148 return false; 17149 } 17150 17151 /// Mark the given method pure. 17152 /// 17153 /// \param Method the method to be marked pure. 17154 /// 17155 /// \param InitRange the source range that covers the "0" initializer. 17156 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 17157 SourceLocation EndLoc = InitRange.getEnd(); 17158 if (EndLoc.isValid()) 17159 Method->setRangeEnd(EndLoc); 17160 17161 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 17162 Method->setPure(); 17163 return false; 17164 } 17165 17166 if (!Method->isInvalidDecl()) 17167 Diag(Method->getLocation(), diag::err_non_virtual_pure) 17168 << Method->getDeclName() << InitRange; 17169 return true; 17170 } 17171 17172 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 17173 if (D->getFriendObjectKind()) 17174 Diag(D->getLocation(), diag::err_pure_friend); 17175 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 17176 CheckPureMethod(M, ZeroLoc); 17177 else 17178 Diag(D->getLocation(), diag::err_illegal_initializer); 17179 } 17180 17181 /// Determine whether the given declaration is a global variable or 17182 /// static data member. 17183 static bool isNonlocalVariable(const Decl *D) { 17184 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 17185 return Var->hasGlobalStorage(); 17186 17187 return false; 17188 } 17189 17190 /// Invoked when we are about to parse an initializer for the declaration 17191 /// 'Dcl'. 17192 /// 17193 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 17194 /// static data member of class X, names should be looked up in the scope of 17195 /// class X. If the declaration had a scope specifier, a scope will have 17196 /// been created and passed in for this purpose. Otherwise, S will be null. 17197 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 17198 // If there is no declaration, there was an error parsing it. 17199 if (!D || D->isInvalidDecl()) 17200 return; 17201 17202 // We will always have a nested name specifier here, but this declaration 17203 // might not be out of line if the specifier names the current namespace: 17204 // extern int n; 17205 // int ::n = 0; 17206 if (S && D->isOutOfLine()) 17207 EnterDeclaratorContext(S, D->getDeclContext()); 17208 17209 // If we are parsing the initializer for a static data member, push a 17210 // new expression evaluation context that is associated with this static 17211 // data member. 17212 if (isNonlocalVariable(D)) 17213 PushExpressionEvaluationContext( 17214 ExpressionEvaluationContext::PotentiallyEvaluated, D); 17215 } 17216 17217 /// Invoked after we are finished parsing an initializer for the declaration D. 17218 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 17219 // If there is no declaration, there was an error parsing it. 17220 if (!D || D->isInvalidDecl()) 17221 return; 17222 17223 if (isNonlocalVariable(D)) 17224 PopExpressionEvaluationContext(); 17225 17226 if (S && D->isOutOfLine()) 17227 ExitDeclaratorContext(S); 17228 } 17229 17230 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 17231 /// C++ if/switch/while/for statement. 17232 /// e.g: "if (int x = f()) {...}" 17233 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 17234 // C++ 6.4p2: 17235 // The declarator shall not specify a function or an array. 17236 // The type-specifier-seq shall not contain typedef and shall not declare a 17237 // new class or enumeration. 17238 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 17239 "Parser allowed 'typedef' as storage class of condition decl."); 17240 17241 Decl *Dcl = ActOnDeclarator(S, D); 17242 if (!Dcl) 17243 return true; 17244 17245 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 17246 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 17247 << D.getSourceRange(); 17248 return true; 17249 } 17250 17251 return Dcl; 17252 } 17253 17254 void Sema::LoadExternalVTableUses() { 17255 if (!ExternalSource) 17256 return; 17257 17258 SmallVector<ExternalVTableUse, 4> VTables; 17259 ExternalSource->ReadUsedVTables(VTables); 17260 SmallVector<VTableUse, 4> NewUses; 17261 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 17262 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 17263 = VTablesUsed.find(VTables[I].Record); 17264 // Even if a definition wasn't required before, it may be required now. 17265 if (Pos != VTablesUsed.end()) { 17266 if (!Pos->second && VTables[I].DefinitionRequired) 17267 Pos->second = true; 17268 continue; 17269 } 17270 17271 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 17272 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 17273 } 17274 17275 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 17276 } 17277 17278 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 17279 bool DefinitionRequired) { 17280 // Ignore any vtable uses in unevaluated operands or for classes that do 17281 // not have a vtable. 17282 if (!Class->isDynamicClass() || Class->isDependentContext() || 17283 CurContext->isDependentContext() || isUnevaluatedContext()) 17284 return; 17285 // Do not mark as used if compiling for the device outside of the target 17286 // region. 17287 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 17288 !isInOpenMPDeclareTargetContext() && 17289 !isInOpenMPTargetExecutionDirective()) { 17290 if (!DefinitionRequired) 17291 MarkVirtualMembersReferenced(Loc, Class); 17292 return; 17293 } 17294 17295 // Try to insert this class into the map. 17296 LoadExternalVTableUses(); 17297 Class = Class->getCanonicalDecl(); 17298 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 17299 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 17300 if (!Pos.second) { 17301 // If we already had an entry, check to see if we are promoting this vtable 17302 // to require a definition. If so, we need to reappend to the VTableUses 17303 // list, since we may have already processed the first entry. 17304 if (DefinitionRequired && !Pos.first->second) { 17305 Pos.first->second = true; 17306 } else { 17307 // Otherwise, we can early exit. 17308 return; 17309 } 17310 } else { 17311 // The Microsoft ABI requires that we perform the destructor body 17312 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 17313 // the deleting destructor is emitted with the vtable, not with the 17314 // destructor definition as in the Itanium ABI. 17315 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17316 CXXDestructorDecl *DD = Class->getDestructor(); 17317 if (DD && DD->isVirtual() && !DD->isDeleted()) { 17318 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 17319 // If this is an out-of-line declaration, marking it referenced will 17320 // not do anything. Manually call CheckDestructor to look up operator 17321 // delete(). 17322 ContextRAII SavedContext(*this, DD); 17323 CheckDestructor(DD); 17324 } else { 17325 MarkFunctionReferenced(Loc, Class->getDestructor()); 17326 } 17327 } 17328 } 17329 } 17330 17331 // Local classes need to have their virtual members marked 17332 // immediately. For all other classes, we mark their virtual members 17333 // at the end of the translation unit. 17334 if (Class->isLocalClass()) 17335 MarkVirtualMembersReferenced(Loc, Class); 17336 else 17337 VTableUses.push_back(std::make_pair(Class, Loc)); 17338 } 17339 17340 bool Sema::DefineUsedVTables() { 17341 LoadExternalVTableUses(); 17342 if (VTableUses.empty()) 17343 return false; 17344 17345 // Note: The VTableUses vector could grow as a result of marking 17346 // the members of a class as "used", so we check the size each 17347 // time through the loop and prefer indices (which are stable) to 17348 // iterators (which are not). 17349 bool DefinedAnything = false; 17350 for (unsigned I = 0; I != VTableUses.size(); ++I) { 17351 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 17352 if (!Class) 17353 continue; 17354 TemplateSpecializationKind ClassTSK = 17355 Class->getTemplateSpecializationKind(); 17356 17357 SourceLocation Loc = VTableUses[I].second; 17358 17359 bool DefineVTable = true; 17360 17361 // If this class has a key function, but that key function is 17362 // defined in another translation unit, we don't need to emit the 17363 // vtable even though we're using it. 17364 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 17365 if (KeyFunction && !KeyFunction->hasBody()) { 17366 // The key function is in another translation unit. 17367 DefineVTable = false; 17368 TemplateSpecializationKind TSK = 17369 KeyFunction->getTemplateSpecializationKind(); 17370 assert(TSK != TSK_ExplicitInstantiationDefinition && 17371 TSK != TSK_ImplicitInstantiation && 17372 "Instantiations don't have key functions"); 17373 (void)TSK; 17374 } else if (!KeyFunction) { 17375 // If we have a class with no key function that is the subject 17376 // of an explicit instantiation declaration, suppress the 17377 // vtable; it will live with the explicit instantiation 17378 // definition. 17379 bool IsExplicitInstantiationDeclaration = 17380 ClassTSK == TSK_ExplicitInstantiationDeclaration; 17381 for (auto R : Class->redecls()) { 17382 TemplateSpecializationKind TSK 17383 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 17384 if (TSK == TSK_ExplicitInstantiationDeclaration) 17385 IsExplicitInstantiationDeclaration = true; 17386 else if (TSK == TSK_ExplicitInstantiationDefinition) { 17387 IsExplicitInstantiationDeclaration = false; 17388 break; 17389 } 17390 } 17391 17392 if (IsExplicitInstantiationDeclaration) 17393 DefineVTable = false; 17394 } 17395 17396 // The exception specifications for all virtual members may be needed even 17397 // if we are not providing an authoritative form of the vtable in this TU. 17398 // We may choose to emit it available_externally anyway. 17399 if (!DefineVTable) { 17400 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 17401 continue; 17402 } 17403 17404 // Mark all of the virtual members of this class as referenced, so 17405 // that we can build a vtable. Then, tell the AST consumer that a 17406 // vtable for this class is required. 17407 DefinedAnything = true; 17408 MarkVirtualMembersReferenced(Loc, Class); 17409 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 17410 if (VTablesUsed[Canonical]) 17411 Consumer.HandleVTable(Class); 17412 17413 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 17414 // no key function or the key function is inlined. Don't warn in C++ ABIs 17415 // that lack key functions, since the user won't be able to make one. 17416 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 17417 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 17418 const FunctionDecl *KeyFunctionDef = nullptr; 17419 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 17420 KeyFunctionDef->isInlined())) { 17421 Diag(Class->getLocation(), 17422 ClassTSK == TSK_ExplicitInstantiationDefinition 17423 ? diag::warn_weak_template_vtable 17424 : diag::warn_weak_vtable) 17425 << Class; 17426 } 17427 } 17428 } 17429 VTableUses.clear(); 17430 17431 return DefinedAnything; 17432 } 17433 17434 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 17435 const CXXRecordDecl *RD) { 17436 for (const auto *I : RD->methods()) 17437 if (I->isVirtual() && !I->isPure()) 17438 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 17439 } 17440 17441 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 17442 const CXXRecordDecl *RD, 17443 bool ConstexprOnly) { 17444 // Mark all functions which will appear in RD's vtable as used. 17445 CXXFinalOverriderMap FinalOverriders; 17446 RD->getFinalOverriders(FinalOverriders); 17447 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 17448 E = FinalOverriders.end(); 17449 I != E; ++I) { 17450 for (OverridingMethods::const_iterator OI = I->second.begin(), 17451 OE = I->second.end(); 17452 OI != OE; ++OI) { 17453 assert(OI->second.size() > 0 && "no final overrider"); 17454 CXXMethodDecl *Overrider = OI->second.front().Method; 17455 17456 // C++ [basic.def.odr]p2: 17457 // [...] A virtual member function is used if it is not pure. [...] 17458 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 17459 MarkFunctionReferenced(Loc, Overrider); 17460 } 17461 } 17462 17463 // Only classes that have virtual bases need a VTT. 17464 if (RD->getNumVBases() == 0) 17465 return; 17466 17467 for (const auto &I : RD->bases()) { 17468 const auto *Base = 17469 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 17470 if (Base->getNumVBases() == 0) 17471 continue; 17472 MarkVirtualMembersReferenced(Loc, Base); 17473 } 17474 } 17475 17476 /// SetIvarInitializers - This routine builds initialization ASTs for the 17477 /// Objective-C implementation whose ivars need be initialized. 17478 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 17479 if (!getLangOpts().CPlusPlus) 17480 return; 17481 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 17482 SmallVector<ObjCIvarDecl*, 8> ivars; 17483 CollectIvarsToConstructOrDestruct(OID, ivars); 17484 if (ivars.empty()) 17485 return; 17486 SmallVector<CXXCtorInitializer*, 32> AllToInit; 17487 for (unsigned i = 0; i < ivars.size(); i++) { 17488 FieldDecl *Field = ivars[i]; 17489 if (Field->isInvalidDecl()) 17490 continue; 17491 17492 CXXCtorInitializer *Member; 17493 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 17494 InitializationKind InitKind = 17495 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 17496 17497 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 17498 ExprResult MemberInit = 17499 InitSeq.Perform(*this, InitEntity, InitKind, None); 17500 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 17501 // Note, MemberInit could actually come back empty if no initialization 17502 // is required (e.g., because it would call a trivial default constructor) 17503 if (!MemberInit.get() || MemberInit.isInvalid()) 17504 continue; 17505 17506 Member = 17507 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 17508 SourceLocation(), 17509 MemberInit.getAs<Expr>(), 17510 SourceLocation()); 17511 AllToInit.push_back(Member); 17512 17513 // Be sure that the destructor is accessible and is marked as referenced. 17514 if (const RecordType *RecordTy = 17515 Context.getBaseElementType(Field->getType()) 17516 ->getAs<RecordType>()) { 17517 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 17518 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 17519 MarkFunctionReferenced(Field->getLocation(), Destructor); 17520 CheckDestructorAccess(Field->getLocation(), Destructor, 17521 PDiag(diag::err_access_dtor_ivar) 17522 << Context.getBaseElementType(Field->getType())); 17523 } 17524 } 17525 } 17526 ObjCImplementation->setIvarInitializers(Context, 17527 AllToInit.data(), AllToInit.size()); 17528 } 17529 } 17530 17531 static 17532 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 17533 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 17534 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 17535 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 17536 Sema &S) { 17537 if (Ctor->isInvalidDecl()) 17538 return; 17539 17540 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 17541 17542 // Target may not be determinable yet, for instance if this is a dependent 17543 // call in an uninstantiated template. 17544 if (Target) { 17545 const FunctionDecl *FNTarget = nullptr; 17546 (void)Target->hasBody(FNTarget); 17547 Target = const_cast<CXXConstructorDecl*>( 17548 cast_or_null<CXXConstructorDecl>(FNTarget)); 17549 } 17550 17551 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 17552 // Avoid dereferencing a null pointer here. 17553 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 17554 17555 if (!Current.insert(Canonical).second) 17556 return; 17557 17558 // We know that beyond here, we aren't chaining into a cycle. 17559 if (!Target || !Target->isDelegatingConstructor() || 17560 Target->isInvalidDecl() || Valid.count(TCanonical)) { 17561 Valid.insert(Current.begin(), Current.end()); 17562 Current.clear(); 17563 // We've hit a cycle. 17564 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 17565 Current.count(TCanonical)) { 17566 // If we haven't diagnosed this cycle yet, do so now. 17567 if (!Invalid.count(TCanonical)) { 17568 S.Diag((*Ctor->init_begin())->getSourceLocation(), 17569 diag::warn_delegating_ctor_cycle) 17570 << Ctor; 17571 17572 // Don't add a note for a function delegating directly to itself. 17573 if (TCanonical != Canonical) 17574 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 17575 17576 CXXConstructorDecl *C = Target; 17577 while (C->getCanonicalDecl() != Canonical) { 17578 const FunctionDecl *FNTarget = nullptr; 17579 (void)C->getTargetConstructor()->hasBody(FNTarget); 17580 assert(FNTarget && "Ctor cycle through bodiless function"); 17581 17582 C = const_cast<CXXConstructorDecl*>( 17583 cast<CXXConstructorDecl>(FNTarget)); 17584 S.Diag(C->getLocation(), diag::note_which_delegates_to); 17585 } 17586 } 17587 17588 Invalid.insert(Current.begin(), Current.end()); 17589 Current.clear(); 17590 } else { 17591 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 17592 } 17593 } 17594 17595 17596 void Sema::CheckDelegatingCtorCycles() { 17597 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 17598 17599 for (DelegatingCtorDeclsType::iterator 17600 I = DelegatingCtorDecls.begin(ExternalSource), 17601 E = DelegatingCtorDecls.end(); 17602 I != E; ++I) 17603 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 17604 17605 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 17606 (*CI)->setInvalidDecl(); 17607 } 17608 17609 namespace { 17610 /// AST visitor that finds references to the 'this' expression. 17611 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 17612 Sema &S; 17613 17614 public: 17615 explicit FindCXXThisExpr(Sema &S) : S(S) { } 17616 17617 bool VisitCXXThisExpr(CXXThisExpr *E) { 17618 S.Diag(E->getLocation(), diag::err_this_static_member_func) 17619 << E->isImplicit(); 17620 return false; 17621 } 17622 }; 17623 } 17624 17625 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 17626 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17627 if (!TSInfo) 17628 return false; 17629 17630 TypeLoc TL = TSInfo->getTypeLoc(); 17631 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17632 if (!ProtoTL) 17633 return false; 17634 17635 // C++11 [expr.prim.general]p3: 17636 // [The expression this] shall not appear before the optional 17637 // cv-qualifier-seq and it shall not appear within the declaration of a 17638 // static member function (although its type and value category are defined 17639 // within a static member function as they are within a non-static member 17640 // function). [ Note: this is because declaration matching does not occur 17641 // until the complete declarator is known. - end note ] 17642 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17643 FindCXXThisExpr Finder(*this); 17644 17645 // If the return type came after the cv-qualifier-seq, check it now. 17646 if (Proto->hasTrailingReturn() && 17647 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 17648 return true; 17649 17650 // Check the exception specification. 17651 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 17652 return true; 17653 17654 // Check the trailing requires clause 17655 if (Expr *E = Method->getTrailingRequiresClause()) 17656 if (!Finder.TraverseStmt(E)) 17657 return true; 17658 17659 return checkThisInStaticMemberFunctionAttributes(Method); 17660 } 17661 17662 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 17663 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17664 if (!TSInfo) 17665 return false; 17666 17667 TypeLoc TL = TSInfo->getTypeLoc(); 17668 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17669 if (!ProtoTL) 17670 return false; 17671 17672 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17673 FindCXXThisExpr Finder(*this); 17674 17675 switch (Proto->getExceptionSpecType()) { 17676 case EST_Unparsed: 17677 case EST_Uninstantiated: 17678 case EST_Unevaluated: 17679 case EST_BasicNoexcept: 17680 case EST_NoThrow: 17681 case EST_DynamicNone: 17682 case EST_MSAny: 17683 case EST_None: 17684 break; 17685 17686 case EST_DependentNoexcept: 17687 case EST_NoexceptFalse: 17688 case EST_NoexceptTrue: 17689 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 17690 return true; 17691 LLVM_FALLTHROUGH; 17692 17693 case EST_Dynamic: 17694 for (const auto &E : Proto->exceptions()) { 17695 if (!Finder.TraverseType(E)) 17696 return true; 17697 } 17698 break; 17699 } 17700 17701 return false; 17702 } 17703 17704 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 17705 FindCXXThisExpr Finder(*this); 17706 17707 // Check attributes. 17708 for (const auto *A : Method->attrs()) { 17709 // FIXME: This should be emitted by tblgen. 17710 Expr *Arg = nullptr; 17711 ArrayRef<Expr *> Args; 17712 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 17713 Arg = G->getArg(); 17714 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 17715 Arg = G->getArg(); 17716 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 17717 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 17718 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 17719 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 17720 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 17721 Arg = ETLF->getSuccessValue(); 17722 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 17723 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 17724 Arg = STLF->getSuccessValue(); 17725 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 17726 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 17727 Arg = LR->getArg(); 17728 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 17729 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 17730 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 17731 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17732 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 17733 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17734 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 17735 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17736 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 17737 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17738 17739 if (Arg && !Finder.TraverseStmt(Arg)) 17740 return true; 17741 17742 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 17743 if (!Finder.TraverseStmt(Args[I])) 17744 return true; 17745 } 17746 } 17747 17748 return false; 17749 } 17750 17751 void Sema::checkExceptionSpecification( 17752 bool IsTopLevel, ExceptionSpecificationType EST, 17753 ArrayRef<ParsedType> DynamicExceptions, 17754 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 17755 SmallVectorImpl<QualType> &Exceptions, 17756 FunctionProtoType::ExceptionSpecInfo &ESI) { 17757 Exceptions.clear(); 17758 ESI.Type = EST; 17759 if (EST == EST_Dynamic) { 17760 Exceptions.reserve(DynamicExceptions.size()); 17761 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 17762 // FIXME: Preserve type source info. 17763 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 17764 17765 if (IsTopLevel) { 17766 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 17767 collectUnexpandedParameterPacks(ET, Unexpanded); 17768 if (!Unexpanded.empty()) { 17769 DiagnoseUnexpandedParameterPacks( 17770 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 17771 Unexpanded); 17772 continue; 17773 } 17774 } 17775 17776 // Check that the type is valid for an exception spec, and 17777 // drop it if not. 17778 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 17779 Exceptions.push_back(ET); 17780 } 17781 ESI.Exceptions = Exceptions; 17782 return; 17783 } 17784 17785 if (isComputedNoexcept(EST)) { 17786 assert((NoexceptExpr->isTypeDependent() || 17787 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 17788 Context.BoolTy) && 17789 "Parser should have made sure that the expression is boolean"); 17790 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 17791 ESI.Type = EST_BasicNoexcept; 17792 return; 17793 } 17794 17795 ESI.NoexceptExpr = NoexceptExpr; 17796 return; 17797 } 17798 } 17799 17800 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 17801 ExceptionSpecificationType EST, 17802 SourceRange SpecificationRange, 17803 ArrayRef<ParsedType> DynamicExceptions, 17804 ArrayRef<SourceRange> DynamicExceptionRanges, 17805 Expr *NoexceptExpr) { 17806 if (!MethodD) 17807 return; 17808 17809 // Dig out the method we're referring to. 17810 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 17811 MethodD = FunTmpl->getTemplatedDecl(); 17812 17813 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 17814 if (!Method) 17815 return; 17816 17817 // Check the exception specification. 17818 llvm::SmallVector<QualType, 4> Exceptions; 17819 FunctionProtoType::ExceptionSpecInfo ESI; 17820 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 17821 DynamicExceptionRanges, NoexceptExpr, Exceptions, 17822 ESI); 17823 17824 // Update the exception specification on the function type. 17825 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 17826 17827 if (Method->isStatic()) 17828 checkThisInStaticMemberFunctionExceptionSpec(Method); 17829 17830 if (Method->isVirtual()) { 17831 // Check overrides, which we previously had to delay. 17832 for (const CXXMethodDecl *O : Method->overridden_methods()) 17833 CheckOverridingFunctionExceptionSpec(Method, O); 17834 } 17835 } 17836 17837 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 17838 /// 17839 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 17840 SourceLocation DeclStart, Declarator &D, 17841 Expr *BitWidth, 17842 InClassInitStyle InitStyle, 17843 AccessSpecifier AS, 17844 const ParsedAttr &MSPropertyAttr) { 17845 IdentifierInfo *II = D.getIdentifier(); 17846 if (!II) { 17847 Diag(DeclStart, diag::err_anonymous_property); 17848 return nullptr; 17849 } 17850 SourceLocation Loc = D.getIdentifierLoc(); 17851 17852 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17853 QualType T = TInfo->getType(); 17854 if (getLangOpts().CPlusPlus) { 17855 CheckExtraCXXDefaultArguments(D); 17856 17857 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 17858 UPPC_DataMemberType)) { 17859 D.setInvalidType(); 17860 T = Context.IntTy; 17861 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 17862 } 17863 } 17864 17865 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 17866 17867 if (D.getDeclSpec().isInlineSpecified()) 17868 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 17869 << getLangOpts().CPlusPlus17; 17870 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 17871 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 17872 diag::err_invalid_thread) 17873 << DeclSpec::getSpecifierName(TSCS); 17874 17875 // Check to see if this name was declared as a member previously 17876 NamedDecl *PrevDecl = nullptr; 17877 LookupResult Previous(*this, II, Loc, LookupMemberName, 17878 ForVisibleRedeclaration); 17879 LookupName(Previous, S); 17880 switch (Previous.getResultKind()) { 17881 case LookupResult::Found: 17882 case LookupResult::FoundUnresolvedValue: 17883 PrevDecl = Previous.getAsSingle<NamedDecl>(); 17884 break; 17885 17886 case LookupResult::FoundOverloaded: 17887 PrevDecl = Previous.getRepresentativeDecl(); 17888 break; 17889 17890 case LookupResult::NotFound: 17891 case LookupResult::NotFoundInCurrentInstantiation: 17892 case LookupResult::Ambiguous: 17893 break; 17894 } 17895 17896 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17897 // Maybe we will complain about the shadowed template parameter. 17898 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 17899 // Just pretend that we didn't see the previous declaration. 17900 PrevDecl = nullptr; 17901 } 17902 17903 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 17904 PrevDecl = nullptr; 17905 17906 SourceLocation TSSL = D.getBeginLoc(); 17907 MSPropertyDecl *NewPD = 17908 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 17909 MSPropertyAttr.getPropertyDataGetter(), 17910 MSPropertyAttr.getPropertyDataSetter()); 17911 ProcessDeclAttributes(TUScope, NewPD, D); 17912 NewPD->setAccess(AS); 17913 17914 if (NewPD->isInvalidDecl()) 17915 Record->setInvalidDecl(); 17916 17917 if (D.getDeclSpec().isModulePrivateSpecified()) 17918 NewPD->setModulePrivate(); 17919 17920 if (NewPD->isInvalidDecl() && PrevDecl) { 17921 // Don't introduce NewFD into scope; there's already something 17922 // with the same name in the same scope. 17923 } else if (II) { 17924 PushOnScopeChains(NewPD, S); 17925 } else 17926 Record->addDecl(NewPD); 17927 17928 return NewPD; 17929 } 17930 17931 void Sema::ActOnStartFunctionDeclarationDeclarator( 17932 Declarator &Declarator, unsigned TemplateParameterDepth) { 17933 auto &Info = InventedParameterInfos.emplace_back(); 17934 TemplateParameterList *ExplicitParams = nullptr; 17935 ArrayRef<TemplateParameterList *> ExplicitLists = 17936 Declarator.getTemplateParameterLists(); 17937 if (!ExplicitLists.empty()) { 17938 bool IsMemberSpecialization, IsInvalid; 17939 ExplicitParams = MatchTemplateParametersToScopeSpecifier( 17940 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), 17941 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, 17942 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, 17943 /*SuppressDiagnostic=*/true); 17944 } 17945 if (ExplicitParams) { 17946 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); 17947 for (NamedDecl *Param : *ExplicitParams) 17948 Info.TemplateParams.push_back(Param); 17949 Info.NumExplicitTemplateParams = ExplicitParams->size(); 17950 } else { 17951 Info.AutoTemplateParameterDepth = TemplateParameterDepth; 17952 Info.NumExplicitTemplateParams = 0; 17953 } 17954 } 17955 17956 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { 17957 auto &FSI = InventedParameterInfos.back(); 17958 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { 17959 if (FSI.NumExplicitTemplateParams != 0) { 17960 TemplateParameterList *ExplicitParams = 17961 Declarator.getTemplateParameterLists().back(); 17962 Declarator.setInventedTemplateParameterList( 17963 TemplateParameterList::Create( 17964 Context, ExplicitParams->getTemplateLoc(), 17965 ExplicitParams->getLAngleLoc(), FSI.TemplateParams, 17966 ExplicitParams->getRAngleLoc(), 17967 ExplicitParams->getRequiresClause())); 17968 } else { 17969 Declarator.setInventedTemplateParameterList( 17970 TemplateParameterList::Create( 17971 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, 17972 SourceLocation(), /*RequiresClause=*/nullptr)); 17973 } 17974 } 17975 InventedParameterInfos.pop_back(); 17976 } 17977