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/Specifiers.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/LiteralSupport.h" 32 #include "clang/Lex/Preprocessor.h" 33 #include "clang/Sema/CXXFieldCollector.h" 34 #include "clang/Sema/DeclSpec.h" 35 #include "clang/Sema/Initialization.h" 36 #include "clang/Sema/Lookup.h" 37 #include "clang/Sema/ParsedTemplate.h" 38 #include "clang/Sema/Scope.h" 39 #include "clang/Sema/ScopeInfo.h" 40 #include "clang/Sema/SemaInternal.h" 41 #include "clang/Sema/Template.h" 42 #include "llvm/ADT/ScopeExit.h" 43 #include "llvm/ADT/SmallString.h" 44 #include "llvm/ADT/STLExtras.h" 45 #include "llvm/ADT/StringExtras.h" 46 #include <map> 47 #include <set> 48 49 using namespace clang; 50 51 //===----------------------------------------------------------------------===// 52 // CheckDefaultArgumentVisitor 53 //===----------------------------------------------------------------------===// 54 55 namespace { 56 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 57 /// the default argument of a parameter to determine whether it 58 /// contains any ill-formed subexpressions. For example, this will 59 /// diagnose the use of local variables or parameters within the 60 /// default argument expression. 61 class CheckDefaultArgumentVisitor 62 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> { 63 Sema &S; 64 const Expr *DefaultArg; 65 66 public: 67 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg) 68 : S(S), DefaultArg(DefaultArg) {} 69 70 bool VisitExpr(const Expr *Node); 71 bool VisitDeclRefExpr(const DeclRefExpr *DRE); 72 bool VisitCXXThisExpr(const CXXThisExpr *ThisE); 73 bool VisitLambdaExpr(const LambdaExpr *Lambda); 74 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE); 75 }; 76 77 /// VisitExpr - Visit all of the children of this expression. 78 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) { 79 bool IsInvalid = false; 80 for (const Stmt *SubStmt : Node->children()) 81 IsInvalid |= Visit(SubStmt); 82 return IsInvalid; 83 } 84 85 /// VisitDeclRefExpr - Visit a reference to a declaration, to 86 /// determine whether this declaration can be used in the default 87 /// argument expression. 88 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) { 89 const NamedDecl *Decl = DRE->getDecl(); 90 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) { 91 // C++ [dcl.fct.default]p9: 92 // [...] parameters of a function shall not be used in default 93 // argument expressions, even if they are not evaluated. [...] 94 // 95 // C++17 [dcl.fct.default]p9 (by CWG 2082): 96 // [...] A parameter shall not appear as a potentially-evaluated 97 // expression in a default argument. [...] 98 // 99 if (DRE->isNonOdrUse() != NOUR_Unevaluated) 100 return S.Diag(DRE->getBeginLoc(), 101 diag::err_param_default_argument_references_param) 102 << Param->getDeclName() << DefaultArg->getSourceRange(); 103 } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) { 104 // C++ [dcl.fct.default]p7: 105 // Local variables shall not be used in default argument 106 // expressions. 107 // 108 // C++17 [dcl.fct.default]p7 (by CWG 2082): 109 // A local variable shall not appear as a potentially-evaluated 110 // expression in a default argument. 111 // 112 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346): 113 // Note: A local variable cannot be odr-used (6.3) in a default argument. 114 // 115 if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse()) 116 return S.Diag(DRE->getBeginLoc(), 117 diag::err_param_default_argument_references_local) 118 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 119 } 120 121 return false; 122 } 123 124 /// VisitCXXThisExpr - Visit a C++ "this" expression. 125 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) { 126 // C++ [dcl.fct.default]p8: 127 // The keyword this shall not be used in a default argument of a 128 // member function. 129 return S.Diag(ThisE->getBeginLoc(), 130 diag::err_param_default_argument_references_this) 131 << ThisE->getSourceRange(); 132 } 133 134 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr( 135 const PseudoObjectExpr *POE) { 136 bool Invalid = false; 137 for (const Expr *E : POE->semantics()) { 138 // Look through bindings. 139 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) { 140 E = OVE->getSourceExpr(); 141 assert(E && "pseudo-object binding without source expression?"); 142 } 143 144 Invalid |= Visit(E); 145 } 146 return Invalid; 147 } 148 149 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) { 150 // C++11 [expr.lambda.prim]p13: 151 // A lambda-expression appearing in a default argument shall not 152 // implicitly or explicitly capture any entity. 153 if (Lambda->capture_begin() == Lambda->capture_end()) 154 return false; 155 156 return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); 157 } 158 } // namespace 159 160 void 161 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 162 const CXXMethodDecl *Method) { 163 // If we have an MSAny spec already, don't bother. 164 if (!Method || ComputedEST == EST_MSAny) 165 return; 166 167 const FunctionProtoType *Proto 168 = Method->getType()->getAs<FunctionProtoType>(); 169 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 170 if (!Proto) 171 return; 172 173 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 174 175 // If we have a throw-all spec at this point, ignore the function. 176 if (ComputedEST == EST_None) 177 return; 178 179 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 180 EST = EST_BasicNoexcept; 181 182 switch (EST) { 183 case EST_Unparsed: 184 case EST_Uninstantiated: 185 case EST_Unevaluated: 186 llvm_unreachable("should not see unresolved exception specs here"); 187 188 // If this function can throw any exceptions, make a note of that. 189 case EST_MSAny: 190 case EST_None: 191 // FIXME: Whichever we see last of MSAny and None determines our result. 192 // We should make a consistent, order-independent choice here. 193 ClearExceptions(); 194 ComputedEST = EST; 195 return; 196 case EST_NoexceptFalse: 197 ClearExceptions(); 198 ComputedEST = EST_None; 199 return; 200 // FIXME: If the call to this decl is using any of its default arguments, we 201 // need to search them for potentially-throwing calls. 202 // If this function has a basic noexcept, it doesn't affect the outcome. 203 case EST_BasicNoexcept: 204 case EST_NoexceptTrue: 205 case EST_NoThrow: 206 return; 207 // If we're still at noexcept(true) and there's a throw() callee, 208 // change to that specification. 209 case EST_DynamicNone: 210 if (ComputedEST == EST_BasicNoexcept) 211 ComputedEST = EST_DynamicNone; 212 return; 213 case EST_DependentNoexcept: 214 llvm_unreachable( 215 "should not generate implicit declarations for dependent cases"); 216 case EST_Dynamic: 217 break; 218 } 219 assert(EST == EST_Dynamic && "EST case not considered earlier."); 220 assert(ComputedEST != EST_None && 221 "Shouldn't collect exceptions when throw-all is guaranteed."); 222 ComputedEST = EST_Dynamic; 223 // Record the exceptions in this function's exception specification. 224 for (const auto &E : Proto->exceptions()) 225 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 226 Exceptions.push_back(E); 227 } 228 229 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) { 230 if (!S || ComputedEST == EST_MSAny) 231 return; 232 233 // FIXME: 234 // 235 // C++0x [except.spec]p14: 236 // [An] implicit exception-specification specifies the type-id T if and 237 // only if T is allowed by the exception-specification of a function directly 238 // invoked by f's implicit definition; f shall allow all exceptions if any 239 // function it directly invokes allows all exceptions, and f shall allow no 240 // exceptions if every function it directly invokes allows no exceptions. 241 // 242 // Note in particular that if an implicit exception-specification is generated 243 // for a function containing a throw-expression, that specification can still 244 // be noexcept(true). 245 // 246 // Note also that 'directly invoked' is not defined in the standard, and there 247 // is no indication that we should only consider potentially-evaluated calls. 248 // 249 // Ultimately we should implement the intent of the standard: the exception 250 // specification should be the set of exceptions which can be thrown by the 251 // implicit definition. For now, we assume that any non-nothrow expression can 252 // throw any exception. 253 254 if (Self->canThrow(S)) 255 ComputedEST = EST_None; 256 } 257 258 ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 259 SourceLocation EqualLoc) { 260 if (RequireCompleteType(Param->getLocation(), Param->getType(), 261 diag::err_typecheck_decl_incomplete_type)) 262 return true; 263 264 // C++ [dcl.fct.default]p5 265 // A default argument expression is implicitly converted (clause 266 // 4) to the parameter type. The default argument expression has 267 // the same semantic constraints as the initializer expression in 268 // a declaration of a variable of the parameter type, using the 269 // copy-initialization semantics (8.5). 270 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 271 Param); 272 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 273 EqualLoc); 274 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 275 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 276 if (Result.isInvalid()) 277 return true; 278 Arg = Result.getAs<Expr>(); 279 280 CheckCompletedExpr(Arg, EqualLoc); 281 Arg = MaybeCreateExprWithCleanups(Arg); 282 283 return Arg; 284 } 285 286 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 287 SourceLocation EqualLoc) { 288 // Add the default argument to the parameter 289 Param->setDefaultArg(Arg); 290 291 // We have already instantiated this parameter; provide each of the 292 // instantiations with the uninstantiated default argument. 293 UnparsedDefaultArgInstantiationsMap::iterator InstPos 294 = UnparsedDefaultArgInstantiations.find(Param); 295 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 296 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 297 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 298 299 // We're done tracking this parameter's instantiations. 300 UnparsedDefaultArgInstantiations.erase(InstPos); 301 } 302 } 303 304 /// ActOnParamDefaultArgument - Check whether the default argument 305 /// provided for a function parameter is well-formed. If so, attach it 306 /// to the parameter declaration. 307 void 308 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 309 Expr *DefaultArg) { 310 if (!param || !DefaultArg) 311 return; 312 313 ParmVarDecl *Param = cast<ParmVarDecl>(param); 314 UnparsedDefaultArgLocs.erase(Param); 315 316 auto Fail = [&] { 317 Param->setInvalidDecl(); 318 Param->setDefaultArg(new (Context) OpaqueValueExpr( 319 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue)); 320 }; 321 322 // Default arguments are only permitted in C++ 323 if (!getLangOpts().CPlusPlus) { 324 Diag(EqualLoc, diag::err_param_default_argument) 325 << DefaultArg->getSourceRange(); 326 return Fail(); 327 } 328 329 // Check for unexpanded parameter packs. 330 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 331 return Fail(); 332 } 333 334 // C++11 [dcl.fct.default]p3 335 // A default argument expression [...] shall not be specified for a 336 // parameter pack. 337 if (Param->isParameterPack()) { 338 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 339 << DefaultArg->getSourceRange(); 340 // Recover by discarding the default argument. 341 Param->setDefaultArg(nullptr); 342 return; 343 } 344 345 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc); 346 if (Result.isInvalid()) 347 return Fail(); 348 349 DefaultArg = Result.getAs<Expr>(); 350 351 // Check that the default argument is well-formed 352 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg); 353 if (DefaultArgChecker.Visit(DefaultArg)) 354 return Fail(); 355 356 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 357 } 358 359 /// ActOnParamUnparsedDefaultArgument - We've seen a default 360 /// argument for a function parameter, but we can't parse it yet 361 /// because we're inside a class definition. Note that this default 362 /// argument will be parsed later. 363 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 364 SourceLocation EqualLoc, 365 SourceLocation ArgLoc) { 366 if (!param) 367 return; 368 369 ParmVarDecl *Param = cast<ParmVarDecl>(param); 370 Param->setUnparsedDefaultArg(); 371 UnparsedDefaultArgLocs[Param] = ArgLoc; 372 } 373 374 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 375 /// the default argument for the parameter param failed. 376 void Sema::ActOnParamDefaultArgumentError(Decl *param, 377 SourceLocation EqualLoc) { 378 if (!param) 379 return; 380 381 ParmVarDecl *Param = cast<ParmVarDecl>(param); 382 Param->setInvalidDecl(); 383 UnparsedDefaultArgLocs.erase(Param); 384 Param->setDefaultArg(new (Context) OpaqueValueExpr( 385 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue)); 386 } 387 388 /// CheckExtraCXXDefaultArguments - Check for any extra default 389 /// arguments in the declarator, which is not a function declaration 390 /// or definition and therefore is not permitted to have default 391 /// arguments. This routine should be invoked for every declarator 392 /// that is not a function declaration or definition. 393 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 394 // C++ [dcl.fct.default]p3 395 // A default argument expression shall be specified only in the 396 // parameter-declaration-clause of a function declaration or in a 397 // template-parameter (14.1). It shall not be specified for a 398 // parameter pack. If it is specified in a 399 // parameter-declaration-clause, it shall not occur within a 400 // declarator or abstract-declarator of a parameter-declaration. 401 bool MightBeFunction = D.isFunctionDeclarationContext(); 402 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 403 DeclaratorChunk &chunk = D.getTypeObject(i); 404 if (chunk.Kind == DeclaratorChunk::Function) { 405 if (MightBeFunction) { 406 // This is a function declaration. It can have default arguments, but 407 // keep looking in case its return type is a function type with default 408 // arguments. 409 MightBeFunction = false; 410 continue; 411 } 412 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 413 ++argIdx) { 414 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 415 if (Param->hasUnparsedDefaultArg()) { 416 std::unique_ptr<CachedTokens> Toks = 417 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 418 SourceRange SR; 419 if (Toks->size() > 1) 420 SR = SourceRange((*Toks)[1].getLocation(), 421 Toks->back().getLocation()); 422 else 423 SR = UnparsedDefaultArgLocs[Param]; 424 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 425 << SR; 426 } else if (Param->getDefaultArg()) { 427 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 428 << Param->getDefaultArg()->getSourceRange(); 429 Param->setDefaultArg(nullptr); 430 } 431 } 432 } else if (chunk.Kind != DeclaratorChunk::Paren) { 433 MightBeFunction = false; 434 } 435 } 436 } 437 438 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 439 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) { 440 return P->hasDefaultArg() && !P->hasInheritedDefaultArg(); 441 }); 442 } 443 444 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 445 /// function, once we already know that they have the same 446 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 447 /// error, false otherwise. 448 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 449 Scope *S) { 450 bool Invalid = false; 451 452 // The declaration context corresponding to the scope is the semantic 453 // parent, unless this is a local function declaration, in which case 454 // it is that surrounding function. 455 DeclContext *ScopeDC = New->isLocalExternDecl() 456 ? New->getLexicalDeclContext() 457 : New->getDeclContext(); 458 459 // Find the previous declaration for the purpose of default arguments. 460 FunctionDecl *PrevForDefaultArgs = Old; 461 for (/**/; PrevForDefaultArgs; 462 // Don't bother looking back past the latest decl if this is a local 463 // extern declaration; nothing else could work. 464 PrevForDefaultArgs = New->isLocalExternDecl() 465 ? nullptr 466 : PrevForDefaultArgs->getPreviousDecl()) { 467 // Ignore hidden declarations. 468 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 469 continue; 470 471 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 472 !New->isCXXClassMember()) { 473 // Ignore default arguments of old decl if they are not in 474 // the same scope and this is not an out-of-line definition of 475 // a member function. 476 continue; 477 } 478 479 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 480 // If only one of these is a local function declaration, then they are 481 // declared in different scopes, even though isDeclInScope may think 482 // they're in the same scope. (If both are local, the scope check is 483 // sufficient, and if neither is local, then they are in the same scope.) 484 continue; 485 } 486 487 // We found the right previous declaration. 488 break; 489 } 490 491 // C++ [dcl.fct.default]p4: 492 // For non-template functions, default arguments can be added in 493 // later declarations of a function in the same 494 // scope. Declarations in different scopes have completely 495 // distinct sets of default arguments. That is, declarations in 496 // inner scopes do not acquire default arguments from 497 // declarations in outer scopes, and vice versa. In a given 498 // function declaration, all parameters subsequent to a 499 // parameter with a default argument shall have default 500 // arguments supplied in this or previous declarations. A 501 // default argument shall not be redefined by a later 502 // declaration (not even to the same value). 503 // 504 // C++ [dcl.fct.default]p6: 505 // Except for member functions of class templates, the default arguments 506 // in a member function definition that appears outside of the class 507 // definition are added to the set of default arguments provided by the 508 // member function declaration in the class definition. 509 for (unsigned p = 0, NumParams = PrevForDefaultArgs 510 ? PrevForDefaultArgs->getNumParams() 511 : 0; 512 p < NumParams; ++p) { 513 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 514 ParmVarDecl *NewParam = New->getParamDecl(p); 515 516 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 517 bool NewParamHasDfl = NewParam->hasDefaultArg(); 518 519 if (OldParamHasDfl && NewParamHasDfl) { 520 unsigned DiagDefaultParamID = 521 diag::err_param_default_argument_redefinition; 522 523 // MSVC accepts that default parameters be redefined for member functions 524 // of template class. The new default parameter's value is ignored. 525 Invalid = true; 526 if (getLangOpts().MicrosoftExt) { 527 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 528 if (MD && MD->getParent()->getDescribedClassTemplate()) { 529 // Merge the old default argument into the new parameter. 530 NewParam->setHasInheritedDefaultArg(); 531 if (OldParam->hasUninstantiatedDefaultArg()) 532 NewParam->setUninstantiatedDefaultArg( 533 OldParam->getUninstantiatedDefaultArg()); 534 else 535 NewParam->setDefaultArg(OldParam->getInit()); 536 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 537 Invalid = false; 538 } 539 } 540 541 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 542 // hint here. Alternatively, we could walk the type-source information 543 // for NewParam to find the last source location in the type... but it 544 // isn't worth the effort right now. This is the kind of test case that 545 // is hard to get right: 546 // int f(int); 547 // void g(int (*fp)(int) = f); 548 // void g(int (*fp)(int) = &f); 549 Diag(NewParam->getLocation(), DiagDefaultParamID) 550 << NewParam->getDefaultArgRange(); 551 552 // Look for the function declaration where the default argument was 553 // actually written, which may be a declaration prior to Old. 554 for (auto Older = PrevForDefaultArgs; 555 OldParam->hasInheritedDefaultArg(); /**/) { 556 Older = Older->getPreviousDecl(); 557 OldParam = Older->getParamDecl(p); 558 } 559 560 Diag(OldParam->getLocation(), diag::note_previous_definition) 561 << OldParam->getDefaultArgRange(); 562 } else if (OldParamHasDfl) { 563 // Merge the old default argument into the new parameter unless the new 564 // function is a friend declaration in a template class. In the latter 565 // case the default arguments will be inherited when the friend 566 // declaration will be instantiated. 567 if (New->getFriendObjectKind() == Decl::FOK_None || 568 !New->getLexicalDeclContext()->isDependentContext()) { 569 // It's important to use getInit() here; getDefaultArg() 570 // strips off any top-level ExprWithCleanups. 571 NewParam->setHasInheritedDefaultArg(); 572 if (OldParam->hasUnparsedDefaultArg()) 573 NewParam->setUnparsedDefaultArg(); 574 else if (OldParam->hasUninstantiatedDefaultArg()) 575 NewParam->setUninstantiatedDefaultArg( 576 OldParam->getUninstantiatedDefaultArg()); 577 else 578 NewParam->setDefaultArg(OldParam->getInit()); 579 } 580 } else if (NewParamHasDfl) { 581 if (New->getDescribedFunctionTemplate()) { 582 // Paragraph 4, quoted above, only applies to non-template functions. 583 Diag(NewParam->getLocation(), 584 diag::err_param_default_argument_template_redecl) 585 << NewParam->getDefaultArgRange(); 586 Diag(PrevForDefaultArgs->getLocation(), 587 diag::note_template_prev_declaration) 588 << false; 589 } else if (New->getTemplateSpecializationKind() 590 != TSK_ImplicitInstantiation && 591 New->getTemplateSpecializationKind() != TSK_Undeclared) { 592 // C++ [temp.expr.spec]p21: 593 // Default function arguments shall not be specified in a declaration 594 // or a definition for one of the following explicit specializations: 595 // - the explicit specialization of a function template; 596 // - the explicit specialization of a member function template; 597 // - the explicit specialization of a member function of a class 598 // template where the class template specialization to which the 599 // member function specialization belongs is implicitly 600 // instantiated. 601 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 602 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 603 << New->getDeclName() 604 << NewParam->getDefaultArgRange(); 605 } else if (New->getDeclContext()->isDependentContext()) { 606 // C++ [dcl.fct.default]p6 (DR217): 607 // Default arguments for a member function of a class template shall 608 // be specified on the initial declaration of the member function 609 // within the class template. 610 // 611 // Reading the tea leaves a bit in DR217 and its reference to DR205 612 // leads me to the conclusion that one cannot add default function 613 // arguments for an out-of-line definition of a member function of a 614 // dependent type. 615 int WhichKind = 2; 616 if (CXXRecordDecl *Record 617 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 618 if (Record->getDescribedClassTemplate()) 619 WhichKind = 0; 620 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 621 WhichKind = 1; 622 else 623 WhichKind = 2; 624 } 625 626 Diag(NewParam->getLocation(), 627 diag::err_param_default_argument_member_template_redecl) 628 << WhichKind 629 << NewParam->getDefaultArgRange(); 630 } 631 } 632 } 633 634 // DR1344: If a default argument is added outside a class definition and that 635 // default argument makes the function a special member function, the program 636 // is ill-formed. This can only happen for constructors. 637 if (isa<CXXConstructorDecl>(New) && 638 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 639 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 640 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 641 if (NewSM != OldSM) { 642 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 643 assert(NewParam->hasDefaultArg()); 644 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 645 << NewParam->getDefaultArgRange() << NewSM; 646 Diag(Old->getLocation(), diag::note_previous_declaration); 647 } 648 } 649 650 const FunctionDecl *Def; 651 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 652 // template has a constexpr specifier then all its declarations shall 653 // contain the constexpr specifier. 654 if (New->getConstexprKind() != Old->getConstexprKind()) { 655 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 656 << New << static_cast<int>(New->getConstexprKind()) 657 << static_cast<int>(Old->getConstexprKind()); 658 Diag(Old->getLocation(), diag::note_previous_declaration); 659 Invalid = true; 660 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 661 Old->isDefined(Def) && 662 // If a friend function is inlined but does not have 'inline' 663 // specifier, it is a definition. Do not report attribute conflict 664 // in this case, redefinition will be diagnosed later. 665 (New->isInlineSpecified() || 666 New->getFriendObjectKind() == Decl::FOK_None)) { 667 // C++11 [dcl.fcn.spec]p4: 668 // If the definition of a function appears in a translation unit before its 669 // first declaration as inline, the program is ill-formed. 670 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 671 Diag(Def->getLocation(), diag::note_previous_definition); 672 Invalid = true; 673 } 674 675 // C++17 [temp.deduct.guide]p3: 676 // Two deduction guide declarations in the same translation unit 677 // for the same class template shall not have equivalent 678 // parameter-declaration-clauses. 679 if (isa<CXXDeductionGuideDecl>(New) && 680 !New->isFunctionTemplateSpecialization() && isVisible(Old)) { 681 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 682 Diag(Old->getLocation(), diag::note_previous_declaration); 683 } 684 685 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 686 // argument expression, that declaration shall be a definition and shall be 687 // the only declaration of the function or function template in the 688 // translation unit. 689 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 690 functionDeclHasDefaultArgument(Old)) { 691 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 692 Diag(Old->getLocation(), diag::note_previous_declaration); 693 Invalid = true; 694 } 695 696 // C++11 [temp.friend]p4 (DR329): 697 // When a function is defined in a friend function declaration in a class 698 // template, the function is instantiated when the function is odr-used. 699 // The same restrictions on multiple declarations and definitions that 700 // apply to non-template function declarations and definitions also apply 701 // to these implicit definitions. 702 const FunctionDecl *OldDefinition = nullptr; 703 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() && 704 Old->isDefined(OldDefinition, true)) 705 CheckForFunctionRedefinition(New, OldDefinition); 706 707 return Invalid; 708 } 709 710 NamedDecl * 711 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 712 MultiTemplateParamsArg TemplateParamLists) { 713 assert(D.isDecompositionDeclarator()); 714 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 715 716 // The syntax only allows a decomposition declarator as a simple-declaration, 717 // a for-range-declaration, or a condition in Clang, but we parse it in more 718 // cases than that. 719 if (!D.mayHaveDecompositionDeclarator()) { 720 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 721 << Decomp.getSourceRange(); 722 return nullptr; 723 } 724 725 if (!TemplateParamLists.empty()) { 726 // FIXME: There's no rule against this, but there are also no rules that 727 // would actually make it usable, so we reject it for now. 728 Diag(TemplateParamLists.front()->getTemplateLoc(), 729 diag::err_decomp_decl_template); 730 return nullptr; 731 } 732 733 Diag(Decomp.getLSquareLoc(), 734 !getLangOpts().CPlusPlus17 735 ? diag::ext_decomp_decl 736 : D.getContext() == DeclaratorContext::Condition 737 ? diag::ext_decomp_decl_cond 738 : diag::warn_cxx14_compat_decomp_decl) 739 << Decomp.getSourceRange(); 740 741 // The semantic context is always just the current context. 742 DeclContext *const DC = CurContext; 743 744 // C++17 [dcl.dcl]/8: 745 // The decl-specifier-seq shall contain only the type-specifier auto 746 // and cv-qualifiers. 747 // C++2a [dcl.dcl]/8: 748 // If decl-specifier-seq contains any decl-specifier other than static, 749 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 750 auto &DS = D.getDeclSpec(); 751 { 752 SmallVector<StringRef, 8> BadSpecifiers; 753 SmallVector<SourceLocation, 8> BadSpecifierLocs; 754 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 755 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 756 if (auto SCS = DS.getStorageClassSpec()) { 757 if (SCS == DeclSpec::SCS_static) { 758 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 759 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 760 } else { 761 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 762 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 763 } 764 } 765 if (auto TSCS = DS.getThreadStorageClassSpec()) { 766 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 767 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 768 } 769 if (DS.hasConstexprSpecifier()) { 770 BadSpecifiers.push_back( 771 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 772 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 773 } 774 if (DS.isInlineSpecified()) { 775 BadSpecifiers.push_back("inline"); 776 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 777 } 778 if (!BadSpecifiers.empty()) { 779 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 780 Err << (int)BadSpecifiers.size() 781 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 782 // Don't add FixItHints to remove the specifiers; we do still respect 783 // them when building the underlying variable. 784 for (auto Loc : BadSpecifierLocs) 785 Err << SourceRange(Loc, Loc); 786 } else if (!CPlusPlus20Specifiers.empty()) { 787 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 788 getLangOpts().CPlusPlus20 789 ? diag::warn_cxx17_compat_decomp_decl_spec 790 : diag::ext_decomp_decl_spec); 791 Warn << (int)CPlusPlus20Specifiers.size() 792 << llvm::join(CPlusPlus20Specifiers.begin(), 793 CPlusPlus20Specifiers.end(), " "); 794 for (auto Loc : CPlusPlus20SpecifierLocs) 795 Warn << SourceRange(Loc, Loc); 796 } 797 // We can't recover from it being declared as a typedef. 798 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 799 return nullptr; 800 } 801 802 // C++2a [dcl.struct.bind]p1: 803 // A cv that includes volatile is deprecated 804 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && 805 getLangOpts().CPlusPlus20) 806 Diag(DS.getVolatileSpecLoc(), 807 diag::warn_deprecated_volatile_structured_binding); 808 809 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 810 QualType R = TInfo->getType(); 811 812 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 813 UPPC_DeclarationType)) 814 D.setInvalidType(); 815 816 // The syntax only allows a single ref-qualifier prior to the decomposition 817 // declarator. No other declarator chunks are permitted. Also check the type 818 // specifier here. 819 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 820 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 821 (D.getNumTypeObjects() == 1 && 822 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 823 Diag(Decomp.getLSquareLoc(), 824 (D.hasGroupingParens() || 825 (D.getNumTypeObjects() && 826 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 827 ? diag::err_decomp_decl_parens 828 : diag::err_decomp_decl_type) 829 << R; 830 831 // In most cases, there's no actual problem with an explicitly-specified 832 // type, but a function type won't work here, and ActOnVariableDeclarator 833 // shouldn't be called for such a type. 834 if (R->isFunctionType()) 835 D.setInvalidType(); 836 } 837 838 // Build the BindingDecls. 839 SmallVector<BindingDecl*, 8> Bindings; 840 841 // Build the BindingDecls. 842 for (auto &B : D.getDecompositionDeclarator().bindings()) { 843 // Check for name conflicts. 844 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 845 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 846 ForVisibleRedeclaration); 847 LookupName(Previous, S, 848 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 849 850 // It's not permitted to shadow a template parameter name. 851 if (Previous.isSingleResult() && 852 Previous.getFoundDecl()->isTemplateParameter()) { 853 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 854 Previous.getFoundDecl()); 855 Previous.clear(); 856 } 857 858 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 859 860 // Find the shadowed declaration before filtering for scope. 861 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 862 ? getShadowedDeclaration(BD, Previous) 863 : nullptr; 864 865 bool ConsiderLinkage = DC->isFunctionOrMethod() && 866 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 867 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 868 /*AllowInlineNamespace*/false); 869 870 if (!Previous.empty()) { 871 auto *Old = Previous.getRepresentativeDecl(); 872 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 873 Diag(Old->getLocation(), diag::note_previous_definition); 874 } else if (ShadowedDecl && !D.isRedeclaration()) { 875 CheckShadow(BD, ShadowedDecl, Previous); 876 } 877 PushOnScopeChains(BD, S, true); 878 Bindings.push_back(BD); 879 ParsingInitForAutoVars.insert(BD); 880 } 881 882 // There are no prior lookup results for the variable itself, because it 883 // is unnamed. 884 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 885 Decomp.getLSquareLoc()); 886 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 887 ForVisibleRedeclaration); 888 889 // Build the variable that holds the non-decomposed object. 890 bool AddToScope = true; 891 NamedDecl *New = 892 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 893 MultiTemplateParamsArg(), AddToScope, Bindings); 894 if (AddToScope) { 895 S->AddDecl(New); 896 CurContext->addHiddenDecl(New); 897 } 898 899 if (isInOpenMPDeclareTargetContext()) 900 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 901 902 return New; 903 } 904 905 static bool checkSimpleDecomposition( 906 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 907 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 908 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 909 if ((int64_t)Bindings.size() != NumElems) { 910 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 911 << DecompType << (unsigned)Bindings.size() 912 << (unsigned)NumElems.getLimitedValue(UINT_MAX) 913 << toString(NumElems, 10) << (NumElems < Bindings.size()); 914 return true; 915 } 916 917 unsigned I = 0; 918 for (auto *B : Bindings) { 919 SourceLocation Loc = B->getLocation(); 920 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 921 if (E.isInvalid()) 922 return true; 923 E = GetInit(Loc, E.get(), I++); 924 if (E.isInvalid()) 925 return true; 926 B->setBinding(ElemType, E.get()); 927 } 928 929 return false; 930 } 931 932 static bool checkArrayLikeDecomposition(Sema &S, 933 ArrayRef<BindingDecl *> Bindings, 934 ValueDecl *Src, QualType DecompType, 935 const llvm::APSInt &NumElems, 936 QualType ElemType) { 937 return checkSimpleDecomposition( 938 S, Bindings, Src, DecompType, NumElems, ElemType, 939 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 940 ExprResult E = S.ActOnIntegerConstant(Loc, I); 941 if (E.isInvalid()) 942 return ExprError(); 943 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 944 }); 945 } 946 947 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 948 ValueDecl *Src, QualType DecompType, 949 const ConstantArrayType *CAT) { 950 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 951 llvm::APSInt(CAT->getSize()), 952 CAT->getElementType()); 953 } 954 955 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 956 ValueDecl *Src, QualType DecompType, 957 const VectorType *VT) { 958 return checkArrayLikeDecomposition( 959 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 960 S.Context.getQualifiedType(VT->getElementType(), 961 DecompType.getQualifiers())); 962 } 963 964 static bool checkComplexDecomposition(Sema &S, 965 ArrayRef<BindingDecl *> Bindings, 966 ValueDecl *Src, QualType DecompType, 967 const ComplexType *CT) { 968 return checkSimpleDecomposition( 969 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 970 S.Context.getQualifiedType(CT->getElementType(), 971 DecompType.getQualifiers()), 972 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 973 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 974 }); 975 } 976 977 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 978 TemplateArgumentListInfo &Args, 979 const TemplateParameterList *Params) { 980 SmallString<128> SS; 981 llvm::raw_svector_ostream OS(SS); 982 bool First = true; 983 unsigned I = 0; 984 for (auto &Arg : Args.arguments()) { 985 if (!First) 986 OS << ", "; 987 Arg.getArgument().print(PrintingPolicy, OS, 988 TemplateParameterList::shouldIncludeTypeForArgument( 989 PrintingPolicy, Params, I)); 990 First = false; 991 I++; 992 } 993 return std::string(OS.str()); 994 } 995 996 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 997 SourceLocation Loc, StringRef Trait, 998 TemplateArgumentListInfo &Args, 999 unsigned DiagID) { 1000 auto DiagnoseMissing = [&] { 1001 if (DiagID) 1002 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 1003 Args, /*Params*/ nullptr); 1004 return true; 1005 }; 1006 1007 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 1008 NamespaceDecl *Std = S.getStdNamespace(); 1009 if (!Std) 1010 return DiagnoseMissing(); 1011 1012 // Look up the trait itself, within namespace std. We can diagnose various 1013 // problems with this lookup even if we've been asked to not diagnose a 1014 // missing specialization, because this can only fail if the user has been 1015 // declaring their own names in namespace std or we don't support the 1016 // standard library implementation in use. 1017 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 1018 Loc, Sema::LookupOrdinaryName); 1019 if (!S.LookupQualifiedName(Result, Std)) 1020 return DiagnoseMissing(); 1021 if (Result.isAmbiguous()) 1022 return true; 1023 1024 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 1025 if (!TraitTD) { 1026 Result.suppressDiagnostics(); 1027 NamedDecl *Found = *Result.begin(); 1028 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 1029 S.Diag(Found->getLocation(), diag::note_declared_at); 1030 return true; 1031 } 1032 1033 // Build the template-id. 1034 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 1035 if (TraitTy.isNull()) 1036 return true; 1037 if (!S.isCompleteType(Loc, TraitTy)) { 1038 if (DiagID) 1039 S.RequireCompleteType( 1040 Loc, TraitTy, DiagID, 1041 printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1042 TraitTD->getTemplateParameters())); 1043 return true; 1044 } 1045 1046 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1047 assert(RD && "specialization of class template is not a class?"); 1048 1049 // Look up the member of the trait type. 1050 S.LookupQualifiedName(TraitMemberLookup, RD); 1051 return TraitMemberLookup.isAmbiguous(); 1052 } 1053 1054 static TemplateArgumentLoc 1055 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1056 uint64_t I) { 1057 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1058 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1059 } 1060 1061 static TemplateArgumentLoc 1062 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1063 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1064 } 1065 1066 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1067 1068 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1069 llvm::APSInt &Size) { 1070 EnterExpressionEvaluationContext ContextRAII( 1071 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1072 1073 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1074 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1075 1076 // Form template argument list for tuple_size<T>. 1077 TemplateArgumentListInfo Args(Loc, Loc); 1078 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1079 1080 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1081 // it's not tuple-like. 1082 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1083 R.empty()) 1084 return IsTupleLike::NotTupleLike; 1085 1086 // If we get this far, we've committed to the tuple interpretation, but 1087 // we can still fail if there actually isn't a usable ::value. 1088 1089 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1090 LookupResult &R; 1091 TemplateArgumentListInfo &Args; 1092 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1093 : R(R), Args(Args) {} 1094 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 1095 SourceLocation Loc) override { 1096 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1097 << printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1098 /*Params*/ nullptr); 1099 } 1100 } Diagnoser(R, Args); 1101 1102 ExprResult E = 1103 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1104 if (E.isInvalid()) 1105 return IsTupleLike::Error; 1106 1107 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser); 1108 if (E.isInvalid()) 1109 return IsTupleLike::Error; 1110 1111 return IsTupleLike::TupleLike; 1112 } 1113 1114 /// \return std::tuple_element<I, T>::type. 1115 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1116 unsigned I, QualType T) { 1117 // Form template argument list for tuple_element<I, T>. 1118 TemplateArgumentListInfo Args(Loc, Loc); 1119 Args.addArgument( 1120 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1121 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1122 1123 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1124 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1125 if (lookupStdTypeTraitMember( 1126 S, R, Loc, "tuple_element", Args, 1127 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1128 return QualType(); 1129 1130 auto *TD = R.getAsSingle<TypeDecl>(); 1131 if (!TD) { 1132 R.suppressDiagnostics(); 1133 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1134 << printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1135 /*Params*/ nullptr); 1136 if (!R.empty()) 1137 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1138 return QualType(); 1139 } 1140 1141 return S.Context.getTypeDeclType(TD); 1142 } 1143 1144 namespace { 1145 struct InitializingBinding { 1146 Sema &S; 1147 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) { 1148 Sema::CodeSynthesisContext Ctx; 1149 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding; 1150 Ctx.PointOfInstantiation = BD->getLocation(); 1151 Ctx.Entity = BD; 1152 S.pushCodeSynthesisContext(Ctx); 1153 } 1154 ~InitializingBinding() { 1155 S.popCodeSynthesisContext(); 1156 } 1157 }; 1158 } 1159 1160 static bool checkTupleLikeDecomposition(Sema &S, 1161 ArrayRef<BindingDecl *> Bindings, 1162 VarDecl *Src, QualType DecompType, 1163 const llvm::APSInt &TupleSize) { 1164 if ((int64_t)Bindings.size() != TupleSize) { 1165 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1166 << DecompType << (unsigned)Bindings.size() 1167 << (unsigned)TupleSize.getLimitedValue(UINT_MAX) 1168 << toString(TupleSize, 10) << (TupleSize < Bindings.size()); 1169 return true; 1170 } 1171 1172 if (Bindings.empty()) 1173 return false; 1174 1175 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1176 1177 // [dcl.decomp]p3: 1178 // The unqualified-id get is looked up in the scope of E by class member 1179 // access lookup ... 1180 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1181 bool UseMemberGet = false; 1182 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1183 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1184 S.LookupQualifiedName(MemberGet, RD); 1185 if (MemberGet.isAmbiguous()) 1186 return true; 1187 // ... and if that finds at least one declaration that is a function 1188 // template whose first template parameter is a non-type parameter ... 1189 for (NamedDecl *D : MemberGet) { 1190 if (FunctionTemplateDecl *FTD = 1191 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1192 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1193 if (TPL->size() != 0 && 1194 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1195 // ... the initializer is e.get<i>(). 1196 UseMemberGet = true; 1197 break; 1198 } 1199 } 1200 } 1201 } 1202 1203 unsigned I = 0; 1204 for (auto *B : Bindings) { 1205 InitializingBinding InitContext(S, B); 1206 SourceLocation Loc = B->getLocation(); 1207 1208 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1209 if (E.isInvalid()) 1210 return true; 1211 1212 // e is an lvalue if the type of the entity is an lvalue reference and 1213 // an xvalue otherwise 1214 if (!Src->getType()->isLValueReferenceType()) 1215 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1216 E.get(), nullptr, VK_XValue, 1217 FPOptionsOverride()); 1218 1219 TemplateArgumentListInfo Args(Loc, Loc); 1220 Args.addArgument( 1221 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1222 1223 if (UseMemberGet) { 1224 // if [lookup of member get] finds at least one declaration, the 1225 // initializer is e.get<i-1>(). 1226 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1227 CXXScopeSpec(), SourceLocation(), nullptr, 1228 MemberGet, &Args, nullptr); 1229 if (E.isInvalid()) 1230 return true; 1231 1232 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1233 } else { 1234 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1235 // in the associated namespaces. 1236 Expr *Get = UnresolvedLookupExpr::Create( 1237 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1238 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1239 UnresolvedSetIterator(), UnresolvedSetIterator()); 1240 1241 Expr *Arg = E.get(); 1242 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1243 } 1244 if (E.isInvalid()) 1245 return true; 1246 Expr *Init = E.get(); 1247 1248 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1249 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1250 if (T.isNull()) 1251 return true; 1252 1253 // each vi is a variable of type "reference to T" initialized with the 1254 // initializer, where the reference is an lvalue reference if the 1255 // initializer is an lvalue and an rvalue reference otherwise 1256 QualType RefType = 1257 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1258 if (RefType.isNull()) 1259 return true; 1260 auto *RefVD = VarDecl::Create( 1261 S.Context, Src->getDeclContext(), Loc, Loc, 1262 B->getDeclName().getAsIdentifierInfo(), RefType, 1263 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1264 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1265 RefVD->setTSCSpec(Src->getTSCSpec()); 1266 RefVD->setImplicit(); 1267 if (Src->isInlineSpecified()) 1268 RefVD->setInlineSpecified(); 1269 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1270 1271 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1272 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1273 InitializationSequence Seq(S, Entity, Kind, Init); 1274 E = Seq.Perform(S, Entity, Kind, Init); 1275 if (E.isInvalid()) 1276 return true; 1277 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1278 if (E.isInvalid()) 1279 return true; 1280 RefVD->setInit(E.get()); 1281 S.CheckCompleteVariableDeclaration(RefVD); 1282 1283 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1284 DeclarationNameInfo(B->getDeclName(), Loc), 1285 RefVD); 1286 if (E.isInvalid()) 1287 return true; 1288 1289 B->setBinding(T, E.get()); 1290 I++; 1291 } 1292 1293 return false; 1294 } 1295 1296 /// Find the base class to decompose in a built-in decomposition of a class type. 1297 /// This base class search is, unfortunately, not quite like any other that we 1298 /// perform anywhere else in C++. 1299 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1300 const CXXRecordDecl *RD, 1301 CXXCastPath &BasePath) { 1302 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1303 CXXBasePath &Path) { 1304 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1305 }; 1306 1307 const CXXRecordDecl *ClassWithFields = nullptr; 1308 AccessSpecifier AS = AS_public; 1309 if (RD->hasDirectFields()) 1310 // [dcl.decomp]p4: 1311 // Otherwise, all of E's non-static data members shall be public direct 1312 // members of E ... 1313 ClassWithFields = RD; 1314 else { 1315 // ... or of ... 1316 CXXBasePaths Paths; 1317 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1318 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1319 // If no classes have fields, just decompose RD itself. (This will work 1320 // if and only if zero bindings were provided.) 1321 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1322 } 1323 1324 CXXBasePath *BestPath = nullptr; 1325 for (auto &P : Paths) { 1326 if (!BestPath) 1327 BestPath = &P; 1328 else if (!S.Context.hasSameType(P.back().Base->getType(), 1329 BestPath->back().Base->getType())) { 1330 // ... the same ... 1331 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1332 << false << RD << BestPath->back().Base->getType() 1333 << P.back().Base->getType(); 1334 return DeclAccessPair(); 1335 } else if (P.Access < BestPath->Access) { 1336 BestPath = &P; 1337 } 1338 } 1339 1340 // ... unambiguous ... 1341 QualType BaseType = BestPath->back().Base->getType(); 1342 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1343 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1344 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1345 return DeclAccessPair(); 1346 } 1347 1348 // ... [accessible, implied by other rules] base class of E. 1349 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1350 *BestPath, diag::err_decomp_decl_inaccessible_base); 1351 AS = BestPath->Access; 1352 1353 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1354 S.BuildBasePathArray(Paths, BasePath); 1355 } 1356 1357 // The above search did not check whether the selected class itself has base 1358 // classes with fields, so check that now. 1359 CXXBasePaths Paths; 1360 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1361 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1362 << (ClassWithFields == RD) << RD << ClassWithFields 1363 << Paths.front().back().Base->getType(); 1364 return DeclAccessPair(); 1365 } 1366 1367 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1368 } 1369 1370 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1371 ValueDecl *Src, QualType DecompType, 1372 const CXXRecordDecl *OrigRD) { 1373 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1374 diag::err_incomplete_type)) 1375 return true; 1376 1377 CXXCastPath BasePath; 1378 DeclAccessPair BasePair = 1379 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1380 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1381 if (!RD) 1382 return true; 1383 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1384 DecompType.getQualifiers()); 1385 1386 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1387 unsigned NumFields = llvm::count_if( 1388 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1389 assert(Bindings.size() != NumFields); 1390 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1391 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields 1392 << (NumFields < Bindings.size()); 1393 return true; 1394 }; 1395 1396 // all of E's non-static data members shall be [...] well-formed 1397 // when named as e.name in the context of the structured binding, 1398 // E shall not have an anonymous union member, ... 1399 unsigned I = 0; 1400 for (auto *FD : RD->fields()) { 1401 if (FD->isUnnamedBitfield()) 1402 continue; 1403 1404 // All the non-static data members are required to be nameable, so they 1405 // must all have names. 1406 if (!FD->getDeclName()) { 1407 if (RD->isLambda()) { 1408 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda); 1409 S.Diag(RD->getLocation(), diag::note_lambda_decl); 1410 return true; 1411 } 1412 1413 if (FD->isAnonymousStructOrUnion()) { 1414 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1415 << DecompType << FD->getType()->isUnionType(); 1416 S.Diag(FD->getLocation(), diag::note_declared_at); 1417 return true; 1418 } 1419 1420 // FIXME: Are there any other ways we could have an anonymous member? 1421 } 1422 1423 // We have a real field to bind. 1424 if (I >= Bindings.size()) 1425 return DiagnoseBadNumberOfBindings(); 1426 auto *B = Bindings[I++]; 1427 SourceLocation Loc = B->getLocation(); 1428 1429 // The field must be accessible in the context of the structured binding. 1430 // We already checked that the base class is accessible. 1431 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1432 // const_cast here. 1433 S.CheckStructuredBindingMemberAccess( 1434 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1435 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1436 BasePair.getAccess(), FD->getAccess()))); 1437 1438 // Initialize the binding to Src.FD. 1439 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1440 if (E.isInvalid()) 1441 return true; 1442 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1443 VK_LValue, &BasePath); 1444 if (E.isInvalid()) 1445 return true; 1446 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1447 CXXScopeSpec(), FD, 1448 DeclAccessPair::make(FD, FD->getAccess()), 1449 DeclarationNameInfo(FD->getDeclName(), Loc)); 1450 if (E.isInvalid()) 1451 return true; 1452 1453 // If the type of the member is T, the referenced type is cv T, where cv is 1454 // the cv-qualification of the decomposition expression. 1455 // 1456 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1457 // 'const' to the type of the field. 1458 Qualifiers Q = DecompType.getQualifiers(); 1459 if (FD->isMutable()) 1460 Q.removeConst(); 1461 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1462 } 1463 1464 if (I != Bindings.size()) 1465 return DiagnoseBadNumberOfBindings(); 1466 1467 return false; 1468 } 1469 1470 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1471 QualType DecompType = DD->getType(); 1472 1473 // If the type of the decomposition is dependent, then so is the type of 1474 // each binding. 1475 if (DecompType->isDependentType()) { 1476 for (auto *B : DD->bindings()) 1477 B->setType(Context.DependentTy); 1478 return; 1479 } 1480 1481 DecompType = DecompType.getNonReferenceType(); 1482 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1483 1484 // C++1z [dcl.decomp]/2: 1485 // If E is an array type [...] 1486 // As an extension, we also support decomposition of built-in complex and 1487 // vector types. 1488 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1489 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1490 DD->setInvalidDecl(); 1491 return; 1492 } 1493 if (auto *VT = DecompType->getAs<VectorType>()) { 1494 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1495 DD->setInvalidDecl(); 1496 return; 1497 } 1498 if (auto *CT = DecompType->getAs<ComplexType>()) { 1499 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1500 DD->setInvalidDecl(); 1501 return; 1502 } 1503 1504 // C++1z [dcl.decomp]/3: 1505 // if the expression std::tuple_size<E>::value is a well-formed integral 1506 // constant expression, [...] 1507 llvm::APSInt TupleSize(32); 1508 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1509 case IsTupleLike::Error: 1510 DD->setInvalidDecl(); 1511 return; 1512 1513 case IsTupleLike::TupleLike: 1514 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1515 DD->setInvalidDecl(); 1516 return; 1517 1518 case IsTupleLike::NotTupleLike: 1519 break; 1520 } 1521 1522 // C++1z [dcl.dcl]/8: 1523 // [E shall be of array or non-union class type] 1524 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1525 if (!RD || RD->isUnion()) { 1526 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1527 << DD << !RD << DecompType; 1528 DD->setInvalidDecl(); 1529 return; 1530 } 1531 1532 // C++1z [dcl.decomp]/4: 1533 // all of E's non-static data members shall be [...] direct members of 1534 // E or of the same unambiguous public base class of E, ... 1535 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1536 DD->setInvalidDecl(); 1537 } 1538 1539 /// Merge the exception specifications of two variable declarations. 1540 /// 1541 /// This is called when there's a redeclaration of a VarDecl. The function 1542 /// checks if the redeclaration might have an exception specification and 1543 /// validates compatibility and merges the specs if necessary. 1544 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1545 // Shortcut if exceptions are disabled. 1546 if (!getLangOpts().CXXExceptions) 1547 return; 1548 1549 assert(Context.hasSameType(New->getType(), Old->getType()) && 1550 "Should only be called if types are otherwise the same."); 1551 1552 QualType NewType = New->getType(); 1553 QualType OldType = Old->getType(); 1554 1555 // We're only interested in pointers and references to functions, as well 1556 // as pointers to member functions. 1557 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1558 NewType = R->getPointeeType(); 1559 OldType = OldType->castAs<ReferenceType>()->getPointeeType(); 1560 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1561 NewType = P->getPointeeType(); 1562 OldType = OldType->castAs<PointerType>()->getPointeeType(); 1563 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1564 NewType = M->getPointeeType(); 1565 OldType = OldType->castAs<MemberPointerType>()->getPointeeType(); 1566 } 1567 1568 if (!NewType->isFunctionProtoType()) 1569 return; 1570 1571 // There's lots of special cases for functions. For function pointers, system 1572 // libraries are hopefully not as broken so that we don't need these 1573 // workarounds. 1574 if (CheckEquivalentExceptionSpec( 1575 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1576 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1577 New->setInvalidDecl(); 1578 } 1579 } 1580 1581 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1582 /// function declaration are well-formed according to C++ 1583 /// [dcl.fct.default]. 1584 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1585 unsigned NumParams = FD->getNumParams(); 1586 unsigned ParamIdx = 0; 1587 1588 // This checking doesn't make sense for explicit specializations; their 1589 // default arguments are determined by the declaration we're specializing, 1590 // not by FD. 1591 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1592 return; 1593 if (auto *FTD = FD->getDescribedFunctionTemplate()) 1594 if (FTD->isMemberSpecialization()) 1595 return; 1596 1597 // Find first parameter with a default argument 1598 for (; ParamIdx < NumParams; ++ParamIdx) { 1599 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1600 if (Param->hasDefaultArg()) 1601 break; 1602 } 1603 1604 // C++20 [dcl.fct.default]p4: 1605 // In a given function declaration, each parameter subsequent to a parameter 1606 // with a default argument shall have a default argument supplied in this or 1607 // a previous declaration, unless the parameter was expanded from a 1608 // parameter pack, or shall be a function parameter pack. 1609 for (; ParamIdx < NumParams; ++ParamIdx) { 1610 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1611 if (!Param->hasDefaultArg() && !Param->isParameterPack() && 1612 !(CurrentInstantiationScope && 1613 CurrentInstantiationScope->isLocalPackExpansion(Param))) { 1614 if (Param->isInvalidDecl()) 1615 /* We already complained about this parameter. */; 1616 else if (Param->getIdentifier()) 1617 Diag(Param->getLocation(), 1618 diag::err_param_default_argument_missing_name) 1619 << Param->getIdentifier(); 1620 else 1621 Diag(Param->getLocation(), 1622 diag::err_param_default_argument_missing); 1623 } 1624 } 1625 } 1626 1627 /// Check that the given type is a literal type. Issue a diagnostic if not, 1628 /// if Kind is Diagnose. 1629 /// \return \c true if a problem has been found (and optionally diagnosed). 1630 template <typename... Ts> 1631 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1632 SourceLocation Loc, QualType T, unsigned DiagID, 1633 Ts &&...DiagArgs) { 1634 if (T->isDependentType()) 1635 return false; 1636 1637 switch (Kind) { 1638 case Sema::CheckConstexprKind::Diagnose: 1639 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1640 std::forward<Ts>(DiagArgs)...); 1641 1642 case Sema::CheckConstexprKind::CheckValid: 1643 return !T->isLiteralType(SemaRef.Context); 1644 } 1645 1646 llvm_unreachable("unknown CheckConstexprKind"); 1647 } 1648 1649 /// Determine whether a destructor cannot be constexpr due to 1650 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, 1651 const CXXDestructorDecl *DD, 1652 Sema::CheckConstexprKind Kind) { 1653 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { 1654 const CXXRecordDecl *RD = 1655 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1656 if (!RD || RD->hasConstexprDestructor()) 1657 return true; 1658 1659 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1660 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) 1661 << static_cast<int>(DD->getConstexprKind()) << !FD 1662 << (FD ? FD->getDeclName() : DeclarationName()) << T; 1663 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) 1664 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; 1665 } 1666 return false; 1667 }; 1668 1669 const CXXRecordDecl *RD = DD->getParent(); 1670 for (const CXXBaseSpecifier &B : RD->bases()) 1671 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) 1672 return false; 1673 for (const FieldDecl *FD : RD->fields()) 1674 if (!Check(FD->getLocation(), FD->getType(), FD)) 1675 return false; 1676 return true; 1677 } 1678 1679 /// Check whether a function's parameter types are all literal types. If so, 1680 /// return true. If not, produce a suitable diagnostic and return false. 1681 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1682 const FunctionDecl *FD, 1683 Sema::CheckConstexprKind Kind) { 1684 unsigned ArgIndex = 0; 1685 const auto *FT = FD->getType()->castAs<FunctionProtoType>(); 1686 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1687 e = FT->param_type_end(); 1688 i != e; ++i, ++ArgIndex) { 1689 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1690 SourceLocation ParamLoc = PD->getLocation(); 1691 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1692 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1693 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1694 FD->isConsteval())) 1695 return false; 1696 } 1697 return true; 1698 } 1699 1700 /// Check whether a function's return type is a literal type. If so, return 1701 /// true. If not, produce a suitable diagnostic and return false. 1702 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, 1703 Sema::CheckConstexprKind Kind) { 1704 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), 1705 diag::err_constexpr_non_literal_return, 1706 FD->isConsteval())) 1707 return false; 1708 return true; 1709 } 1710 1711 /// Get diagnostic %select index for tag kind for 1712 /// record diagnostic message. 1713 /// WARNING: Indexes apply to particular diagnostics only! 1714 /// 1715 /// \returns diagnostic %select index. 1716 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1717 switch (Tag) { 1718 case TTK_Struct: return 0; 1719 case TTK_Interface: return 1; 1720 case TTK_Class: return 2; 1721 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1722 } 1723 } 1724 1725 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1726 Stmt *Body, 1727 Sema::CheckConstexprKind Kind); 1728 1729 // Check whether a function declaration satisfies the requirements of a 1730 // constexpr function definition or a constexpr constructor definition. If so, 1731 // return true. If not, produce appropriate diagnostics (unless asked not to by 1732 // Kind) and return false. 1733 // 1734 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1735 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1736 CheckConstexprKind Kind) { 1737 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1738 if (MD && MD->isInstance()) { 1739 // C++11 [dcl.constexpr]p4: 1740 // The definition of a constexpr constructor shall satisfy the following 1741 // constraints: 1742 // - the class shall not have any virtual base classes; 1743 // 1744 // FIXME: This only applies to constructors and destructors, not arbitrary 1745 // member functions. 1746 const CXXRecordDecl *RD = MD->getParent(); 1747 if (RD->getNumVBases()) { 1748 if (Kind == CheckConstexprKind::CheckValid) 1749 return false; 1750 1751 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1752 << isa<CXXConstructorDecl>(NewFD) 1753 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1754 for (const auto &I : RD->vbases()) 1755 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1756 << I.getSourceRange(); 1757 return false; 1758 } 1759 } 1760 1761 if (!isa<CXXConstructorDecl>(NewFD)) { 1762 // C++11 [dcl.constexpr]p3: 1763 // The definition of a constexpr function shall satisfy the following 1764 // constraints: 1765 // - it shall not be virtual; (removed in C++20) 1766 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1767 if (Method && Method->isVirtual()) { 1768 if (getLangOpts().CPlusPlus20) { 1769 if (Kind == CheckConstexprKind::Diagnose) 1770 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1771 } else { 1772 if (Kind == CheckConstexprKind::CheckValid) 1773 return false; 1774 1775 Method = Method->getCanonicalDecl(); 1776 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1777 1778 // If it's not obvious why this function is virtual, find an overridden 1779 // function which uses the 'virtual' keyword. 1780 const CXXMethodDecl *WrittenVirtual = Method; 1781 while (!WrittenVirtual->isVirtualAsWritten()) 1782 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1783 if (WrittenVirtual != Method) 1784 Diag(WrittenVirtual->getLocation(), 1785 diag::note_overridden_virtual_function); 1786 return false; 1787 } 1788 } 1789 1790 // - its return type shall be a literal type; 1791 if (!CheckConstexprReturnType(*this, NewFD, Kind)) 1792 return false; 1793 } 1794 1795 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { 1796 // A destructor can be constexpr only if the defaulted destructor could be; 1797 // we don't need to check the members and bases if we already know they all 1798 // have constexpr destructors. 1799 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { 1800 if (Kind == CheckConstexprKind::CheckValid) 1801 return false; 1802 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) 1803 return false; 1804 } 1805 } 1806 1807 // - each of its parameter types shall be a literal type; 1808 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1809 return false; 1810 1811 Stmt *Body = NewFD->getBody(); 1812 assert(Body && 1813 "CheckConstexprFunctionDefinition called on function with no body"); 1814 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1815 } 1816 1817 /// Check the given declaration statement is legal within a constexpr function 1818 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1819 /// 1820 /// \return true if the body is OK (maybe only as an extension), false if we 1821 /// have diagnosed a problem. 1822 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1823 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1824 Sema::CheckConstexprKind Kind) { 1825 // C++11 [dcl.constexpr]p3 and p4: 1826 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1827 // contain only 1828 for (const auto *DclIt : DS->decls()) { 1829 switch (DclIt->getKind()) { 1830 case Decl::StaticAssert: 1831 case Decl::Using: 1832 case Decl::UsingShadow: 1833 case Decl::UsingDirective: 1834 case Decl::UnresolvedUsingTypename: 1835 case Decl::UnresolvedUsingValue: 1836 case Decl::UsingEnum: 1837 // - static_assert-declarations 1838 // - using-declarations, 1839 // - using-directives, 1840 // - using-enum-declaration 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 SemaRef.getLangOpts().CPlusPlus2b 1896 ? diag::warn_cxx20_compat_constexpr_static_var 1897 : diag::ext_constexpr_static_var) 1898 << isa<CXXConstructorDecl>(Dcl) 1899 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1900 } else if (!SemaRef.getLangOpts().CPlusPlus2b) { 1901 return false; 1902 } 1903 } 1904 if (!SemaRef.LangOpts.CPlusPlus2b && 1905 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1906 diag::err_constexpr_local_var_non_literal_type, 1907 isa<CXXConstructorDecl>(Dcl))) 1908 return false; 1909 if (!VD->getType()->isDependentType() && 1910 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1911 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1912 SemaRef.Diag( 1913 VD->getLocation(), 1914 SemaRef.getLangOpts().CPlusPlus20 1915 ? diag::warn_cxx17_compat_constexpr_local_var_no_init 1916 : diag::ext_constexpr_local_var_no_init) 1917 << isa<CXXConstructorDecl>(Dcl); 1918 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1919 return false; 1920 } 1921 continue; 1922 } 1923 } 1924 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1925 SemaRef.Diag(VD->getLocation(), 1926 SemaRef.getLangOpts().CPlusPlus14 1927 ? diag::warn_cxx11_compat_constexpr_local_var 1928 : diag::ext_constexpr_local_var) 1929 << isa<CXXConstructorDecl>(Dcl); 1930 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1931 return false; 1932 } 1933 continue; 1934 } 1935 1936 case Decl::NamespaceAlias: 1937 case Decl::Function: 1938 // These are disallowed in C++11 and permitted in C++1y. Allow them 1939 // everywhere as an extension. 1940 if (!Cxx1yLoc.isValid()) 1941 Cxx1yLoc = DS->getBeginLoc(); 1942 continue; 1943 1944 default: 1945 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1946 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1947 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1948 } 1949 return false; 1950 } 1951 } 1952 1953 return true; 1954 } 1955 1956 /// Check that the given field is initialized within a constexpr constructor. 1957 /// 1958 /// \param Dcl The constexpr constructor being checked. 1959 /// \param Field The field being checked. This may be a member of an anonymous 1960 /// struct or union nested within the class being checked. 1961 /// \param Inits All declarations, including anonymous struct/union members and 1962 /// indirect members, for which any initialization was provided. 1963 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1964 /// multiple notes for different members to the same error. 1965 /// \param Kind Whether we're diagnosing a constructor as written or determining 1966 /// whether the formal requirements are satisfied. 1967 /// \return \c false if we're checking for validity and the constructor does 1968 /// not satisfy the requirements on a constexpr constructor. 1969 static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1970 const FunctionDecl *Dcl, 1971 FieldDecl *Field, 1972 llvm::SmallSet<Decl*, 16> &Inits, 1973 bool &Diagnosed, 1974 Sema::CheckConstexprKind Kind) { 1975 // In C++20 onwards, there's nothing to check for validity. 1976 if (Kind == Sema::CheckConstexprKind::CheckValid && 1977 SemaRef.getLangOpts().CPlusPlus20) 1978 return true; 1979 1980 if (Field->isInvalidDecl()) 1981 return true; 1982 1983 if (Field->isUnnamedBitfield()) 1984 return true; 1985 1986 // Anonymous unions with no variant members and empty anonymous structs do not 1987 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1988 // indirect fields don't need initializing. 1989 if (Field->isAnonymousStructOrUnion() && 1990 (Field->getType()->isUnionType() 1991 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1992 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1993 return true; 1994 1995 if (!Inits.count(Field)) { 1996 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1997 if (!Diagnosed) { 1998 SemaRef.Diag(Dcl->getLocation(), 1999 SemaRef.getLangOpts().CPlusPlus20 2000 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init 2001 : diag::ext_constexpr_ctor_missing_init); 2002 Diagnosed = true; 2003 } 2004 SemaRef.Diag(Field->getLocation(), 2005 diag::note_constexpr_ctor_missing_init); 2006 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2007 return false; 2008 } 2009 } else if (Field->isAnonymousStructOrUnion()) { 2010 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 2011 for (auto *I : RD->fields()) 2012 // If an anonymous union contains an anonymous struct of which any member 2013 // is initialized, all members must be initialized. 2014 if (!RD->isUnion() || Inits.count(I)) 2015 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2016 Kind)) 2017 return false; 2018 } 2019 return true; 2020 } 2021 2022 /// Check the provided statement is allowed in a constexpr function 2023 /// definition. 2024 static bool 2025 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 2026 SmallVectorImpl<SourceLocation> &ReturnStmts, 2027 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 2028 SourceLocation &Cxx2bLoc, 2029 Sema::CheckConstexprKind Kind) { 2030 // - its function-body shall be [...] a compound-statement that contains only 2031 switch (S->getStmtClass()) { 2032 case Stmt::NullStmtClass: 2033 // - null statements, 2034 return true; 2035 2036 case Stmt::DeclStmtClass: 2037 // - static_assert-declarations 2038 // - using-declarations, 2039 // - using-directives, 2040 // - typedef declarations and alias-declarations that do not define 2041 // classes or enumerations, 2042 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 2043 return false; 2044 return true; 2045 2046 case Stmt::ReturnStmtClass: 2047 // - and exactly one return statement; 2048 if (isa<CXXConstructorDecl>(Dcl)) { 2049 // C++1y allows return statements in constexpr constructors. 2050 if (!Cxx1yLoc.isValid()) 2051 Cxx1yLoc = S->getBeginLoc(); 2052 return true; 2053 } 2054 2055 ReturnStmts.push_back(S->getBeginLoc()); 2056 return true; 2057 2058 case Stmt::AttributedStmtClass: 2059 // Attributes on a statement don't affect its formal kind and hence don't 2060 // affect its validity in a constexpr function. 2061 return CheckConstexprFunctionStmt( 2062 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts, 2063 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind); 2064 2065 case Stmt::CompoundStmtClass: { 2066 // C++1y allows compound-statements. 2067 if (!Cxx1yLoc.isValid()) 2068 Cxx1yLoc = S->getBeginLoc(); 2069 2070 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2071 for (auto *BodyIt : CompStmt->body()) { 2072 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2073 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2074 return false; 2075 } 2076 return true; 2077 } 2078 2079 case Stmt::IfStmtClass: { 2080 // C++1y allows if-statements. 2081 if (!Cxx1yLoc.isValid()) 2082 Cxx1yLoc = S->getBeginLoc(); 2083 2084 IfStmt *If = cast<IfStmt>(S); 2085 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2086 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2087 return false; 2088 if (If->getElse() && 2089 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2090 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2091 return false; 2092 return true; 2093 } 2094 2095 case Stmt::WhileStmtClass: 2096 case Stmt::DoStmtClass: 2097 case Stmt::ForStmtClass: 2098 case Stmt::CXXForRangeStmtClass: 2099 case Stmt::ContinueStmtClass: 2100 // C++1y allows all of these. We don't allow them as extensions in C++11, 2101 // because they don't make sense without variable mutation. 2102 if (!SemaRef.getLangOpts().CPlusPlus14) 2103 break; 2104 if (!Cxx1yLoc.isValid()) 2105 Cxx1yLoc = S->getBeginLoc(); 2106 for (Stmt *SubStmt : S->children()) { 2107 if (SubStmt && 2108 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2109 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2110 return false; 2111 } 2112 return true; 2113 2114 case Stmt::SwitchStmtClass: 2115 case Stmt::CaseStmtClass: 2116 case Stmt::DefaultStmtClass: 2117 case Stmt::BreakStmtClass: 2118 // C++1y allows switch-statements, and since they don't need variable 2119 // mutation, we can reasonably allow them in C++11 as an extension. 2120 if (!Cxx1yLoc.isValid()) 2121 Cxx1yLoc = S->getBeginLoc(); 2122 for (Stmt *SubStmt : S->children()) { 2123 if (SubStmt && 2124 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2125 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2126 return false; 2127 } 2128 return true; 2129 2130 case Stmt::LabelStmtClass: 2131 case Stmt::GotoStmtClass: 2132 if (Cxx2bLoc.isInvalid()) 2133 Cxx2bLoc = S->getBeginLoc(); 2134 for (Stmt *SubStmt : S->children()) { 2135 if (SubStmt && 2136 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2137 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2138 return false; 2139 } 2140 return true; 2141 2142 case Stmt::GCCAsmStmtClass: 2143 case Stmt::MSAsmStmtClass: 2144 // C++2a allows inline assembly statements. 2145 case Stmt::CXXTryStmtClass: 2146 if (Cxx2aLoc.isInvalid()) 2147 Cxx2aLoc = S->getBeginLoc(); 2148 for (Stmt *SubStmt : S->children()) { 2149 if (SubStmt && 2150 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2151 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2152 return false; 2153 } 2154 return true; 2155 2156 case Stmt::CXXCatchStmtClass: 2157 // Do not bother checking the language mode (already covered by the 2158 // try block check). 2159 if (!CheckConstexprFunctionStmt( 2160 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts, 2161 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2162 return false; 2163 return true; 2164 2165 default: 2166 if (!isa<Expr>(S)) 2167 break; 2168 2169 // C++1y allows expression-statements. 2170 if (!Cxx1yLoc.isValid()) 2171 Cxx1yLoc = S->getBeginLoc(); 2172 return true; 2173 } 2174 2175 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2176 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2177 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2178 } 2179 return false; 2180 } 2181 2182 /// Check the body for the given constexpr function declaration only contains 2183 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2184 /// 2185 /// \return true if the body is OK, false if we have found or diagnosed a 2186 /// problem. 2187 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2188 Stmt *Body, 2189 Sema::CheckConstexprKind Kind) { 2190 SmallVector<SourceLocation, 4> ReturnStmts; 2191 2192 if (isa<CXXTryStmt>(Body)) { 2193 // C++11 [dcl.constexpr]p3: 2194 // The definition of a constexpr function shall satisfy the following 2195 // constraints: [...] 2196 // - its function-body shall be = delete, = default, or a 2197 // compound-statement 2198 // 2199 // C++11 [dcl.constexpr]p4: 2200 // In the definition of a constexpr constructor, [...] 2201 // - its function-body shall not be a function-try-block; 2202 // 2203 // This restriction is lifted in C++2a, as long as inner statements also 2204 // apply the general constexpr rules. 2205 switch (Kind) { 2206 case Sema::CheckConstexprKind::CheckValid: 2207 if (!SemaRef.getLangOpts().CPlusPlus20) 2208 return false; 2209 break; 2210 2211 case Sema::CheckConstexprKind::Diagnose: 2212 SemaRef.Diag(Body->getBeginLoc(), 2213 !SemaRef.getLangOpts().CPlusPlus20 2214 ? diag::ext_constexpr_function_try_block_cxx20 2215 : diag::warn_cxx17_compat_constexpr_function_try_block) 2216 << isa<CXXConstructorDecl>(Dcl); 2217 break; 2218 } 2219 } 2220 2221 // - its function-body shall be [...] a compound-statement that contains only 2222 // [... list of cases ...] 2223 // 2224 // Note that walking the children here is enough to properly check for 2225 // CompoundStmt and CXXTryStmt body. 2226 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc; 2227 for (Stmt *SubStmt : Body->children()) { 2228 if (SubStmt && 2229 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2230 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2231 return false; 2232 } 2233 2234 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2235 // If this is only valid as an extension, report that we don't satisfy the 2236 // constraints of the current language. 2237 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2b) || 2238 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) || 2239 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2240 return false; 2241 } else if (Cxx2bLoc.isValid()) { 2242 SemaRef.Diag(Cxx2bLoc, 2243 SemaRef.getLangOpts().CPlusPlus2b 2244 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt 2245 : diag::ext_constexpr_body_invalid_stmt_cxx2b) 2246 << isa<CXXConstructorDecl>(Dcl); 2247 } else if (Cxx2aLoc.isValid()) { 2248 SemaRef.Diag(Cxx2aLoc, 2249 SemaRef.getLangOpts().CPlusPlus20 2250 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2251 : diag::ext_constexpr_body_invalid_stmt_cxx20) 2252 << isa<CXXConstructorDecl>(Dcl); 2253 } else if (Cxx1yLoc.isValid()) { 2254 SemaRef.Diag(Cxx1yLoc, 2255 SemaRef.getLangOpts().CPlusPlus14 2256 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2257 : diag::ext_constexpr_body_invalid_stmt) 2258 << isa<CXXConstructorDecl>(Dcl); 2259 } 2260 2261 if (const CXXConstructorDecl *Constructor 2262 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2263 const CXXRecordDecl *RD = Constructor->getParent(); 2264 // DR1359: 2265 // - every non-variant non-static data member and base class sub-object 2266 // shall be initialized; 2267 // DR1460: 2268 // - if the class is a union having variant members, exactly one of them 2269 // shall be initialized; 2270 if (RD->isUnion()) { 2271 if (Constructor->getNumCtorInitializers() == 0 && 2272 RD->hasVariantMembers()) { 2273 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2274 SemaRef.Diag( 2275 Dcl->getLocation(), 2276 SemaRef.getLangOpts().CPlusPlus20 2277 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2278 : diag::ext_constexpr_union_ctor_no_init); 2279 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2280 return false; 2281 } 2282 } 2283 } else if (!Constructor->isDependentContext() && 2284 !Constructor->isDelegatingConstructor()) { 2285 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2286 2287 // Skip detailed checking if we have enough initializers, and we would 2288 // allow at most one initializer per member. 2289 bool AnyAnonStructUnionMembers = false; 2290 unsigned Fields = 0; 2291 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2292 E = RD->field_end(); I != E; ++I, ++Fields) { 2293 if (I->isAnonymousStructOrUnion()) { 2294 AnyAnonStructUnionMembers = true; 2295 break; 2296 } 2297 } 2298 // DR1460: 2299 // - if the class is a union-like class, but is not a union, for each of 2300 // its anonymous union members having variant members, exactly one of 2301 // them shall be initialized; 2302 if (AnyAnonStructUnionMembers || 2303 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2304 // Check initialization of non-static data members. Base classes are 2305 // always initialized so do not need to be checked. Dependent bases 2306 // might not have initializers in the member initializer list. 2307 llvm::SmallSet<Decl*, 16> Inits; 2308 for (const auto *I: Constructor->inits()) { 2309 if (FieldDecl *FD = I->getMember()) 2310 Inits.insert(FD); 2311 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2312 Inits.insert(ID->chain_begin(), ID->chain_end()); 2313 } 2314 2315 bool Diagnosed = false; 2316 for (auto *I : RD->fields()) 2317 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2318 Kind)) 2319 return false; 2320 } 2321 } 2322 } else { 2323 if (ReturnStmts.empty()) { 2324 // C++1y doesn't require constexpr functions to contain a 'return' 2325 // statement. We still do, unless the return type might be void, because 2326 // otherwise if there's no return statement, the function cannot 2327 // be used in a core constant expression. 2328 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2329 (Dcl->getReturnType()->isVoidType() || 2330 Dcl->getReturnType()->isDependentType()); 2331 switch (Kind) { 2332 case Sema::CheckConstexprKind::Diagnose: 2333 SemaRef.Diag(Dcl->getLocation(), 2334 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2335 : diag::err_constexpr_body_no_return) 2336 << Dcl->isConsteval(); 2337 if (!OK) 2338 return false; 2339 break; 2340 2341 case Sema::CheckConstexprKind::CheckValid: 2342 // The formal requirements don't include this rule in C++14, even 2343 // though the "must be able to produce a constant expression" rules 2344 // still imply it in some cases. 2345 if (!SemaRef.getLangOpts().CPlusPlus14) 2346 return false; 2347 break; 2348 } 2349 } else if (ReturnStmts.size() > 1) { 2350 switch (Kind) { 2351 case Sema::CheckConstexprKind::Diagnose: 2352 SemaRef.Diag( 2353 ReturnStmts.back(), 2354 SemaRef.getLangOpts().CPlusPlus14 2355 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2356 : diag::ext_constexpr_body_multiple_return); 2357 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2358 SemaRef.Diag(ReturnStmts[I], 2359 diag::note_constexpr_body_previous_return); 2360 break; 2361 2362 case Sema::CheckConstexprKind::CheckValid: 2363 if (!SemaRef.getLangOpts().CPlusPlus14) 2364 return false; 2365 break; 2366 } 2367 } 2368 } 2369 2370 // C++11 [dcl.constexpr]p5: 2371 // if no function argument values exist such that the function invocation 2372 // substitution would produce a constant expression, the program is 2373 // ill-formed; no diagnostic required. 2374 // C++11 [dcl.constexpr]p3: 2375 // - every constructor call and implicit conversion used in initializing the 2376 // return value shall be one of those allowed in a constant expression. 2377 // C++11 [dcl.constexpr]p4: 2378 // - every constructor involved in initializing non-static data members and 2379 // base class sub-objects shall be a constexpr constructor. 2380 // 2381 // Note that this rule is distinct from the "requirements for a constexpr 2382 // function", so is not checked in CheckValid mode. 2383 SmallVector<PartialDiagnosticAt, 8> Diags; 2384 if (Kind == Sema::CheckConstexprKind::Diagnose && 2385 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2386 SemaRef.Diag(Dcl->getLocation(), 2387 diag::ext_constexpr_function_never_constant_expr) 2388 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2389 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2390 SemaRef.Diag(Diags[I].first, Diags[I].second); 2391 // Don't return false here: we allow this for compatibility in 2392 // system headers. 2393 } 2394 2395 return true; 2396 } 2397 2398 /// Get the class that is directly named by the current context. This is the 2399 /// class for which an unqualified-id in this scope could name a constructor 2400 /// or destructor. 2401 /// 2402 /// If the scope specifier denotes a class, this will be that class. 2403 /// If the scope specifier is empty, this will be the class whose 2404 /// member-specification we are currently within. Otherwise, there 2405 /// is no such class. 2406 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2407 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2408 2409 if (SS && SS->isInvalid()) 2410 return nullptr; 2411 2412 if (SS && SS->isNotEmpty()) { 2413 DeclContext *DC = computeDeclContext(*SS, true); 2414 return dyn_cast_or_null<CXXRecordDecl>(DC); 2415 } 2416 2417 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2418 } 2419 2420 /// isCurrentClassName - Determine whether the identifier II is the 2421 /// name of the class type currently being defined. In the case of 2422 /// nested classes, this will only return true if II is the name of 2423 /// the innermost class. 2424 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2425 const CXXScopeSpec *SS) { 2426 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2427 return CurDecl && &II == CurDecl->getIdentifier(); 2428 } 2429 2430 /// Determine whether the identifier II is a typo for the name of 2431 /// the class type currently being defined. If so, update it to the identifier 2432 /// that should have been used. 2433 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2434 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2435 2436 if (!getLangOpts().SpellChecking) 2437 return false; 2438 2439 CXXRecordDecl *CurDecl; 2440 if (SS && SS->isSet() && !SS->isInvalid()) { 2441 DeclContext *DC = computeDeclContext(*SS, true); 2442 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2443 } else 2444 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2445 2446 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2447 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2448 < II->getLength()) { 2449 II = CurDecl->getIdentifier(); 2450 return true; 2451 } 2452 2453 return false; 2454 } 2455 2456 /// Determine whether the given class is a base class of the given 2457 /// class, including looking at dependent bases. 2458 static bool findCircularInheritance(const CXXRecordDecl *Class, 2459 const CXXRecordDecl *Current) { 2460 SmallVector<const CXXRecordDecl*, 8> Queue; 2461 2462 Class = Class->getCanonicalDecl(); 2463 while (true) { 2464 for (const auto &I : Current->bases()) { 2465 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2466 if (!Base) 2467 continue; 2468 2469 Base = Base->getDefinition(); 2470 if (!Base) 2471 continue; 2472 2473 if (Base->getCanonicalDecl() == Class) 2474 return true; 2475 2476 Queue.push_back(Base); 2477 } 2478 2479 if (Queue.empty()) 2480 return false; 2481 2482 Current = Queue.pop_back_val(); 2483 } 2484 2485 return false; 2486 } 2487 2488 /// Check the validity of a C++ base class specifier. 2489 /// 2490 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2491 /// and returns NULL otherwise. 2492 CXXBaseSpecifier * 2493 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2494 SourceRange SpecifierRange, 2495 bool Virtual, AccessSpecifier Access, 2496 TypeSourceInfo *TInfo, 2497 SourceLocation EllipsisLoc) { 2498 QualType BaseType = TInfo->getType(); 2499 if (BaseType->containsErrors()) { 2500 // Already emitted a diagnostic when parsing the error type. 2501 return nullptr; 2502 } 2503 // C++ [class.union]p1: 2504 // A union shall not have base classes. 2505 if (Class->isUnion()) { 2506 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2507 << SpecifierRange; 2508 return nullptr; 2509 } 2510 2511 if (EllipsisLoc.isValid() && 2512 !TInfo->getType()->containsUnexpandedParameterPack()) { 2513 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2514 << TInfo->getTypeLoc().getSourceRange(); 2515 EllipsisLoc = SourceLocation(); 2516 } 2517 2518 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2519 2520 if (BaseType->isDependentType()) { 2521 // Make sure that we don't have circular inheritance among our dependent 2522 // bases. For non-dependent bases, the check for completeness below handles 2523 // this. 2524 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2525 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2526 ((BaseDecl = BaseDecl->getDefinition()) && 2527 findCircularInheritance(Class, BaseDecl))) { 2528 Diag(BaseLoc, diag::err_circular_inheritance) 2529 << BaseType << Context.getTypeDeclType(Class); 2530 2531 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2532 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2533 << BaseType; 2534 2535 return nullptr; 2536 } 2537 } 2538 2539 // Make sure that we don't make an ill-formed AST where the type of the 2540 // Class is non-dependent and its attached base class specifier is an 2541 // dependent type, which violates invariants in many clang code paths (e.g. 2542 // constexpr evaluator). If this case happens (in errory-recovery mode), we 2543 // explicitly mark the Class decl invalid. The diagnostic was already 2544 // emitted. 2545 if (!Class->getTypeForDecl()->isDependentType()) 2546 Class->setInvalidDecl(); 2547 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2548 Class->getTagKind() == TTK_Class, 2549 Access, TInfo, EllipsisLoc); 2550 } 2551 2552 // Base specifiers must be record types. 2553 if (!BaseType->isRecordType()) { 2554 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2555 return nullptr; 2556 } 2557 2558 // C++ [class.union]p1: 2559 // A union shall not be used as a base class. 2560 if (BaseType->isUnionType()) { 2561 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2562 return nullptr; 2563 } 2564 2565 // For the MS ABI, propagate DLL attributes to base class templates. 2566 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2567 if (Attr *ClassAttr = getDLLAttr(Class)) { 2568 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2569 BaseType->getAsCXXRecordDecl())) { 2570 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2571 BaseLoc); 2572 } 2573 } 2574 } 2575 2576 // C++ [class.derived]p2: 2577 // The class-name in a base-specifier shall not be an incompletely 2578 // defined class. 2579 if (RequireCompleteType(BaseLoc, BaseType, 2580 diag::err_incomplete_base_class, SpecifierRange)) { 2581 Class->setInvalidDecl(); 2582 return nullptr; 2583 } 2584 2585 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2586 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2587 assert(BaseDecl && "Record type has no declaration"); 2588 BaseDecl = BaseDecl->getDefinition(); 2589 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2590 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2591 assert(CXXBaseDecl && "Base type is not a C++ type"); 2592 2593 // Microsoft docs say: 2594 // "If a base-class has a code_seg attribute, derived classes must have the 2595 // same attribute." 2596 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2597 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2598 if ((DerivedCSA || BaseCSA) && 2599 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2600 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2601 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2602 << CXXBaseDecl; 2603 return nullptr; 2604 } 2605 2606 // A class which contains a flexible array member is not suitable for use as a 2607 // base class: 2608 // - If the layout determines that a base comes before another base, 2609 // the flexible array member would index into the subsequent base. 2610 // - If the layout determines that base comes before the derived class, 2611 // the flexible array member would index into the derived class. 2612 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2613 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2614 << CXXBaseDecl->getDeclName(); 2615 return nullptr; 2616 } 2617 2618 // C++ [class]p3: 2619 // If a class is marked final and it appears as a base-type-specifier in 2620 // base-clause, the program is ill-formed. 2621 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2622 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2623 << CXXBaseDecl->getDeclName() 2624 << FA->isSpelledAsSealed(); 2625 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2626 << CXXBaseDecl->getDeclName() << FA->getRange(); 2627 return nullptr; 2628 } 2629 2630 if (BaseDecl->isInvalidDecl()) 2631 Class->setInvalidDecl(); 2632 2633 // Create the base specifier. 2634 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2635 Class->getTagKind() == TTK_Class, 2636 Access, TInfo, EllipsisLoc); 2637 } 2638 2639 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2640 /// one entry in the base class list of a class specifier, for 2641 /// example: 2642 /// class foo : public bar, virtual private baz { 2643 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2644 BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2645 const ParsedAttributesView &Attributes, 2646 bool Virtual, AccessSpecifier Access, 2647 ParsedType basetype, SourceLocation BaseLoc, 2648 SourceLocation EllipsisLoc) { 2649 if (!classdecl) 2650 return true; 2651 2652 AdjustDeclIfTemplate(classdecl); 2653 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2654 if (!Class) 2655 return true; 2656 2657 // We haven't yet attached the base specifiers. 2658 Class->setIsParsingBaseSpecifiers(); 2659 2660 // We do not support any C++11 attributes on base-specifiers yet. 2661 // Diagnose any attributes we see. 2662 for (const ParsedAttr &AL : Attributes) { 2663 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2664 continue; 2665 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2666 ? (unsigned)diag::warn_unknown_attribute_ignored 2667 : (unsigned)diag::err_base_specifier_attribute) 2668 << AL << AL.getRange(); 2669 } 2670 2671 TypeSourceInfo *TInfo = nullptr; 2672 GetTypeFromParser(basetype, &TInfo); 2673 2674 if (EllipsisLoc.isInvalid() && 2675 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2676 UPPC_BaseType)) 2677 return true; 2678 2679 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2680 Virtual, Access, TInfo, 2681 EllipsisLoc)) 2682 return BaseSpec; 2683 else 2684 Class->setInvalidDecl(); 2685 2686 return true; 2687 } 2688 2689 /// Use small set to collect indirect bases. As this is only used 2690 /// locally, there's no need to abstract the small size parameter. 2691 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2692 2693 /// Recursively add the bases of Type. Don't add Type itself. 2694 static void 2695 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2696 const QualType &Type) 2697 { 2698 // Even though the incoming type is a base, it might not be 2699 // a class -- it could be a template parm, for instance. 2700 if (auto Rec = Type->getAs<RecordType>()) { 2701 auto Decl = Rec->getAsCXXRecordDecl(); 2702 2703 // Iterate over its bases. 2704 for (const auto &BaseSpec : Decl->bases()) { 2705 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2706 .getUnqualifiedType(); 2707 if (Set.insert(Base).second) 2708 // If we've not already seen it, recurse. 2709 NoteIndirectBases(Context, Set, Base); 2710 } 2711 } 2712 } 2713 2714 /// Performs the actual work of attaching the given base class 2715 /// specifiers to a C++ class. 2716 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2717 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2718 if (Bases.empty()) 2719 return false; 2720 2721 // Used to keep track of which base types we have already seen, so 2722 // that we can properly diagnose redundant direct base types. Note 2723 // that the key is always the unqualified canonical type of the base 2724 // class. 2725 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2726 2727 // Used to track indirect bases so we can see if a direct base is 2728 // ambiguous. 2729 IndirectBaseSet IndirectBaseTypes; 2730 2731 // Copy non-redundant base specifiers into permanent storage. 2732 unsigned NumGoodBases = 0; 2733 bool Invalid = false; 2734 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2735 QualType NewBaseType 2736 = Context.getCanonicalType(Bases[idx]->getType()); 2737 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2738 2739 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2740 if (KnownBase) { 2741 // C++ [class.mi]p3: 2742 // A class shall not be specified as a direct base class of a 2743 // derived class more than once. 2744 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2745 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2746 2747 // Delete the duplicate base class specifier; we're going to 2748 // overwrite its pointer later. 2749 Context.Deallocate(Bases[idx]); 2750 2751 Invalid = true; 2752 } else { 2753 // Okay, add this new base class. 2754 KnownBase = Bases[idx]; 2755 Bases[NumGoodBases++] = Bases[idx]; 2756 2757 if (NewBaseType->isDependentType()) 2758 continue; 2759 // Note this base's direct & indirect bases, if there could be ambiguity. 2760 if (Bases.size() > 1) 2761 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2762 2763 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2764 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2765 if (Class->isInterface() && 2766 (!RD->isInterfaceLike() || 2767 KnownBase->getAccessSpecifier() != AS_public)) { 2768 // The Microsoft extension __interface does not permit bases that 2769 // are not themselves public interfaces. 2770 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2771 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2772 << RD->getSourceRange(); 2773 Invalid = true; 2774 } 2775 if (RD->hasAttr<WeakAttr>()) 2776 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2777 } 2778 } 2779 } 2780 2781 // Attach the remaining base class specifiers to the derived class. 2782 Class->setBases(Bases.data(), NumGoodBases); 2783 2784 // Check that the only base classes that are duplicate are virtual. 2785 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2786 // Check whether this direct base is inaccessible due to ambiguity. 2787 QualType BaseType = Bases[idx]->getType(); 2788 2789 // Skip all dependent types in templates being used as base specifiers. 2790 // Checks below assume that the base specifier is a CXXRecord. 2791 if (BaseType->isDependentType()) 2792 continue; 2793 2794 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2795 .getUnqualifiedType(); 2796 2797 if (IndirectBaseTypes.count(CanonicalBase)) { 2798 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2799 /*DetectVirtual=*/true); 2800 bool found 2801 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2802 assert(found); 2803 (void)found; 2804 2805 if (Paths.isAmbiguous(CanonicalBase)) 2806 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2807 << BaseType << getAmbiguousPathsDisplayString(Paths) 2808 << Bases[idx]->getSourceRange(); 2809 else 2810 assert(Bases[idx]->isVirtual()); 2811 } 2812 2813 // Delete the base class specifier, since its data has been copied 2814 // into the CXXRecordDecl. 2815 Context.Deallocate(Bases[idx]); 2816 } 2817 2818 return Invalid; 2819 } 2820 2821 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2822 /// class, after checking whether there are any duplicate base 2823 /// classes. 2824 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2825 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2826 if (!ClassDecl || Bases.empty()) 2827 return; 2828 2829 AdjustDeclIfTemplate(ClassDecl); 2830 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2831 } 2832 2833 /// Determine whether the type \p Derived is a C++ class that is 2834 /// derived from the type \p Base. 2835 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2836 if (!getLangOpts().CPlusPlus) 2837 return false; 2838 2839 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2840 if (!DerivedRD) 2841 return false; 2842 2843 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2844 if (!BaseRD) 2845 return false; 2846 2847 // If either the base or the derived type is invalid, don't try to 2848 // check whether one is derived from the other. 2849 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2850 return false; 2851 2852 // FIXME: In a modules build, do we need the entire path to be visible for us 2853 // to be able to use the inheritance relationship? 2854 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2855 return false; 2856 2857 return DerivedRD->isDerivedFrom(BaseRD); 2858 } 2859 2860 /// Determine whether the type \p Derived is a C++ class that is 2861 /// derived from the type \p Base. 2862 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2863 CXXBasePaths &Paths) { 2864 if (!getLangOpts().CPlusPlus) 2865 return false; 2866 2867 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2868 if (!DerivedRD) 2869 return false; 2870 2871 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2872 if (!BaseRD) 2873 return false; 2874 2875 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2876 return false; 2877 2878 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2879 } 2880 2881 static void BuildBasePathArray(const CXXBasePath &Path, 2882 CXXCastPath &BasePathArray) { 2883 // We first go backward and check if we have a virtual base. 2884 // FIXME: It would be better if CXXBasePath had the base specifier for 2885 // the nearest virtual base. 2886 unsigned Start = 0; 2887 for (unsigned I = Path.size(); I != 0; --I) { 2888 if (Path[I - 1].Base->isVirtual()) { 2889 Start = I - 1; 2890 break; 2891 } 2892 } 2893 2894 // Now add all bases. 2895 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2896 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2897 } 2898 2899 2900 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2901 CXXCastPath &BasePathArray) { 2902 assert(BasePathArray.empty() && "Base path array must be empty!"); 2903 assert(Paths.isRecordingPaths() && "Must record paths!"); 2904 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2905 } 2906 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2907 /// conversion (where Derived and Base are class types) is 2908 /// well-formed, meaning that the conversion is unambiguous (and 2909 /// that all of the base classes are accessible). Returns true 2910 /// and emits a diagnostic if the code is ill-formed, returns false 2911 /// otherwise. Loc is the location where this routine should point to 2912 /// if there is an error, and Range is the source range to highlight 2913 /// if there is an error. 2914 /// 2915 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the 2916 /// diagnostic for the respective type of error will be suppressed, but the 2917 /// check for ill-formed code will still be performed. 2918 bool 2919 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2920 unsigned InaccessibleBaseID, 2921 unsigned AmbiguousBaseConvID, 2922 SourceLocation Loc, SourceRange Range, 2923 DeclarationName Name, 2924 CXXCastPath *BasePath, 2925 bool IgnoreAccess) { 2926 // First, determine whether the path from Derived to Base is 2927 // ambiguous. This is slightly more expensive than checking whether 2928 // the Derived to Base conversion exists, because here we need to 2929 // explore multiple paths to determine if there is an ambiguity. 2930 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2931 /*DetectVirtual=*/false); 2932 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2933 if (!DerivationOkay) 2934 return true; 2935 2936 const CXXBasePath *Path = nullptr; 2937 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2938 Path = &Paths.front(); 2939 2940 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2941 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2942 // user to access such bases. 2943 if (!Path && getLangOpts().MSVCCompat) { 2944 for (const CXXBasePath &PossiblePath : Paths) { 2945 if (PossiblePath.size() == 1) { 2946 Path = &PossiblePath; 2947 if (AmbiguousBaseConvID) 2948 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2949 << Base << Derived << Range; 2950 break; 2951 } 2952 } 2953 } 2954 2955 if (Path) { 2956 if (!IgnoreAccess) { 2957 // Check that the base class can be accessed. 2958 switch ( 2959 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2960 case AR_inaccessible: 2961 return true; 2962 case AR_accessible: 2963 case AR_dependent: 2964 case AR_delayed: 2965 break; 2966 } 2967 } 2968 2969 // Build a base path if necessary. 2970 if (BasePath) 2971 ::BuildBasePathArray(*Path, *BasePath); 2972 return false; 2973 } 2974 2975 if (AmbiguousBaseConvID) { 2976 // We know that the derived-to-base conversion is ambiguous, and 2977 // we're going to produce a diagnostic. Perform the derived-to-base 2978 // search just one more time to compute all of the possible paths so 2979 // that we can print them out. This is more expensive than any of 2980 // the previous derived-to-base checks we've done, but at this point 2981 // performance isn't as much of an issue. 2982 Paths.clear(); 2983 Paths.setRecordingPaths(true); 2984 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2985 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2986 (void)StillOkay; 2987 2988 // Build up a textual representation of the ambiguous paths, e.g., 2989 // D -> B -> A, that will be used to illustrate the ambiguous 2990 // conversions in the diagnostic. We only print one of the paths 2991 // to each base class subobject. 2992 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2993 2994 Diag(Loc, AmbiguousBaseConvID) 2995 << Derived << Base << PathDisplayStr << Range << Name; 2996 } 2997 return true; 2998 } 2999 3000 bool 3001 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 3002 SourceLocation Loc, SourceRange Range, 3003 CXXCastPath *BasePath, 3004 bool IgnoreAccess) { 3005 return CheckDerivedToBaseConversion( 3006 Derived, Base, diag::err_upcast_to_inaccessible_base, 3007 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 3008 BasePath, IgnoreAccess); 3009 } 3010 3011 3012 /// Builds a string representing ambiguous paths from a 3013 /// specific derived class to different subobjects of the same base 3014 /// class. 3015 /// 3016 /// This function builds a string that can be used in error messages 3017 /// to show the different paths that one can take through the 3018 /// inheritance hierarchy to go from the derived class to different 3019 /// subobjects of a base class. The result looks something like this: 3020 /// @code 3021 /// struct D -> struct B -> struct A 3022 /// struct D -> struct C -> struct A 3023 /// @endcode 3024 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 3025 std::string PathDisplayStr; 3026 std::set<unsigned> DisplayedPaths; 3027 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3028 Path != Paths.end(); ++Path) { 3029 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 3030 // We haven't displayed a path to this particular base 3031 // class subobject yet. 3032 PathDisplayStr += "\n "; 3033 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 3034 for (CXXBasePath::const_iterator Element = Path->begin(); 3035 Element != Path->end(); ++Element) 3036 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 3037 } 3038 } 3039 3040 return PathDisplayStr; 3041 } 3042 3043 //===----------------------------------------------------------------------===// 3044 // C++ class member Handling 3045 //===----------------------------------------------------------------------===// 3046 3047 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 3048 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 3049 SourceLocation ColonLoc, 3050 const ParsedAttributesView &Attrs) { 3051 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 3052 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 3053 ASLoc, ColonLoc); 3054 CurContext->addHiddenDecl(ASDecl); 3055 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 3056 } 3057 3058 /// CheckOverrideControl - Check C++11 override control semantics. 3059 void Sema::CheckOverrideControl(NamedDecl *D) { 3060 if (D->isInvalidDecl()) 3061 return; 3062 3063 // We only care about "override" and "final" declarations. 3064 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 3065 return; 3066 3067 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3068 3069 // We can't check dependent instance methods. 3070 if (MD && MD->isInstance() && 3071 (MD->getParent()->hasAnyDependentBases() || 3072 MD->getType()->isDependentType())) 3073 return; 3074 3075 if (MD && !MD->isVirtual()) { 3076 // If we have a non-virtual method, check if if hides a virtual method. 3077 // (In that case, it's most likely the method has the wrong type.) 3078 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 3079 FindHiddenVirtualMethods(MD, OverloadedMethods); 3080 3081 if (!OverloadedMethods.empty()) { 3082 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3083 Diag(OA->getLocation(), 3084 diag::override_keyword_hides_virtual_member_function) 3085 << "override" << (OverloadedMethods.size() > 1); 3086 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3087 Diag(FA->getLocation(), 3088 diag::override_keyword_hides_virtual_member_function) 3089 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3090 << (OverloadedMethods.size() > 1); 3091 } 3092 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3093 MD->setInvalidDecl(); 3094 return; 3095 } 3096 // Fall through into the general case diagnostic. 3097 // FIXME: We might want to attempt typo correction here. 3098 } 3099 3100 if (!MD || !MD->isVirtual()) { 3101 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3102 Diag(OA->getLocation(), 3103 diag::override_keyword_only_allowed_on_virtual_member_functions) 3104 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3105 D->dropAttr<OverrideAttr>(); 3106 } 3107 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3108 Diag(FA->getLocation(), 3109 diag::override_keyword_only_allowed_on_virtual_member_functions) 3110 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3111 << FixItHint::CreateRemoval(FA->getLocation()); 3112 D->dropAttr<FinalAttr>(); 3113 } 3114 return; 3115 } 3116 3117 // C++11 [class.virtual]p5: 3118 // If a function is marked with the virt-specifier override and 3119 // does not override a member function of a base class, the program is 3120 // ill-formed. 3121 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3122 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3123 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3124 << MD->getDeclName(); 3125 } 3126 3127 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { 3128 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3129 return; 3130 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3131 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3132 return; 3133 3134 SourceLocation Loc = MD->getLocation(); 3135 SourceLocation SpellingLoc = Loc; 3136 if (getSourceManager().isMacroArgExpansion(Loc)) 3137 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3138 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3139 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3140 return; 3141 3142 if (MD->size_overridden_methods() > 0) { 3143 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { 3144 unsigned DiagID = 3145 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation()) 3146 ? DiagInconsistent 3147 : DiagSuggest; 3148 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3149 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3150 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3151 }; 3152 if (isa<CXXDestructorDecl>(MD)) 3153 EmitDiag( 3154 diag::warn_inconsistent_destructor_marked_not_override_overriding, 3155 diag::warn_suggest_destructor_marked_not_override_overriding); 3156 else 3157 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding, 3158 diag::warn_suggest_function_marked_not_override_overriding); 3159 } 3160 } 3161 3162 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3163 /// function overrides a virtual member function marked 'final', according to 3164 /// C++11 [class.virtual]p4. 3165 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3166 const CXXMethodDecl *Old) { 3167 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3168 if (!FA) 3169 return false; 3170 3171 Diag(New->getLocation(), diag::err_final_function_overridden) 3172 << New->getDeclName() 3173 << FA->isSpelledAsSealed(); 3174 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3175 return true; 3176 } 3177 3178 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3179 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3180 // FIXME: Destruction of ObjC lifetime types has side-effects. 3181 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3182 return !RD->isCompleteDefinition() || 3183 !RD->hasTrivialDefaultConstructor() || 3184 !RD->hasTrivialDestructor(); 3185 return false; 3186 } 3187 3188 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3189 ParsedAttributesView::const_iterator Itr = 3190 llvm::find_if(list, [](const ParsedAttr &AL) { 3191 return AL.isDeclspecPropertyAttribute(); 3192 }); 3193 if (Itr != list.end()) 3194 return &*Itr; 3195 return nullptr; 3196 } 3197 3198 // Check if there is a field shadowing. 3199 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3200 DeclarationName FieldName, 3201 const CXXRecordDecl *RD, 3202 bool DeclIsField) { 3203 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3204 return; 3205 3206 // To record a shadowed field in a base 3207 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3208 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3209 CXXBasePath &Path) { 3210 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3211 // Record an ambiguous path directly 3212 if (Bases.find(Base) != Bases.end()) 3213 return true; 3214 for (const auto Field : Base->lookup(FieldName)) { 3215 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3216 Field->getAccess() != AS_private) { 3217 assert(Field->getAccess() != AS_none); 3218 assert(Bases.find(Base) == Bases.end()); 3219 Bases[Base] = Field; 3220 return true; 3221 } 3222 } 3223 return false; 3224 }; 3225 3226 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3227 /*DetectVirtual=*/true); 3228 if (!RD->lookupInBases(FieldShadowed, Paths)) 3229 return; 3230 3231 for (const auto &P : Paths) { 3232 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3233 auto It = Bases.find(Base); 3234 // Skip duplicated bases 3235 if (It == Bases.end()) 3236 continue; 3237 auto BaseField = It->second; 3238 assert(BaseField->getAccess() != AS_private); 3239 if (AS_none != 3240 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3241 Diag(Loc, diag::warn_shadow_field) 3242 << FieldName << RD << Base << DeclIsField; 3243 Diag(BaseField->getLocation(), diag::note_shadow_field); 3244 Bases.erase(It); 3245 } 3246 } 3247 } 3248 3249 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3250 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3251 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3252 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3253 /// present (but parsing it has been deferred). 3254 NamedDecl * 3255 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3256 MultiTemplateParamsArg TemplateParameterLists, 3257 Expr *BW, const VirtSpecifiers &VS, 3258 InClassInitStyle InitStyle) { 3259 const DeclSpec &DS = D.getDeclSpec(); 3260 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3261 DeclarationName Name = NameInfo.getName(); 3262 SourceLocation Loc = NameInfo.getLoc(); 3263 3264 // For anonymous bitfields, the location should point to the type. 3265 if (Loc.isInvalid()) 3266 Loc = D.getBeginLoc(); 3267 3268 Expr *BitWidth = static_cast<Expr*>(BW); 3269 3270 assert(isa<CXXRecordDecl>(CurContext)); 3271 assert(!DS.isFriendSpecified()); 3272 3273 bool isFunc = D.isDeclarationOfFunction(); 3274 const ParsedAttr *MSPropertyAttr = 3275 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3276 3277 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3278 // The Microsoft extension __interface only permits public member functions 3279 // and prohibits constructors, destructors, operators, non-public member 3280 // functions, static methods and data members. 3281 unsigned InvalidDecl; 3282 bool ShowDeclName = true; 3283 if (!isFunc && 3284 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3285 InvalidDecl = 0; 3286 else if (!isFunc) 3287 InvalidDecl = 1; 3288 else if (AS != AS_public) 3289 InvalidDecl = 2; 3290 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3291 InvalidDecl = 3; 3292 else switch (Name.getNameKind()) { 3293 case DeclarationName::CXXConstructorName: 3294 InvalidDecl = 4; 3295 ShowDeclName = false; 3296 break; 3297 3298 case DeclarationName::CXXDestructorName: 3299 InvalidDecl = 5; 3300 ShowDeclName = false; 3301 break; 3302 3303 case DeclarationName::CXXOperatorName: 3304 case DeclarationName::CXXConversionFunctionName: 3305 InvalidDecl = 6; 3306 break; 3307 3308 default: 3309 InvalidDecl = 0; 3310 break; 3311 } 3312 3313 if (InvalidDecl) { 3314 if (ShowDeclName) 3315 Diag(Loc, diag::err_invalid_member_in_interface) 3316 << (InvalidDecl-1) << Name; 3317 else 3318 Diag(Loc, diag::err_invalid_member_in_interface) 3319 << (InvalidDecl-1) << ""; 3320 return nullptr; 3321 } 3322 } 3323 3324 // C++ 9.2p6: A member shall not be declared to have automatic storage 3325 // duration (auto, register) or with the extern storage-class-specifier. 3326 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3327 // data members and cannot be applied to names declared const or static, 3328 // and cannot be applied to reference members. 3329 switch (DS.getStorageClassSpec()) { 3330 case DeclSpec::SCS_unspecified: 3331 case DeclSpec::SCS_typedef: 3332 case DeclSpec::SCS_static: 3333 break; 3334 case DeclSpec::SCS_mutable: 3335 if (isFunc) { 3336 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3337 3338 // FIXME: It would be nicer if the keyword was ignored only for this 3339 // declarator. Otherwise we could get follow-up errors. 3340 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3341 } 3342 break; 3343 default: 3344 Diag(DS.getStorageClassSpecLoc(), 3345 diag::err_storageclass_invalid_for_member); 3346 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3347 break; 3348 } 3349 3350 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3351 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3352 !isFunc); 3353 3354 if (DS.hasConstexprSpecifier() && isInstField) { 3355 SemaDiagnosticBuilder B = 3356 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3357 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3358 if (InitStyle == ICIS_NoInit) { 3359 B << 0 << 0; 3360 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3361 B << FixItHint::CreateRemoval(ConstexprLoc); 3362 else { 3363 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3364 D.getMutableDeclSpec().ClearConstexprSpec(); 3365 const char *PrevSpec; 3366 unsigned DiagID; 3367 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3368 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3369 (void)Failed; 3370 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3371 } 3372 } else { 3373 B << 1; 3374 const char *PrevSpec; 3375 unsigned DiagID; 3376 if (D.getMutableDeclSpec().SetStorageClassSpec( 3377 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3378 Context.getPrintingPolicy())) { 3379 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3380 "This is the only DeclSpec that should fail to be applied"); 3381 B << 1; 3382 } else { 3383 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3384 isInstField = false; 3385 } 3386 } 3387 } 3388 3389 NamedDecl *Member; 3390 if (isInstField) { 3391 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3392 3393 // Data members must have identifiers for names. 3394 if (!Name.isIdentifier()) { 3395 Diag(Loc, diag::err_bad_variable_name) 3396 << Name; 3397 return nullptr; 3398 } 3399 3400 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3401 3402 // Member field could not be with "template" keyword. 3403 // So TemplateParameterLists should be empty in this case. 3404 if (TemplateParameterLists.size()) { 3405 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3406 if (TemplateParams->size()) { 3407 // There is no such thing as a member field template. 3408 Diag(D.getIdentifierLoc(), diag::err_template_member) 3409 << II 3410 << SourceRange(TemplateParams->getTemplateLoc(), 3411 TemplateParams->getRAngleLoc()); 3412 } else { 3413 // There is an extraneous 'template<>' for this member. 3414 Diag(TemplateParams->getTemplateLoc(), 3415 diag::err_template_member_noparams) 3416 << II 3417 << SourceRange(TemplateParams->getTemplateLoc(), 3418 TemplateParams->getRAngleLoc()); 3419 } 3420 return nullptr; 3421 } 3422 3423 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 3424 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments) 3425 << II 3426 << SourceRange(D.getName().TemplateId->LAngleLoc, 3427 D.getName().TemplateId->RAngleLoc) 3428 << D.getName().TemplateId->LAngleLoc; 3429 D.SetIdentifier(Name.getAsIdentifierInfo(), Loc); 3430 } 3431 3432 if (SS.isSet() && !SS.isInvalid()) { 3433 // The user provided a superfluous scope specifier inside a class 3434 // definition: 3435 // 3436 // class X { 3437 // int X::member; 3438 // }; 3439 if (DeclContext *DC = computeDeclContext(SS, false)) 3440 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3441 D.getName().getKind() == 3442 UnqualifiedIdKind::IK_TemplateId); 3443 else 3444 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3445 << Name << SS.getRange(); 3446 3447 SS.clear(); 3448 } 3449 3450 if (MSPropertyAttr) { 3451 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3452 BitWidth, InitStyle, AS, *MSPropertyAttr); 3453 if (!Member) 3454 return nullptr; 3455 isInstField = false; 3456 } else { 3457 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3458 BitWidth, InitStyle, AS); 3459 if (!Member) 3460 return nullptr; 3461 } 3462 3463 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3464 } else { 3465 Member = HandleDeclarator(S, D, TemplateParameterLists); 3466 if (!Member) 3467 return nullptr; 3468 3469 // Non-instance-fields can't have a bitfield. 3470 if (BitWidth) { 3471 if (Member->isInvalidDecl()) { 3472 // don't emit another diagnostic. 3473 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3474 // C++ 9.6p3: A bit-field shall not be a static member. 3475 // "static member 'A' cannot be a bit-field" 3476 Diag(Loc, diag::err_static_not_bitfield) 3477 << Name << BitWidth->getSourceRange(); 3478 } else if (isa<TypedefDecl>(Member)) { 3479 // "typedef member 'x' cannot be a bit-field" 3480 Diag(Loc, diag::err_typedef_not_bitfield) 3481 << Name << BitWidth->getSourceRange(); 3482 } else { 3483 // A function typedef ("typedef int f(); f a;"). 3484 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3485 Diag(Loc, diag::err_not_integral_type_bitfield) 3486 << Name << cast<ValueDecl>(Member)->getType() 3487 << BitWidth->getSourceRange(); 3488 } 3489 3490 BitWidth = nullptr; 3491 Member->setInvalidDecl(); 3492 } 3493 3494 NamedDecl *NonTemplateMember = Member; 3495 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3496 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3497 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3498 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3499 3500 Member->setAccess(AS); 3501 3502 // If we have declared a member function template or static data member 3503 // template, set the access of the templated declaration as well. 3504 if (NonTemplateMember != Member) 3505 NonTemplateMember->setAccess(AS); 3506 3507 // C++ [temp.deduct.guide]p3: 3508 // A deduction guide [...] for a member class template [shall be 3509 // declared] with the same access [as the template]. 3510 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3511 auto *TD = DG->getDeducedTemplate(); 3512 // Access specifiers are only meaningful if both the template and the 3513 // deduction guide are from the same scope. 3514 if (AS != TD->getAccess() && 3515 TD->getDeclContext()->getRedeclContext()->Equals( 3516 DG->getDeclContext()->getRedeclContext())) { 3517 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3518 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3519 << TD->getAccess(); 3520 const AccessSpecDecl *LastAccessSpec = nullptr; 3521 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3522 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3523 LastAccessSpec = AccessSpec; 3524 } 3525 assert(LastAccessSpec && "differing access with no access specifier"); 3526 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3527 << AS; 3528 } 3529 } 3530 } 3531 3532 if (VS.isOverrideSpecified()) 3533 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3534 AttributeCommonInfo::AS_Keyword)); 3535 if (VS.isFinalSpecified()) 3536 Member->addAttr(FinalAttr::Create( 3537 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3538 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3539 3540 if (VS.getLastLocation().isValid()) { 3541 // Update the end location of a method that has a virt-specifiers. 3542 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3543 MD->setRangeEnd(VS.getLastLocation()); 3544 } 3545 3546 CheckOverrideControl(Member); 3547 3548 assert((Name || isInstField) && "No identifier for non-field ?"); 3549 3550 if (isInstField) { 3551 FieldDecl *FD = cast<FieldDecl>(Member); 3552 FieldCollector->Add(FD); 3553 3554 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3555 // Remember all explicit private FieldDecls that have a name, no side 3556 // effects and are not part of a dependent type declaration. 3557 if (!FD->isImplicit() && FD->getDeclName() && 3558 FD->getAccess() == AS_private && 3559 !FD->hasAttr<UnusedAttr>() && 3560 !FD->getParent()->isDependentContext() && 3561 !InitializationHasSideEffects(*FD)) 3562 UnusedPrivateFields.insert(FD); 3563 } 3564 } 3565 3566 return Member; 3567 } 3568 3569 namespace { 3570 class UninitializedFieldVisitor 3571 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3572 Sema &S; 3573 // List of Decls to generate a warning on. Also remove Decls that become 3574 // initialized. 3575 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3576 // List of base classes of the record. Classes are removed after their 3577 // initializers. 3578 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3579 // Vector of decls to be removed from the Decl set prior to visiting the 3580 // nodes. These Decls may have been initialized in the prior initializer. 3581 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3582 // If non-null, add a note to the warning pointing back to the constructor. 3583 const CXXConstructorDecl *Constructor; 3584 // Variables to hold state when processing an initializer list. When 3585 // InitList is true, special case initialization of FieldDecls matching 3586 // InitListFieldDecl. 3587 bool InitList; 3588 FieldDecl *InitListFieldDecl; 3589 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3590 3591 public: 3592 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3593 UninitializedFieldVisitor(Sema &S, 3594 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3595 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3596 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3597 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3598 3599 // Returns true if the use of ME is not an uninitialized use. 3600 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3601 bool CheckReferenceOnly) { 3602 llvm::SmallVector<FieldDecl*, 4> Fields; 3603 bool ReferenceField = false; 3604 while (ME) { 3605 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3606 if (!FD) 3607 return false; 3608 Fields.push_back(FD); 3609 if (FD->getType()->isReferenceType()) 3610 ReferenceField = true; 3611 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3612 } 3613 3614 // Binding a reference to an uninitialized field is not an 3615 // uninitialized use. 3616 if (CheckReferenceOnly && !ReferenceField) 3617 return true; 3618 3619 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3620 // Discard the first field since it is the field decl that is being 3621 // initialized. 3622 for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields))) 3623 UsedFieldIndex.push_back(FD->getFieldIndex()); 3624 3625 for (auto UsedIter = UsedFieldIndex.begin(), 3626 UsedEnd = UsedFieldIndex.end(), 3627 OrigIter = InitFieldIndex.begin(), 3628 OrigEnd = InitFieldIndex.end(); 3629 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3630 if (*UsedIter < *OrigIter) 3631 return true; 3632 if (*UsedIter > *OrigIter) 3633 break; 3634 } 3635 3636 return false; 3637 } 3638 3639 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3640 bool AddressOf) { 3641 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3642 return; 3643 3644 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3645 // or union. 3646 MemberExpr *FieldME = ME; 3647 3648 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3649 3650 Expr *Base = ME; 3651 while (MemberExpr *SubME = 3652 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3653 3654 if (isa<VarDecl>(SubME->getMemberDecl())) 3655 return; 3656 3657 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3658 if (!FD->isAnonymousStructOrUnion()) 3659 FieldME = SubME; 3660 3661 if (!FieldME->getType().isPODType(S.Context)) 3662 AllPODFields = false; 3663 3664 Base = SubME->getBase(); 3665 } 3666 3667 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) { 3668 Visit(Base); 3669 return; 3670 } 3671 3672 if (AddressOf && AllPODFields) 3673 return; 3674 3675 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3676 3677 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3678 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3679 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3680 } 3681 3682 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3683 QualType T = BaseCast->getType(); 3684 if (T->isPointerType() && 3685 BaseClasses.count(T->getPointeeType())) { 3686 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3687 << T->getPointeeType() << FoundVD; 3688 } 3689 } 3690 } 3691 3692 if (!Decls.count(FoundVD)) 3693 return; 3694 3695 const bool IsReference = FoundVD->getType()->isReferenceType(); 3696 3697 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3698 // Special checking for initializer lists. 3699 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3700 return; 3701 } 3702 } else { 3703 // Prevent double warnings on use of unbounded references. 3704 if (CheckReferenceOnly && !IsReference) 3705 return; 3706 } 3707 3708 unsigned diag = IsReference 3709 ? diag::warn_reference_field_is_uninit 3710 : diag::warn_field_is_uninit; 3711 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3712 if (Constructor) 3713 S.Diag(Constructor->getLocation(), 3714 diag::note_uninit_in_this_constructor) 3715 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3716 3717 } 3718 3719 void HandleValue(Expr *E, bool AddressOf) { 3720 E = E->IgnoreParens(); 3721 3722 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3723 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3724 AddressOf /*AddressOf*/); 3725 return; 3726 } 3727 3728 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3729 Visit(CO->getCond()); 3730 HandleValue(CO->getTrueExpr(), AddressOf); 3731 HandleValue(CO->getFalseExpr(), AddressOf); 3732 return; 3733 } 3734 3735 if (BinaryConditionalOperator *BCO = 3736 dyn_cast<BinaryConditionalOperator>(E)) { 3737 Visit(BCO->getCond()); 3738 HandleValue(BCO->getFalseExpr(), AddressOf); 3739 return; 3740 } 3741 3742 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3743 HandleValue(OVE->getSourceExpr(), AddressOf); 3744 return; 3745 } 3746 3747 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3748 switch (BO->getOpcode()) { 3749 default: 3750 break; 3751 case(BO_PtrMemD): 3752 case(BO_PtrMemI): 3753 HandleValue(BO->getLHS(), AddressOf); 3754 Visit(BO->getRHS()); 3755 return; 3756 case(BO_Comma): 3757 Visit(BO->getLHS()); 3758 HandleValue(BO->getRHS(), AddressOf); 3759 return; 3760 } 3761 } 3762 3763 Visit(E); 3764 } 3765 3766 void CheckInitListExpr(InitListExpr *ILE) { 3767 InitFieldIndex.push_back(0); 3768 for (auto Child : ILE->children()) { 3769 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3770 CheckInitListExpr(SubList); 3771 } else { 3772 Visit(Child); 3773 } 3774 ++InitFieldIndex.back(); 3775 } 3776 InitFieldIndex.pop_back(); 3777 } 3778 3779 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3780 FieldDecl *Field, const Type *BaseClass) { 3781 // Remove Decls that may have been initialized in the previous 3782 // initializer. 3783 for (ValueDecl* VD : DeclsToRemove) 3784 Decls.erase(VD); 3785 DeclsToRemove.clear(); 3786 3787 Constructor = FieldConstructor; 3788 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3789 3790 if (ILE && Field) { 3791 InitList = true; 3792 InitListFieldDecl = Field; 3793 InitFieldIndex.clear(); 3794 CheckInitListExpr(ILE); 3795 } else { 3796 InitList = false; 3797 Visit(E); 3798 } 3799 3800 if (Field) 3801 Decls.erase(Field); 3802 if (BaseClass) 3803 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3804 } 3805 3806 void VisitMemberExpr(MemberExpr *ME) { 3807 // All uses of unbounded reference fields will warn. 3808 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3809 } 3810 3811 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3812 if (E->getCastKind() == CK_LValueToRValue) { 3813 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3814 return; 3815 } 3816 3817 Inherited::VisitImplicitCastExpr(E); 3818 } 3819 3820 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3821 if (E->getConstructor()->isCopyConstructor()) { 3822 Expr *ArgExpr = E->getArg(0); 3823 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3824 if (ILE->getNumInits() == 1) 3825 ArgExpr = ILE->getInit(0); 3826 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3827 if (ICE->getCastKind() == CK_NoOp) 3828 ArgExpr = ICE->getSubExpr(); 3829 HandleValue(ArgExpr, false /*AddressOf*/); 3830 return; 3831 } 3832 Inherited::VisitCXXConstructExpr(E); 3833 } 3834 3835 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3836 Expr *Callee = E->getCallee(); 3837 if (isa<MemberExpr>(Callee)) { 3838 HandleValue(Callee, false /*AddressOf*/); 3839 for (auto Arg : E->arguments()) 3840 Visit(Arg); 3841 return; 3842 } 3843 3844 Inherited::VisitCXXMemberCallExpr(E); 3845 } 3846 3847 void VisitCallExpr(CallExpr *E) { 3848 // Treat std::move as a use. 3849 if (E->isCallToStdMove()) { 3850 HandleValue(E->getArg(0), /*AddressOf=*/false); 3851 return; 3852 } 3853 3854 Inherited::VisitCallExpr(E); 3855 } 3856 3857 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3858 Expr *Callee = E->getCallee(); 3859 3860 if (isa<UnresolvedLookupExpr>(Callee)) 3861 return Inherited::VisitCXXOperatorCallExpr(E); 3862 3863 Visit(Callee); 3864 for (auto Arg : E->arguments()) 3865 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3866 } 3867 3868 void VisitBinaryOperator(BinaryOperator *E) { 3869 // If a field assignment is detected, remove the field from the 3870 // uninitiailized field set. 3871 if (E->getOpcode() == BO_Assign) 3872 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3873 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3874 if (!FD->getType()->isReferenceType()) 3875 DeclsToRemove.push_back(FD); 3876 3877 if (E->isCompoundAssignmentOp()) { 3878 HandleValue(E->getLHS(), false /*AddressOf*/); 3879 Visit(E->getRHS()); 3880 return; 3881 } 3882 3883 Inherited::VisitBinaryOperator(E); 3884 } 3885 3886 void VisitUnaryOperator(UnaryOperator *E) { 3887 if (E->isIncrementDecrementOp()) { 3888 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3889 return; 3890 } 3891 if (E->getOpcode() == UO_AddrOf) { 3892 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3893 HandleValue(ME->getBase(), true /*AddressOf*/); 3894 return; 3895 } 3896 } 3897 3898 Inherited::VisitUnaryOperator(E); 3899 } 3900 }; 3901 3902 // Diagnose value-uses of fields to initialize themselves, e.g. 3903 // foo(foo) 3904 // where foo is not also a parameter to the constructor. 3905 // Also diagnose across field uninitialized use such as 3906 // x(y), y(x) 3907 // TODO: implement -Wuninitialized and fold this into that framework. 3908 static void DiagnoseUninitializedFields( 3909 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3910 3911 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3912 Constructor->getLocation())) { 3913 return; 3914 } 3915 3916 if (Constructor->isInvalidDecl()) 3917 return; 3918 3919 const CXXRecordDecl *RD = Constructor->getParent(); 3920 3921 if (RD->isDependentContext()) 3922 return; 3923 3924 // Holds fields that are uninitialized. 3925 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3926 3927 // At the beginning, all fields are uninitialized. 3928 for (auto *I : RD->decls()) { 3929 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3930 UninitializedFields.insert(FD); 3931 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3932 UninitializedFields.insert(IFD->getAnonField()); 3933 } 3934 } 3935 3936 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3937 for (auto I : RD->bases()) 3938 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3939 3940 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3941 return; 3942 3943 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3944 UninitializedFields, 3945 UninitializedBaseClasses); 3946 3947 for (const auto *FieldInit : Constructor->inits()) { 3948 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3949 break; 3950 3951 Expr *InitExpr = FieldInit->getInit(); 3952 if (!InitExpr) 3953 continue; 3954 3955 if (CXXDefaultInitExpr *Default = 3956 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3957 InitExpr = Default->getExpr(); 3958 if (!InitExpr) 3959 continue; 3960 // In class initializers will point to the constructor. 3961 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3962 FieldInit->getAnyMember(), 3963 FieldInit->getBaseClass()); 3964 } else { 3965 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3966 FieldInit->getAnyMember(), 3967 FieldInit->getBaseClass()); 3968 } 3969 } 3970 } 3971 } // namespace 3972 3973 /// Enter a new C++ default initializer scope. After calling this, the 3974 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3975 /// parsing or instantiating the initializer failed. 3976 void Sema::ActOnStartCXXInClassMemberInitializer() { 3977 // Create a synthetic function scope to represent the call to the constructor 3978 // that notionally surrounds a use of this initializer. 3979 PushFunctionScope(); 3980 } 3981 3982 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 3983 if (!D.isFunctionDeclarator()) 3984 return; 3985 auto &FTI = D.getFunctionTypeInfo(); 3986 if (!FTI.Params) 3987 return; 3988 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 3989 FTI.NumParams)) { 3990 auto *ParamDecl = cast<NamedDecl>(Param.Param); 3991 if (ParamDecl->getDeclName()) 3992 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 3993 } 3994 } 3995 3996 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 3997 return ActOnRequiresClause(ConstraintExpr); 3998 } 3999 4000 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) { 4001 if (ConstraintExpr.isInvalid()) 4002 return ExprError(); 4003 4004 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr); 4005 if (ConstraintExpr.isInvalid()) 4006 return ExprError(); 4007 4008 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(), 4009 UPPC_RequiresClause)) 4010 return ExprError(); 4011 4012 return ConstraintExpr; 4013 } 4014 4015 /// This is invoked after parsing an in-class initializer for a 4016 /// non-static C++ class member, and after instantiating an in-class initializer 4017 /// in a class template. Such actions are deferred until the class is complete. 4018 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 4019 SourceLocation InitLoc, 4020 Expr *InitExpr) { 4021 // Pop the notional constructor scope we created earlier. 4022 PopFunctionScopeInfo(nullptr, D); 4023 4024 FieldDecl *FD = dyn_cast<FieldDecl>(D); 4025 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 4026 "must set init style when field is created"); 4027 4028 if (!InitExpr) { 4029 D->setInvalidDecl(); 4030 if (FD) 4031 FD->removeInClassInitializer(); 4032 return; 4033 } 4034 4035 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 4036 FD->setInvalidDecl(); 4037 FD->removeInClassInitializer(); 4038 return; 4039 } 4040 4041 ExprResult Init = InitExpr; 4042 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 4043 InitializedEntity Entity = 4044 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 4045 InitializationKind Kind = 4046 FD->getInClassInitStyle() == ICIS_ListInit 4047 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 4048 InitExpr->getBeginLoc(), 4049 InitExpr->getEndLoc()) 4050 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 4051 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 4052 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 4053 if (Init.isInvalid()) { 4054 FD->setInvalidDecl(); 4055 return; 4056 } 4057 } 4058 4059 // C++11 [class.base.init]p7: 4060 // The initialization of each base and member constitutes a 4061 // full-expression. 4062 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 4063 if (Init.isInvalid()) { 4064 FD->setInvalidDecl(); 4065 return; 4066 } 4067 4068 InitExpr = Init.get(); 4069 4070 FD->setInClassInitializer(InitExpr); 4071 } 4072 4073 /// Find the direct and/or virtual base specifiers that 4074 /// correspond to the given base type, for use in base initialization 4075 /// within a constructor. 4076 static bool FindBaseInitializer(Sema &SemaRef, 4077 CXXRecordDecl *ClassDecl, 4078 QualType BaseType, 4079 const CXXBaseSpecifier *&DirectBaseSpec, 4080 const CXXBaseSpecifier *&VirtualBaseSpec) { 4081 // First, check for a direct base class. 4082 DirectBaseSpec = nullptr; 4083 for (const auto &Base : ClassDecl->bases()) { 4084 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 4085 // We found a direct base of this type. That's what we're 4086 // initializing. 4087 DirectBaseSpec = &Base; 4088 break; 4089 } 4090 } 4091 4092 // Check for a virtual base class. 4093 // FIXME: We might be able to short-circuit this if we know in advance that 4094 // there are no virtual bases. 4095 VirtualBaseSpec = nullptr; 4096 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 4097 // We haven't found a base yet; search the class hierarchy for a 4098 // virtual base class. 4099 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 4100 /*DetectVirtual=*/false); 4101 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 4102 SemaRef.Context.getTypeDeclType(ClassDecl), 4103 BaseType, Paths)) { 4104 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 4105 Path != Paths.end(); ++Path) { 4106 if (Path->back().Base->isVirtual()) { 4107 VirtualBaseSpec = Path->back().Base; 4108 break; 4109 } 4110 } 4111 } 4112 } 4113 4114 return DirectBaseSpec || VirtualBaseSpec; 4115 } 4116 4117 /// Handle a C++ member initializer using braced-init-list syntax. 4118 MemInitResult 4119 Sema::ActOnMemInitializer(Decl *ConstructorD, 4120 Scope *S, 4121 CXXScopeSpec &SS, 4122 IdentifierInfo *MemberOrBase, 4123 ParsedType TemplateTypeTy, 4124 const DeclSpec &DS, 4125 SourceLocation IdLoc, 4126 Expr *InitList, 4127 SourceLocation EllipsisLoc) { 4128 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4129 DS, IdLoc, InitList, 4130 EllipsisLoc); 4131 } 4132 4133 /// Handle a C++ member initializer using parentheses syntax. 4134 MemInitResult 4135 Sema::ActOnMemInitializer(Decl *ConstructorD, 4136 Scope *S, 4137 CXXScopeSpec &SS, 4138 IdentifierInfo *MemberOrBase, 4139 ParsedType TemplateTypeTy, 4140 const DeclSpec &DS, 4141 SourceLocation IdLoc, 4142 SourceLocation LParenLoc, 4143 ArrayRef<Expr *> Args, 4144 SourceLocation RParenLoc, 4145 SourceLocation EllipsisLoc) { 4146 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4147 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4148 DS, IdLoc, List, EllipsisLoc); 4149 } 4150 4151 namespace { 4152 4153 // Callback to only accept typo corrections that can be a valid C++ member 4154 // initializer: either a non-static field member or a base class. 4155 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4156 public: 4157 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4158 : ClassDecl(ClassDecl) {} 4159 4160 bool ValidateCandidate(const TypoCorrection &candidate) override { 4161 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4162 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4163 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4164 return isa<TypeDecl>(ND); 4165 } 4166 return false; 4167 } 4168 4169 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4170 return std::make_unique<MemInitializerValidatorCCC>(*this); 4171 } 4172 4173 private: 4174 CXXRecordDecl *ClassDecl; 4175 }; 4176 4177 } 4178 4179 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4180 CXXScopeSpec &SS, 4181 ParsedType TemplateTypeTy, 4182 IdentifierInfo *MemberOrBase) { 4183 if (SS.getScopeRep() || TemplateTypeTy) 4184 return nullptr; 4185 for (auto *D : ClassDecl->lookup(MemberOrBase)) 4186 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) 4187 return cast<ValueDecl>(D); 4188 return nullptr; 4189 } 4190 4191 /// Handle a C++ member initializer. 4192 MemInitResult 4193 Sema::BuildMemInitializer(Decl *ConstructorD, 4194 Scope *S, 4195 CXXScopeSpec &SS, 4196 IdentifierInfo *MemberOrBase, 4197 ParsedType TemplateTypeTy, 4198 const DeclSpec &DS, 4199 SourceLocation IdLoc, 4200 Expr *Init, 4201 SourceLocation EllipsisLoc) { 4202 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr, 4203 /*RecoverUncorrectedTypos=*/true); 4204 if (!Res.isUsable()) 4205 return true; 4206 Init = Res.get(); 4207 4208 if (!ConstructorD) 4209 return true; 4210 4211 AdjustDeclIfTemplate(ConstructorD); 4212 4213 CXXConstructorDecl *Constructor 4214 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4215 if (!Constructor) { 4216 // The user wrote a constructor initializer on a function that is 4217 // not a C++ constructor. Ignore the error for now, because we may 4218 // have more member initializers coming; we'll diagnose it just 4219 // once in ActOnMemInitializers. 4220 return true; 4221 } 4222 4223 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4224 4225 // C++ [class.base.init]p2: 4226 // Names in a mem-initializer-id are looked up in the scope of the 4227 // constructor's class and, if not found in that scope, are looked 4228 // up in the scope containing the constructor's definition. 4229 // [Note: if the constructor's class contains a member with the 4230 // same name as a direct or virtual base class of the class, a 4231 // mem-initializer-id naming the member or base class and composed 4232 // of a single identifier refers to the class member. A 4233 // mem-initializer-id for the hidden base class may be specified 4234 // using a qualified name. ] 4235 4236 // Look for a member, first. 4237 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4238 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4239 if (EllipsisLoc.isValid()) 4240 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4241 << MemberOrBase 4242 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4243 4244 return BuildMemberInitializer(Member, Init, IdLoc); 4245 } 4246 // It didn't name a member, so see if it names a class. 4247 QualType BaseType; 4248 TypeSourceInfo *TInfo = nullptr; 4249 4250 if (TemplateTypeTy) { 4251 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4252 if (BaseType.isNull()) 4253 return true; 4254 } else if (DS.getTypeSpecType() == TST_decltype) { 4255 BaseType = BuildDecltypeType(DS.getRepAsExpr()); 4256 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4257 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4258 return true; 4259 } else { 4260 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4261 LookupParsedName(R, S, &SS); 4262 4263 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4264 if (!TyD) { 4265 if (R.isAmbiguous()) return true; 4266 4267 // We don't want access-control diagnostics here. 4268 R.suppressDiagnostics(); 4269 4270 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4271 bool NotUnknownSpecialization = false; 4272 DeclContext *DC = computeDeclContext(SS, false); 4273 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4274 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4275 4276 if (!NotUnknownSpecialization) { 4277 // When the scope specifier can refer to a member of an unknown 4278 // specialization, we take it as a type name. 4279 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4280 SS.getWithLocInContext(Context), 4281 *MemberOrBase, IdLoc); 4282 if (BaseType.isNull()) 4283 return true; 4284 4285 TInfo = Context.CreateTypeSourceInfo(BaseType); 4286 DependentNameTypeLoc TL = 4287 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4288 if (!TL.isNull()) { 4289 TL.setNameLoc(IdLoc); 4290 TL.setElaboratedKeywordLoc(SourceLocation()); 4291 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4292 } 4293 4294 R.clear(); 4295 R.setLookupName(MemberOrBase); 4296 } 4297 } 4298 4299 // If no results were found, try to correct typos. 4300 TypoCorrection Corr; 4301 MemInitializerValidatorCCC CCC(ClassDecl); 4302 if (R.empty() && BaseType.isNull() && 4303 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4304 CCC, CTK_ErrorRecovery, ClassDecl))) { 4305 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4306 // We have found a non-static data member with a similar 4307 // name to what was typed; complain and initialize that 4308 // member. 4309 diagnoseTypo(Corr, 4310 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4311 << MemberOrBase << true); 4312 return BuildMemberInitializer(Member, Init, IdLoc); 4313 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4314 const CXXBaseSpecifier *DirectBaseSpec; 4315 const CXXBaseSpecifier *VirtualBaseSpec; 4316 if (FindBaseInitializer(*this, ClassDecl, 4317 Context.getTypeDeclType(Type), 4318 DirectBaseSpec, VirtualBaseSpec)) { 4319 // We have found a direct or virtual base class with a 4320 // similar name to what was typed; complain and initialize 4321 // that base class. 4322 diagnoseTypo(Corr, 4323 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4324 << MemberOrBase << false, 4325 PDiag() /*Suppress note, we provide our own.*/); 4326 4327 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4328 : VirtualBaseSpec; 4329 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4330 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4331 4332 TyD = Type; 4333 } 4334 } 4335 } 4336 4337 if (!TyD && BaseType.isNull()) { 4338 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4339 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4340 return true; 4341 } 4342 } 4343 4344 if (BaseType.isNull()) { 4345 BaseType = Context.getTypeDeclType(TyD); 4346 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4347 if (SS.isSet()) { 4348 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4349 BaseType); 4350 TInfo = Context.CreateTypeSourceInfo(BaseType); 4351 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4352 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4353 TL.setElaboratedKeywordLoc(SourceLocation()); 4354 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4355 } 4356 } 4357 } 4358 4359 if (!TInfo) 4360 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4361 4362 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4363 } 4364 4365 MemInitResult 4366 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4367 SourceLocation IdLoc) { 4368 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4369 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4370 assert((DirectMember || IndirectMember) && 4371 "Member must be a FieldDecl or IndirectFieldDecl"); 4372 4373 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4374 return true; 4375 4376 if (Member->isInvalidDecl()) 4377 return true; 4378 4379 MultiExprArg Args; 4380 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4381 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4382 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4383 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4384 } else { 4385 // Template instantiation doesn't reconstruct ParenListExprs for us. 4386 Args = Init; 4387 } 4388 4389 SourceRange InitRange = Init->getSourceRange(); 4390 4391 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4392 // Can't check initialization for a member of dependent type or when 4393 // any of the arguments are type-dependent expressions. 4394 DiscardCleanupsInEvaluationContext(); 4395 } else { 4396 bool InitList = false; 4397 if (isa<InitListExpr>(Init)) { 4398 InitList = true; 4399 Args = Init; 4400 } 4401 4402 // Initialize the member. 4403 InitializedEntity MemberEntity = 4404 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4405 : InitializedEntity::InitializeMember(IndirectMember, 4406 nullptr); 4407 InitializationKind Kind = 4408 InitList ? InitializationKind::CreateDirectList( 4409 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4410 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4411 InitRange.getEnd()); 4412 4413 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4414 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4415 nullptr); 4416 if (!MemberInit.isInvalid()) { 4417 // C++11 [class.base.init]p7: 4418 // The initialization of each base and member constitutes a 4419 // full-expression. 4420 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4421 /*DiscardedValue*/ false); 4422 } 4423 4424 if (MemberInit.isInvalid()) { 4425 // Args were sensible expressions but we couldn't initialize the member 4426 // from them. Preserve them in a RecoveryExpr instead. 4427 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, 4428 Member->getType()) 4429 .get(); 4430 if (!Init) 4431 return true; 4432 } else { 4433 Init = MemberInit.get(); 4434 } 4435 } 4436 4437 if (DirectMember) { 4438 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4439 InitRange.getBegin(), Init, 4440 InitRange.getEnd()); 4441 } else { 4442 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4443 InitRange.getBegin(), Init, 4444 InitRange.getEnd()); 4445 } 4446 } 4447 4448 MemInitResult 4449 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4450 CXXRecordDecl *ClassDecl) { 4451 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4452 if (!LangOpts.CPlusPlus11) 4453 return Diag(NameLoc, diag::err_delegating_ctor) 4454 << TInfo->getTypeLoc().getLocalSourceRange(); 4455 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4456 4457 bool InitList = true; 4458 MultiExprArg Args = Init; 4459 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4460 InitList = false; 4461 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4462 } 4463 4464 SourceRange InitRange = Init->getSourceRange(); 4465 // Initialize the object. 4466 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4467 QualType(ClassDecl->getTypeForDecl(), 0)); 4468 InitializationKind Kind = 4469 InitList ? InitializationKind::CreateDirectList( 4470 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4471 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4472 InitRange.getEnd()); 4473 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4474 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4475 Args, nullptr); 4476 if (!DelegationInit.isInvalid()) { 4477 assert((DelegationInit.get()->containsErrors() || 4478 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) && 4479 "Delegating constructor with no target?"); 4480 4481 // C++11 [class.base.init]p7: 4482 // The initialization of each base and member constitutes a 4483 // full-expression. 4484 DelegationInit = ActOnFinishFullExpr( 4485 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4486 } 4487 4488 if (DelegationInit.isInvalid()) { 4489 DelegationInit = 4490 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, 4491 QualType(ClassDecl->getTypeForDecl(), 0)); 4492 if (DelegationInit.isInvalid()) 4493 return true; 4494 } else { 4495 // If we are in a dependent context, template instantiation will 4496 // perform this type-checking again. Just save the arguments that we 4497 // received in a ParenListExpr. 4498 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4499 // of the information that we have about the base 4500 // initializer. However, deconstructing the ASTs is a dicey process, 4501 // and this approach is far more likely to get the corner cases right. 4502 if (CurContext->isDependentContext()) 4503 DelegationInit = Init; 4504 } 4505 4506 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4507 DelegationInit.getAs<Expr>(), 4508 InitRange.getEnd()); 4509 } 4510 4511 MemInitResult 4512 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4513 Expr *Init, CXXRecordDecl *ClassDecl, 4514 SourceLocation EllipsisLoc) { 4515 SourceLocation BaseLoc 4516 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4517 4518 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4519 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4520 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4521 4522 // C++ [class.base.init]p2: 4523 // [...] Unless the mem-initializer-id names a nonstatic data 4524 // member of the constructor's class or a direct or virtual base 4525 // of that class, the mem-initializer is ill-formed. A 4526 // mem-initializer-list can initialize a base class using any 4527 // name that denotes that base class type. 4528 4529 // We can store the initializers in "as-written" form and delay analysis until 4530 // instantiation if the constructor is dependent. But not for dependent 4531 // (broken) code in a non-template! SetCtorInitializers does not expect this. 4532 bool Dependent = CurContext->isDependentContext() && 4533 (BaseType->isDependentType() || Init->isTypeDependent()); 4534 4535 SourceRange InitRange = Init->getSourceRange(); 4536 if (EllipsisLoc.isValid()) { 4537 // This is a pack expansion. 4538 if (!BaseType->containsUnexpandedParameterPack()) { 4539 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4540 << SourceRange(BaseLoc, InitRange.getEnd()); 4541 4542 EllipsisLoc = SourceLocation(); 4543 } 4544 } else { 4545 // Check for any unexpanded parameter packs. 4546 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4547 return true; 4548 4549 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4550 return true; 4551 } 4552 4553 // Check for direct and virtual base classes. 4554 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4555 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4556 if (!Dependent) { 4557 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4558 BaseType)) 4559 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4560 4561 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4562 VirtualBaseSpec); 4563 4564 // C++ [base.class.init]p2: 4565 // Unless the mem-initializer-id names a nonstatic data member of the 4566 // constructor's class or a direct or virtual base of that class, the 4567 // mem-initializer is ill-formed. 4568 if (!DirectBaseSpec && !VirtualBaseSpec) { 4569 // If the class has any dependent bases, then it's possible that 4570 // one of those types will resolve to the same type as 4571 // BaseType. Therefore, just treat this as a dependent base 4572 // class initialization. FIXME: Should we try to check the 4573 // initialization anyway? It seems odd. 4574 if (ClassDecl->hasAnyDependentBases()) 4575 Dependent = true; 4576 else 4577 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4578 << BaseType << Context.getTypeDeclType(ClassDecl) 4579 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4580 } 4581 } 4582 4583 if (Dependent) { 4584 DiscardCleanupsInEvaluationContext(); 4585 4586 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4587 /*IsVirtual=*/false, 4588 InitRange.getBegin(), Init, 4589 InitRange.getEnd(), EllipsisLoc); 4590 } 4591 4592 // C++ [base.class.init]p2: 4593 // If a mem-initializer-id is ambiguous because it designates both 4594 // a direct non-virtual base class and an inherited virtual base 4595 // class, the mem-initializer is ill-formed. 4596 if (DirectBaseSpec && VirtualBaseSpec) 4597 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4598 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4599 4600 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4601 if (!BaseSpec) 4602 BaseSpec = VirtualBaseSpec; 4603 4604 // Initialize the base. 4605 bool InitList = true; 4606 MultiExprArg Args = Init; 4607 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4608 InitList = false; 4609 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4610 } 4611 4612 InitializedEntity BaseEntity = 4613 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4614 InitializationKind Kind = 4615 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4616 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4617 InitRange.getEnd()); 4618 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4619 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4620 if (!BaseInit.isInvalid()) { 4621 // C++11 [class.base.init]p7: 4622 // The initialization of each base and member constitutes a 4623 // full-expression. 4624 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4625 /*DiscardedValue*/ false); 4626 } 4627 4628 if (BaseInit.isInvalid()) { 4629 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), 4630 Args, BaseType); 4631 if (BaseInit.isInvalid()) 4632 return true; 4633 } else { 4634 // If we are in a dependent context, template instantiation will 4635 // perform this type-checking again. Just save the arguments that we 4636 // received in a ParenListExpr. 4637 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4638 // of the information that we have about the base 4639 // initializer. However, deconstructing the ASTs is a dicey process, 4640 // and this approach is far more likely to get the corner cases right. 4641 if (CurContext->isDependentContext()) 4642 BaseInit = Init; 4643 } 4644 4645 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4646 BaseSpec->isVirtual(), 4647 InitRange.getBegin(), 4648 BaseInit.getAs<Expr>(), 4649 InitRange.getEnd(), EllipsisLoc); 4650 } 4651 4652 // Create a static_cast\<T&&>(expr). 4653 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4654 if (T.isNull()) T = E->getType(); 4655 QualType TargetType = SemaRef.BuildReferenceType( 4656 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4657 SourceLocation ExprLoc = E->getBeginLoc(); 4658 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4659 TargetType, ExprLoc); 4660 4661 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4662 SourceRange(ExprLoc, ExprLoc), 4663 E->getSourceRange()).get(); 4664 } 4665 4666 /// ImplicitInitializerKind - How an implicit base or member initializer should 4667 /// initialize its base or member. 4668 enum ImplicitInitializerKind { 4669 IIK_Default, 4670 IIK_Copy, 4671 IIK_Move, 4672 IIK_Inherit 4673 }; 4674 4675 static bool 4676 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4677 ImplicitInitializerKind ImplicitInitKind, 4678 CXXBaseSpecifier *BaseSpec, 4679 bool IsInheritedVirtualBase, 4680 CXXCtorInitializer *&CXXBaseInit) { 4681 InitializedEntity InitEntity 4682 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4683 IsInheritedVirtualBase); 4684 4685 ExprResult BaseInit; 4686 4687 switch (ImplicitInitKind) { 4688 case IIK_Inherit: 4689 case IIK_Default: { 4690 InitializationKind InitKind 4691 = InitializationKind::CreateDefault(Constructor->getLocation()); 4692 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4693 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4694 break; 4695 } 4696 4697 case IIK_Move: 4698 case IIK_Copy: { 4699 bool Moving = ImplicitInitKind == IIK_Move; 4700 ParmVarDecl *Param = Constructor->getParamDecl(0); 4701 QualType ParamType = Param->getType().getNonReferenceType(); 4702 4703 Expr *CopyCtorArg = 4704 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4705 SourceLocation(), Param, false, 4706 Constructor->getLocation(), ParamType, 4707 VK_LValue, nullptr); 4708 4709 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4710 4711 // Cast to the base class to avoid ambiguities. 4712 QualType ArgTy = 4713 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4714 ParamType.getQualifiers()); 4715 4716 if (Moving) { 4717 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4718 } 4719 4720 CXXCastPath BasePath; 4721 BasePath.push_back(BaseSpec); 4722 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4723 CK_UncheckedDerivedToBase, 4724 Moving ? VK_XValue : VK_LValue, 4725 &BasePath).get(); 4726 4727 InitializationKind InitKind 4728 = InitializationKind::CreateDirect(Constructor->getLocation(), 4729 SourceLocation(), SourceLocation()); 4730 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4731 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4732 break; 4733 } 4734 } 4735 4736 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4737 if (BaseInit.isInvalid()) 4738 return true; 4739 4740 CXXBaseInit = 4741 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4742 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4743 SourceLocation()), 4744 BaseSpec->isVirtual(), 4745 SourceLocation(), 4746 BaseInit.getAs<Expr>(), 4747 SourceLocation(), 4748 SourceLocation()); 4749 4750 return false; 4751 } 4752 4753 static bool RefersToRValueRef(Expr *MemRef) { 4754 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4755 return Referenced->getType()->isRValueReferenceType(); 4756 } 4757 4758 static bool 4759 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4760 ImplicitInitializerKind ImplicitInitKind, 4761 FieldDecl *Field, IndirectFieldDecl *Indirect, 4762 CXXCtorInitializer *&CXXMemberInit) { 4763 if (Field->isInvalidDecl()) 4764 return true; 4765 4766 SourceLocation Loc = Constructor->getLocation(); 4767 4768 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4769 bool Moving = ImplicitInitKind == IIK_Move; 4770 ParmVarDecl *Param = Constructor->getParamDecl(0); 4771 QualType ParamType = Param->getType().getNonReferenceType(); 4772 4773 // Suppress copying zero-width bitfields. 4774 if (Field->isZeroLengthBitField(SemaRef.Context)) 4775 return false; 4776 4777 Expr *MemberExprBase = 4778 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4779 SourceLocation(), Param, false, 4780 Loc, ParamType, VK_LValue, nullptr); 4781 4782 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4783 4784 if (Moving) { 4785 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4786 } 4787 4788 // Build a reference to this field within the parameter. 4789 CXXScopeSpec SS; 4790 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4791 Sema::LookupMemberName); 4792 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4793 : cast<ValueDecl>(Field), AS_public); 4794 MemberLookup.resolveKind(); 4795 ExprResult CtorArg 4796 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4797 ParamType, Loc, 4798 /*IsArrow=*/false, 4799 SS, 4800 /*TemplateKWLoc=*/SourceLocation(), 4801 /*FirstQualifierInScope=*/nullptr, 4802 MemberLookup, 4803 /*TemplateArgs=*/nullptr, 4804 /*S*/nullptr); 4805 if (CtorArg.isInvalid()) 4806 return true; 4807 4808 // C++11 [class.copy]p15: 4809 // - if a member m has rvalue reference type T&&, it is direct-initialized 4810 // with static_cast<T&&>(x.m); 4811 if (RefersToRValueRef(CtorArg.get())) { 4812 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4813 } 4814 4815 InitializedEntity Entity = 4816 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4817 /*Implicit*/ true) 4818 : InitializedEntity::InitializeMember(Field, nullptr, 4819 /*Implicit*/ true); 4820 4821 // Direct-initialize to use the copy constructor. 4822 InitializationKind InitKind = 4823 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4824 4825 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4826 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4827 ExprResult MemberInit = 4828 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4829 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4830 if (MemberInit.isInvalid()) 4831 return true; 4832 4833 if (Indirect) 4834 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4835 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4836 else 4837 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4838 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4839 return false; 4840 } 4841 4842 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4843 "Unhandled implicit init kind!"); 4844 4845 QualType FieldBaseElementType = 4846 SemaRef.Context.getBaseElementType(Field->getType()); 4847 4848 if (FieldBaseElementType->isRecordType()) { 4849 InitializedEntity InitEntity = 4850 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4851 /*Implicit*/ true) 4852 : InitializedEntity::InitializeMember(Field, nullptr, 4853 /*Implicit*/ true); 4854 InitializationKind InitKind = 4855 InitializationKind::CreateDefault(Loc); 4856 4857 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4858 ExprResult MemberInit = 4859 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4860 4861 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4862 if (MemberInit.isInvalid()) 4863 return true; 4864 4865 if (Indirect) 4866 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4867 Indirect, Loc, 4868 Loc, 4869 MemberInit.get(), 4870 Loc); 4871 else 4872 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4873 Field, Loc, Loc, 4874 MemberInit.get(), 4875 Loc); 4876 return false; 4877 } 4878 4879 if (!Field->getParent()->isUnion()) { 4880 if (FieldBaseElementType->isReferenceType()) { 4881 SemaRef.Diag(Constructor->getLocation(), 4882 diag::err_uninitialized_member_in_ctor) 4883 << (int)Constructor->isImplicit() 4884 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4885 << 0 << Field->getDeclName(); 4886 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4887 return true; 4888 } 4889 4890 if (FieldBaseElementType.isConstQualified()) { 4891 SemaRef.Diag(Constructor->getLocation(), 4892 diag::err_uninitialized_member_in_ctor) 4893 << (int)Constructor->isImplicit() 4894 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4895 << 1 << Field->getDeclName(); 4896 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4897 return true; 4898 } 4899 } 4900 4901 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4902 // ARC and Weak: 4903 // Default-initialize Objective-C pointers to NULL. 4904 CXXMemberInit 4905 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4906 Loc, Loc, 4907 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4908 Loc); 4909 return false; 4910 } 4911 4912 // Nothing to initialize. 4913 CXXMemberInit = nullptr; 4914 return false; 4915 } 4916 4917 namespace { 4918 struct BaseAndFieldInfo { 4919 Sema &S; 4920 CXXConstructorDecl *Ctor; 4921 bool AnyErrorsInInits; 4922 ImplicitInitializerKind IIK; 4923 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4924 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4925 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4926 4927 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4928 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4929 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4930 if (Ctor->getInheritedConstructor()) 4931 IIK = IIK_Inherit; 4932 else if (Generated && Ctor->isCopyConstructor()) 4933 IIK = IIK_Copy; 4934 else if (Generated && Ctor->isMoveConstructor()) 4935 IIK = IIK_Move; 4936 else 4937 IIK = IIK_Default; 4938 } 4939 4940 bool isImplicitCopyOrMove() const { 4941 switch (IIK) { 4942 case IIK_Copy: 4943 case IIK_Move: 4944 return true; 4945 4946 case IIK_Default: 4947 case IIK_Inherit: 4948 return false; 4949 } 4950 4951 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4952 } 4953 4954 bool addFieldInitializer(CXXCtorInitializer *Init) { 4955 AllToInit.push_back(Init); 4956 4957 // Check whether this initializer makes the field "used". 4958 if (Init->getInit()->HasSideEffects(S.Context)) 4959 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4960 4961 return false; 4962 } 4963 4964 bool isInactiveUnionMember(FieldDecl *Field) { 4965 RecordDecl *Record = Field->getParent(); 4966 if (!Record->isUnion()) 4967 return false; 4968 4969 if (FieldDecl *Active = 4970 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4971 return Active != Field->getCanonicalDecl(); 4972 4973 // In an implicit copy or move constructor, ignore any in-class initializer. 4974 if (isImplicitCopyOrMove()) 4975 return true; 4976 4977 // If there's no explicit initialization, the field is active only if it 4978 // has an in-class initializer... 4979 if (Field->hasInClassInitializer()) 4980 return false; 4981 // ... or it's an anonymous struct or union whose class has an in-class 4982 // initializer. 4983 if (!Field->isAnonymousStructOrUnion()) 4984 return true; 4985 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4986 return !FieldRD->hasInClassInitializer(); 4987 } 4988 4989 /// Determine whether the given field is, or is within, a union member 4990 /// that is inactive (because there was an initializer given for a different 4991 /// member of the union, or because the union was not initialized at all). 4992 bool isWithinInactiveUnionMember(FieldDecl *Field, 4993 IndirectFieldDecl *Indirect) { 4994 if (!Indirect) 4995 return isInactiveUnionMember(Field); 4996 4997 for (auto *C : Indirect->chain()) { 4998 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4999 if (Field && isInactiveUnionMember(Field)) 5000 return true; 5001 } 5002 return false; 5003 } 5004 }; 5005 } 5006 5007 /// Determine whether the given type is an incomplete or zero-lenfgth 5008 /// array type. 5009 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 5010 if (T->isIncompleteArrayType()) 5011 return true; 5012 5013 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 5014 if (!ArrayT->getSize()) 5015 return true; 5016 5017 T = ArrayT->getElementType(); 5018 } 5019 5020 return false; 5021 } 5022 5023 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 5024 FieldDecl *Field, 5025 IndirectFieldDecl *Indirect = nullptr) { 5026 if (Field->isInvalidDecl()) 5027 return false; 5028 5029 // Overwhelmingly common case: we have a direct initializer for this field. 5030 if (CXXCtorInitializer *Init = 5031 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 5032 return Info.addFieldInitializer(Init); 5033 5034 // C++11 [class.base.init]p8: 5035 // if the entity is a non-static data member that has a 5036 // brace-or-equal-initializer and either 5037 // -- the constructor's class is a union and no other variant member of that 5038 // union is designated by a mem-initializer-id or 5039 // -- the constructor's class is not a union, and, if the entity is a member 5040 // of an anonymous union, no other member of that union is designated by 5041 // a mem-initializer-id, 5042 // the entity is initialized as specified in [dcl.init]. 5043 // 5044 // We also apply the same rules to handle anonymous structs within anonymous 5045 // unions. 5046 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 5047 return false; 5048 5049 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 5050 ExprResult DIE = 5051 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 5052 if (DIE.isInvalid()) 5053 return true; 5054 5055 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 5056 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 5057 5058 CXXCtorInitializer *Init; 5059 if (Indirect) 5060 Init = new (SemaRef.Context) 5061 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 5062 SourceLocation(), DIE.get(), SourceLocation()); 5063 else 5064 Init = new (SemaRef.Context) 5065 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 5066 SourceLocation(), DIE.get(), SourceLocation()); 5067 return Info.addFieldInitializer(Init); 5068 } 5069 5070 // Don't initialize incomplete or zero-length arrays. 5071 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 5072 return false; 5073 5074 // Don't try to build an implicit initializer if there were semantic 5075 // errors in any of the initializers (and therefore we might be 5076 // missing some that the user actually wrote). 5077 if (Info.AnyErrorsInInits) 5078 return false; 5079 5080 CXXCtorInitializer *Init = nullptr; 5081 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 5082 Indirect, Init)) 5083 return true; 5084 5085 if (!Init) 5086 return false; 5087 5088 return Info.addFieldInitializer(Init); 5089 } 5090 5091 bool 5092 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 5093 CXXCtorInitializer *Initializer) { 5094 assert(Initializer->isDelegatingInitializer()); 5095 Constructor->setNumCtorInitializers(1); 5096 CXXCtorInitializer **initializer = 5097 new (Context) CXXCtorInitializer*[1]; 5098 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 5099 Constructor->setCtorInitializers(initializer); 5100 5101 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 5102 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 5103 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 5104 } 5105 5106 DelegatingCtorDecls.push_back(Constructor); 5107 5108 DiagnoseUninitializedFields(*this, Constructor); 5109 5110 return false; 5111 } 5112 5113 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 5114 ArrayRef<CXXCtorInitializer *> Initializers) { 5115 if (Constructor->isDependentContext()) { 5116 // Just store the initializers as written, they will be checked during 5117 // instantiation. 5118 if (!Initializers.empty()) { 5119 Constructor->setNumCtorInitializers(Initializers.size()); 5120 CXXCtorInitializer **baseOrMemberInitializers = 5121 new (Context) CXXCtorInitializer*[Initializers.size()]; 5122 memcpy(baseOrMemberInitializers, Initializers.data(), 5123 Initializers.size() * sizeof(CXXCtorInitializer*)); 5124 Constructor->setCtorInitializers(baseOrMemberInitializers); 5125 } 5126 5127 // Let template instantiation know whether we had errors. 5128 if (AnyErrors) 5129 Constructor->setInvalidDecl(); 5130 5131 return false; 5132 } 5133 5134 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 5135 5136 // We need to build the initializer AST according to order of construction 5137 // and not what user specified in the Initializers list. 5138 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 5139 if (!ClassDecl) 5140 return true; 5141 5142 bool HadError = false; 5143 5144 for (unsigned i = 0; i < Initializers.size(); i++) { 5145 CXXCtorInitializer *Member = Initializers[i]; 5146 5147 if (Member->isBaseInitializer()) 5148 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5149 else { 5150 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5151 5152 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5153 for (auto *C : F->chain()) { 5154 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5155 if (FD && FD->getParent()->isUnion()) 5156 Info.ActiveUnionMember.insert(std::make_pair( 5157 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5158 } 5159 } else if (FieldDecl *FD = Member->getMember()) { 5160 if (FD->getParent()->isUnion()) 5161 Info.ActiveUnionMember.insert(std::make_pair( 5162 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5163 } 5164 } 5165 } 5166 5167 // Keep track of the direct virtual bases. 5168 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5169 for (auto &I : ClassDecl->bases()) { 5170 if (I.isVirtual()) 5171 DirectVBases.insert(&I); 5172 } 5173 5174 // Push virtual bases before others. 5175 for (auto &VBase : ClassDecl->vbases()) { 5176 if (CXXCtorInitializer *Value 5177 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5178 // [class.base.init]p7, per DR257: 5179 // A mem-initializer where the mem-initializer-id names a virtual base 5180 // class is ignored during execution of a constructor of any class that 5181 // is not the most derived class. 5182 if (ClassDecl->isAbstract()) { 5183 // FIXME: Provide a fixit to remove the base specifier. This requires 5184 // tracking the location of the associated comma for a base specifier. 5185 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5186 << VBase.getType() << ClassDecl; 5187 DiagnoseAbstractType(ClassDecl); 5188 } 5189 5190 Info.AllToInit.push_back(Value); 5191 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5192 // [class.base.init]p8, per DR257: 5193 // If a given [...] base class is not named by a mem-initializer-id 5194 // [...] and the entity is not a virtual base class of an abstract 5195 // class, then [...] the entity is default-initialized. 5196 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5197 CXXCtorInitializer *CXXBaseInit; 5198 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5199 &VBase, IsInheritedVirtualBase, 5200 CXXBaseInit)) { 5201 HadError = true; 5202 continue; 5203 } 5204 5205 Info.AllToInit.push_back(CXXBaseInit); 5206 } 5207 } 5208 5209 // Non-virtual bases. 5210 for (auto &Base : ClassDecl->bases()) { 5211 // Virtuals are in the virtual base list and already constructed. 5212 if (Base.isVirtual()) 5213 continue; 5214 5215 if (CXXCtorInitializer *Value 5216 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5217 Info.AllToInit.push_back(Value); 5218 } else if (!AnyErrors) { 5219 CXXCtorInitializer *CXXBaseInit; 5220 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5221 &Base, /*IsInheritedVirtualBase=*/false, 5222 CXXBaseInit)) { 5223 HadError = true; 5224 continue; 5225 } 5226 5227 Info.AllToInit.push_back(CXXBaseInit); 5228 } 5229 } 5230 5231 // Fields. 5232 for (auto *Mem : ClassDecl->decls()) { 5233 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5234 // C++ [class.bit]p2: 5235 // A declaration for a bit-field that omits the identifier declares an 5236 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5237 // initialized. 5238 if (F->isUnnamedBitfield()) 5239 continue; 5240 5241 // If we're not generating the implicit copy/move constructor, then we'll 5242 // handle anonymous struct/union fields based on their individual 5243 // indirect fields. 5244 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5245 continue; 5246 5247 if (CollectFieldInitializer(*this, Info, F)) 5248 HadError = true; 5249 continue; 5250 } 5251 5252 // Beyond this point, we only consider default initialization. 5253 if (Info.isImplicitCopyOrMove()) 5254 continue; 5255 5256 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5257 if (F->getType()->isIncompleteArrayType()) { 5258 assert(ClassDecl->hasFlexibleArrayMember() && 5259 "Incomplete array type is not valid"); 5260 continue; 5261 } 5262 5263 // Initialize each field of an anonymous struct individually. 5264 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5265 HadError = true; 5266 5267 continue; 5268 } 5269 } 5270 5271 unsigned NumInitializers = Info.AllToInit.size(); 5272 if (NumInitializers > 0) { 5273 Constructor->setNumCtorInitializers(NumInitializers); 5274 CXXCtorInitializer **baseOrMemberInitializers = 5275 new (Context) CXXCtorInitializer*[NumInitializers]; 5276 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5277 NumInitializers * sizeof(CXXCtorInitializer*)); 5278 Constructor->setCtorInitializers(baseOrMemberInitializers); 5279 5280 // Constructors implicitly reference the base and member 5281 // destructors. 5282 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5283 Constructor->getParent()); 5284 } 5285 5286 return HadError; 5287 } 5288 5289 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5290 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5291 const RecordDecl *RD = RT->getDecl(); 5292 if (RD->isAnonymousStructOrUnion()) { 5293 for (auto *Field : RD->fields()) 5294 PopulateKeysForFields(Field, IdealInits); 5295 return; 5296 } 5297 } 5298 IdealInits.push_back(Field->getCanonicalDecl()); 5299 } 5300 5301 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5302 return Context.getCanonicalType(BaseType).getTypePtr(); 5303 } 5304 5305 static const void *GetKeyForMember(ASTContext &Context, 5306 CXXCtorInitializer *Member) { 5307 if (!Member->isAnyMemberInitializer()) 5308 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5309 5310 return Member->getAnyMember()->getCanonicalDecl(); 5311 } 5312 5313 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, 5314 const CXXCtorInitializer *Previous, 5315 const CXXCtorInitializer *Current) { 5316 if (Previous->isAnyMemberInitializer()) 5317 Diag << 0 << Previous->getAnyMember(); 5318 else 5319 Diag << 1 << Previous->getTypeSourceInfo()->getType(); 5320 5321 if (Current->isAnyMemberInitializer()) 5322 Diag << 0 << Current->getAnyMember(); 5323 else 5324 Diag << 1 << Current->getTypeSourceInfo()->getType(); 5325 } 5326 5327 static void DiagnoseBaseOrMemInitializerOrder( 5328 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5329 ArrayRef<CXXCtorInitializer *> Inits) { 5330 if (Constructor->getDeclContext()->isDependentContext()) 5331 return; 5332 5333 // Don't check initializers order unless the warning is enabled at the 5334 // location of at least one initializer. 5335 bool ShouldCheckOrder = false; 5336 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5337 CXXCtorInitializer *Init = Inits[InitIndex]; 5338 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5339 Init->getSourceLocation())) { 5340 ShouldCheckOrder = true; 5341 break; 5342 } 5343 } 5344 if (!ShouldCheckOrder) 5345 return; 5346 5347 // Build the list of bases and members in the order that they'll 5348 // actually be initialized. The explicit initializers should be in 5349 // this same order but may be missing things. 5350 SmallVector<const void*, 32> IdealInitKeys; 5351 5352 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5353 5354 // 1. Virtual bases. 5355 for (const auto &VBase : ClassDecl->vbases()) 5356 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5357 5358 // 2. Non-virtual bases. 5359 for (const auto &Base : ClassDecl->bases()) { 5360 if (Base.isVirtual()) 5361 continue; 5362 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5363 } 5364 5365 // 3. Direct fields. 5366 for (auto *Field : ClassDecl->fields()) { 5367 if (Field->isUnnamedBitfield()) 5368 continue; 5369 5370 PopulateKeysForFields(Field, IdealInitKeys); 5371 } 5372 5373 unsigned NumIdealInits = IdealInitKeys.size(); 5374 unsigned IdealIndex = 0; 5375 5376 // Track initializers that are in an incorrect order for either a warning or 5377 // note if multiple ones occur. 5378 SmallVector<unsigned> WarnIndexes; 5379 // Correlates the index of an initializer in the init-list to the index of 5380 // the field/base in the class. 5381 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder; 5382 5383 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5384 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]); 5385 5386 // Scan forward to try to find this initializer in the idealized 5387 // initializers list. 5388 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5389 if (InitKey == IdealInitKeys[IdealIndex]) 5390 break; 5391 5392 // If we didn't find this initializer, it must be because we 5393 // scanned past it on a previous iteration. That can only 5394 // happen if we're out of order; emit a warning. 5395 if (IdealIndex == NumIdealInits && InitIndex) { 5396 WarnIndexes.push_back(InitIndex); 5397 5398 // Move back to the initializer's location in the ideal list. 5399 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5400 if (InitKey == IdealInitKeys[IdealIndex]) 5401 break; 5402 5403 assert(IdealIndex < NumIdealInits && 5404 "initializer not found in initializer list"); 5405 } 5406 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex); 5407 } 5408 5409 if (WarnIndexes.empty()) 5410 return; 5411 5412 // Sort based on the ideal order, first in the pair. 5413 llvm::sort(CorrelatedInitOrder, 5414 [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; }); 5415 5416 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to 5417 // emit the diagnostic before we can try adding notes. 5418 { 5419 Sema::SemaDiagnosticBuilder D = SemaRef.Diag( 5420 Inits[WarnIndexes.front() - 1]->getSourceLocation(), 5421 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order 5422 : diag::warn_some_initializers_out_of_order); 5423 5424 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) { 5425 if (CorrelatedInitOrder[I].second == I) 5426 continue; 5427 // Ideally we would be using InsertFromRange here, but clang doesn't 5428 // appear to handle InsertFromRange correctly when the source range is 5429 // modified by another fix-it. 5430 D << FixItHint::CreateReplacement( 5431 Inits[I]->getSourceRange(), 5432 Lexer::getSourceText( 5433 CharSourceRange::getTokenRange( 5434 Inits[CorrelatedInitOrder[I].second]->getSourceRange()), 5435 SemaRef.getSourceManager(), SemaRef.getLangOpts())); 5436 } 5437 5438 // If there is only 1 item out of order, the warning expects the name and 5439 // type of each being added to it. 5440 if (WarnIndexes.size() == 1) { 5441 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1], 5442 Inits[WarnIndexes.front()]); 5443 return; 5444 } 5445 } 5446 // More than 1 item to warn, create notes letting the user know which ones 5447 // are bad. 5448 for (unsigned WarnIndex : WarnIndexes) { 5449 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1]; 5450 auto D = SemaRef.Diag(PrevInit->getSourceLocation(), 5451 diag::note_initializer_out_of_order); 5452 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]); 5453 D << PrevInit->getSourceRange(); 5454 } 5455 } 5456 5457 namespace { 5458 bool CheckRedundantInit(Sema &S, 5459 CXXCtorInitializer *Init, 5460 CXXCtorInitializer *&PrevInit) { 5461 if (!PrevInit) { 5462 PrevInit = Init; 5463 return false; 5464 } 5465 5466 if (FieldDecl *Field = Init->getAnyMember()) 5467 S.Diag(Init->getSourceLocation(), 5468 diag::err_multiple_mem_initialization) 5469 << Field->getDeclName() 5470 << Init->getSourceRange(); 5471 else { 5472 const Type *BaseClass = Init->getBaseClass(); 5473 assert(BaseClass && "neither field nor base"); 5474 S.Diag(Init->getSourceLocation(), 5475 diag::err_multiple_base_initialization) 5476 << QualType(BaseClass, 0) 5477 << Init->getSourceRange(); 5478 } 5479 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5480 << 0 << PrevInit->getSourceRange(); 5481 5482 return true; 5483 } 5484 5485 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5486 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5487 5488 bool CheckRedundantUnionInit(Sema &S, 5489 CXXCtorInitializer *Init, 5490 RedundantUnionMap &Unions) { 5491 FieldDecl *Field = Init->getAnyMember(); 5492 RecordDecl *Parent = Field->getParent(); 5493 NamedDecl *Child = Field; 5494 5495 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5496 if (Parent->isUnion()) { 5497 UnionEntry &En = Unions[Parent]; 5498 if (En.first && En.first != Child) { 5499 S.Diag(Init->getSourceLocation(), 5500 diag::err_multiple_mem_union_initialization) 5501 << Field->getDeclName() 5502 << Init->getSourceRange(); 5503 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5504 << 0 << En.second->getSourceRange(); 5505 return true; 5506 } 5507 if (!En.first) { 5508 En.first = Child; 5509 En.second = Init; 5510 } 5511 if (!Parent->isAnonymousStructOrUnion()) 5512 return false; 5513 } 5514 5515 Child = Parent; 5516 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5517 } 5518 5519 return false; 5520 } 5521 } // namespace 5522 5523 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5524 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5525 SourceLocation ColonLoc, 5526 ArrayRef<CXXCtorInitializer*> MemInits, 5527 bool AnyErrors) { 5528 if (!ConstructorDecl) 5529 return; 5530 5531 AdjustDeclIfTemplate(ConstructorDecl); 5532 5533 CXXConstructorDecl *Constructor 5534 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5535 5536 if (!Constructor) { 5537 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5538 return; 5539 } 5540 5541 // Mapping for the duplicate initializers check. 5542 // For member initializers, this is keyed with a FieldDecl*. 5543 // For base initializers, this is keyed with a Type*. 5544 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5545 5546 // Mapping for the inconsistent anonymous-union initializers check. 5547 RedundantUnionMap MemberUnions; 5548 5549 bool HadError = false; 5550 for (unsigned i = 0; i < MemInits.size(); i++) { 5551 CXXCtorInitializer *Init = MemInits[i]; 5552 5553 // Set the source order index. 5554 Init->setSourceOrder(i); 5555 5556 if (Init->isAnyMemberInitializer()) { 5557 const void *Key = GetKeyForMember(Context, Init); 5558 if (CheckRedundantInit(*this, Init, Members[Key]) || 5559 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5560 HadError = true; 5561 } else if (Init->isBaseInitializer()) { 5562 const void *Key = GetKeyForMember(Context, Init); 5563 if (CheckRedundantInit(*this, Init, Members[Key])) 5564 HadError = true; 5565 } else { 5566 assert(Init->isDelegatingInitializer()); 5567 // This must be the only initializer 5568 if (MemInits.size() != 1) { 5569 Diag(Init->getSourceLocation(), 5570 diag::err_delegating_initializer_alone) 5571 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5572 // We will treat this as being the only initializer. 5573 } 5574 SetDelegatingInitializer(Constructor, MemInits[i]); 5575 // Return immediately as the initializer is set. 5576 return; 5577 } 5578 } 5579 5580 if (HadError) 5581 return; 5582 5583 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5584 5585 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5586 5587 DiagnoseUninitializedFields(*this, Constructor); 5588 } 5589 5590 void 5591 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5592 CXXRecordDecl *ClassDecl) { 5593 // Ignore dependent contexts. Also ignore unions, since their members never 5594 // have destructors implicitly called. 5595 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5596 return; 5597 5598 // FIXME: all the access-control diagnostics are positioned on the 5599 // field/base declaration. That's probably good; that said, the 5600 // user might reasonably want to know why the destructor is being 5601 // emitted, and we currently don't say. 5602 5603 // Non-static data members. 5604 for (auto *Field : ClassDecl->fields()) { 5605 if (Field->isInvalidDecl()) 5606 continue; 5607 5608 // Don't destroy incomplete or zero-length arrays. 5609 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5610 continue; 5611 5612 QualType FieldType = Context.getBaseElementType(Field->getType()); 5613 5614 const RecordType* RT = FieldType->getAs<RecordType>(); 5615 if (!RT) 5616 continue; 5617 5618 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5619 if (FieldClassDecl->isInvalidDecl()) 5620 continue; 5621 if (FieldClassDecl->hasIrrelevantDestructor()) 5622 continue; 5623 // The destructor for an implicit anonymous union member is never invoked. 5624 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5625 continue; 5626 5627 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5628 assert(Dtor && "No dtor found for FieldClassDecl!"); 5629 CheckDestructorAccess(Field->getLocation(), Dtor, 5630 PDiag(diag::err_access_dtor_field) 5631 << Field->getDeclName() 5632 << FieldType); 5633 5634 MarkFunctionReferenced(Location, Dtor); 5635 DiagnoseUseOfDecl(Dtor, Location); 5636 } 5637 5638 // We only potentially invoke the destructors of potentially constructed 5639 // subobjects. 5640 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5641 5642 // If the destructor exists and has already been marked used in the MS ABI, 5643 // then virtual base destructors have already been checked and marked used. 5644 // Skip checking them again to avoid duplicate diagnostics. 5645 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5646 CXXDestructorDecl *Dtor = ClassDecl->getDestructor(); 5647 if (Dtor && Dtor->isUsed()) 5648 VisitVirtualBases = false; 5649 } 5650 5651 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5652 5653 // Bases. 5654 for (const auto &Base : ClassDecl->bases()) { 5655 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5656 if (!RT) 5657 continue; 5658 5659 // Remember direct virtual bases. 5660 if (Base.isVirtual()) { 5661 if (!VisitVirtualBases) 5662 continue; 5663 DirectVirtualBases.insert(RT); 5664 } 5665 5666 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5667 // If our base class is invalid, we probably can't get its dtor anyway. 5668 if (BaseClassDecl->isInvalidDecl()) 5669 continue; 5670 if (BaseClassDecl->hasIrrelevantDestructor()) 5671 continue; 5672 5673 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5674 assert(Dtor && "No dtor found for BaseClassDecl!"); 5675 5676 // FIXME: caret should be on the start of the class name 5677 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5678 PDiag(diag::err_access_dtor_base) 5679 << Base.getType() << Base.getSourceRange(), 5680 Context.getTypeDeclType(ClassDecl)); 5681 5682 MarkFunctionReferenced(Location, Dtor); 5683 DiagnoseUseOfDecl(Dtor, Location); 5684 } 5685 5686 if (VisitVirtualBases) 5687 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl, 5688 &DirectVirtualBases); 5689 } 5690 5691 void Sema::MarkVirtualBaseDestructorsReferenced( 5692 SourceLocation Location, CXXRecordDecl *ClassDecl, 5693 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) { 5694 // Virtual bases. 5695 for (const auto &VBase : ClassDecl->vbases()) { 5696 // Bases are always records in a well-formed non-dependent class. 5697 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5698 5699 // Ignore already visited direct virtual bases. 5700 if (DirectVirtualBases && DirectVirtualBases->count(RT)) 5701 continue; 5702 5703 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5704 // If our base class is invalid, we probably can't get its dtor anyway. 5705 if (BaseClassDecl->isInvalidDecl()) 5706 continue; 5707 if (BaseClassDecl->hasIrrelevantDestructor()) 5708 continue; 5709 5710 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5711 assert(Dtor && "No dtor found for BaseClassDecl!"); 5712 if (CheckDestructorAccess( 5713 ClassDecl->getLocation(), Dtor, 5714 PDiag(diag::err_access_dtor_vbase) 5715 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5716 Context.getTypeDeclType(ClassDecl)) == 5717 AR_accessible) { 5718 CheckDerivedToBaseConversion( 5719 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5720 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5721 SourceRange(), DeclarationName(), nullptr); 5722 } 5723 5724 MarkFunctionReferenced(Location, Dtor); 5725 DiagnoseUseOfDecl(Dtor, Location); 5726 } 5727 } 5728 5729 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5730 if (!CDtorDecl) 5731 return; 5732 5733 if (CXXConstructorDecl *Constructor 5734 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5735 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5736 DiagnoseUninitializedFields(*this, Constructor); 5737 } 5738 } 5739 5740 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5741 if (!getLangOpts().CPlusPlus) 5742 return false; 5743 5744 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5745 if (!RD) 5746 return false; 5747 5748 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5749 // class template specialization here, but doing so breaks a lot of code. 5750 5751 // We can't answer whether something is abstract until it has a 5752 // definition. If it's currently being defined, we'll walk back 5753 // over all the declarations when we have a full definition. 5754 const CXXRecordDecl *Def = RD->getDefinition(); 5755 if (!Def || Def->isBeingDefined()) 5756 return false; 5757 5758 return RD->isAbstract(); 5759 } 5760 5761 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5762 TypeDiagnoser &Diagnoser) { 5763 if (!isAbstractType(Loc, T)) 5764 return false; 5765 5766 T = Context.getBaseElementType(T); 5767 Diagnoser.diagnose(*this, Loc, T); 5768 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5769 return true; 5770 } 5771 5772 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5773 // Check if we've already emitted the list of pure virtual functions 5774 // for this class. 5775 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5776 return; 5777 5778 // If the diagnostic is suppressed, don't emit the notes. We're only 5779 // going to emit them once, so try to attach them to a diagnostic we're 5780 // actually going to show. 5781 if (Diags.isLastDiagnosticIgnored()) 5782 return; 5783 5784 CXXFinalOverriderMap FinalOverriders; 5785 RD->getFinalOverriders(FinalOverriders); 5786 5787 // Keep a set of seen pure methods so we won't diagnose the same method 5788 // more than once. 5789 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5790 5791 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5792 MEnd = FinalOverriders.end(); 5793 M != MEnd; 5794 ++M) { 5795 for (OverridingMethods::iterator SO = M->second.begin(), 5796 SOEnd = M->second.end(); 5797 SO != SOEnd; ++SO) { 5798 // C++ [class.abstract]p4: 5799 // A class is abstract if it contains or inherits at least one 5800 // pure virtual function for which the final overrider is pure 5801 // virtual. 5802 5803 // 5804 if (SO->second.size() != 1) 5805 continue; 5806 5807 if (!SO->second.front().Method->isPure()) 5808 continue; 5809 5810 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5811 continue; 5812 5813 Diag(SO->second.front().Method->getLocation(), 5814 diag::note_pure_virtual_function) 5815 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5816 } 5817 } 5818 5819 if (!PureVirtualClassDiagSet) 5820 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5821 PureVirtualClassDiagSet->insert(RD); 5822 } 5823 5824 namespace { 5825 struct AbstractUsageInfo { 5826 Sema &S; 5827 CXXRecordDecl *Record; 5828 CanQualType AbstractType; 5829 bool Invalid; 5830 5831 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5832 : S(S), Record(Record), 5833 AbstractType(S.Context.getCanonicalType( 5834 S.Context.getTypeDeclType(Record))), 5835 Invalid(false) {} 5836 5837 void DiagnoseAbstractType() { 5838 if (Invalid) return; 5839 S.DiagnoseAbstractType(Record); 5840 Invalid = true; 5841 } 5842 5843 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5844 }; 5845 5846 struct CheckAbstractUsage { 5847 AbstractUsageInfo &Info; 5848 const NamedDecl *Ctx; 5849 5850 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5851 : Info(Info), Ctx(Ctx) {} 5852 5853 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5854 switch (TL.getTypeLocClass()) { 5855 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5856 #define TYPELOC(CLASS, PARENT) \ 5857 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5858 #include "clang/AST/TypeLocNodes.def" 5859 } 5860 } 5861 5862 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5863 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5864 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5865 if (!TL.getParam(I)) 5866 continue; 5867 5868 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5869 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5870 } 5871 } 5872 5873 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5874 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5875 } 5876 5877 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5878 // Visit the type parameters from a permissive context. 5879 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5880 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5881 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5882 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5883 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5884 // TODO: other template argument types? 5885 } 5886 } 5887 5888 // Visit pointee types from a permissive context. 5889 #define CheckPolymorphic(Type) \ 5890 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5891 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5892 } 5893 CheckPolymorphic(PointerTypeLoc) 5894 CheckPolymorphic(ReferenceTypeLoc) 5895 CheckPolymorphic(MemberPointerTypeLoc) 5896 CheckPolymorphic(BlockPointerTypeLoc) 5897 CheckPolymorphic(AtomicTypeLoc) 5898 5899 /// Handle all the types we haven't given a more specific 5900 /// implementation for above. 5901 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5902 // Every other kind of type that we haven't called out already 5903 // that has an inner type is either (1) sugar or (2) contains that 5904 // inner type in some way as a subobject. 5905 if (TypeLoc Next = TL.getNextTypeLoc()) 5906 return Visit(Next, Sel); 5907 5908 // If there's no inner type and we're in a permissive context, 5909 // don't diagnose. 5910 if (Sel == Sema::AbstractNone) return; 5911 5912 // Check whether the type matches the abstract type. 5913 QualType T = TL.getType(); 5914 if (T->isArrayType()) { 5915 Sel = Sema::AbstractArrayType; 5916 T = Info.S.Context.getBaseElementType(T); 5917 } 5918 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5919 if (CT != Info.AbstractType) return; 5920 5921 // It matched; do some magic. 5922 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646. 5923 if (Sel == Sema::AbstractArrayType) { 5924 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5925 << T << TL.getSourceRange(); 5926 } else { 5927 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5928 << Sel << T << TL.getSourceRange(); 5929 } 5930 Info.DiagnoseAbstractType(); 5931 } 5932 }; 5933 5934 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5935 Sema::AbstractDiagSelID Sel) { 5936 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5937 } 5938 5939 } 5940 5941 /// Check for invalid uses of an abstract type in a function declaration. 5942 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5943 FunctionDecl *FD) { 5944 // No need to do the check on definitions, which require that 5945 // the return/param types be complete. 5946 if (FD->doesThisDeclarationHaveABody()) 5947 return; 5948 5949 // For safety's sake, just ignore it if we don't have type source 5950 // information. This should never happen for non-implicit methods, 5951 // but... 5952 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5953 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone); 5954 } 5955 5956 /// Check for invalid uses of an abstract type in a variable0 declaration. 5957 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5958 VarDecl *VD) { 5959 // No need to do the check on definitions, which require that 5960 // the type is complete. 5961 if (VD->isThisDeclarationADefinition()) 5962 return; 5963 5964 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(), 5965 Sema::AbstractVariableType); 5966 } 5967 5968 /// Check for invalid uses of an abstract type within a class definition. 5969 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5970 CXXRecordDecl *RD) { 5971 for (auto *D : RD->decls()) { 5972 if (D->isImplicit()) continue; 5973 5974 // Step through friends to the befriended declaration. 5975 if (auto *FD = dyn_cast<FriendDecl>(D)) { 5976 D = FD->getFriendDecl(); 5977 if (!D) continue; 5978 } 5979 5980 // Functions and function templates. 5981 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 5982 CheckAbstractClassUsage(Info, FD); 5983 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) { 5984 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl()); 5985 5986 // Fields and static variables. 5987 } else if (auto *FD = dyn_cast<FieldDecl>(D)) { 5988 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5989 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5990 } else if (auto *VD = dyn_cast<VarDecl>(D)) { 5991 CheckAbstractClassUsage(Info, VD); 5992 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) { 5993 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl()); 5994 5995 // Nested classes and class templates. 5996 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 5997 CheckAbstractClassUsage(Info, RD); 5998 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) { 5999 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl()); 6000 } 6001 } 6002 } 6003 6004 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 6005 Attr *ClassAttr = getDLLAttr(Class); 6006 if (!ClassAttr) 6007 return; 6008 6009 assert(ClassAttr->getKind() == attr::DLLExport); 6010 6011 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6012 6013 if (TSK == TSK_ExplicitInstantiationDeclaration) 6014 // Don't go any further if this is just an explicit instantiation 6015 // declaration. 6016 return; 6017 6018 // Add a context note to explain how we got to any diagnostics produced below. 6019 struct MarkingClassDllexported { 6020 Sema &S; 6021 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class, 6022 SourceLocation AttrLoc) 6023 : S(S) { 6024 Sema::CodeSynthesisContext Ctx; 6025 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported; 6026 Ctx.PointOfInstantiation = AttrLoc; 6027 Ctx.Entity = Class; 6028 S.pushCodeSynthesisContext(Ctx); 6029 } 6030 ~MarkingClassDllexported() { 6031 S.popCodeSynthesisContext(); 6032 } 6033 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); 6034 6035 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 6036 S.MarkVTableUsed(Class->getLocation(), Class, true); 6037 6038 for (Decl *Member : Class->decls()) { 6039 // Skip members that were not marked exported. 6040 if (!Member->hasAttr<DLLExportAttr>()) 6041 continue; 6042 6043 // Defined static variables that are members of an exported base 6044 // class must be marked export too. 6045 auto *VD = dyn_cast<VarDecl>(Member); 6046 if (VD && VD->getStorageClass() == SC_Static && 6047 TSK == TSK_ImplicitInstantiation) 6048 S.MarkVariableReferenced(VD->getLocation(), VD); 6049 6050 auto *MD = dyn_cast<CXXMethodDecl>(Member); 6051 if (!MD) 6052 continue; 6053 6054 if (MD->isUserProvided()) { 6055 // Instantiate non-default class member functions ... 6056 6057 // .. except for certain kinds of template specializations. 6058 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 6059 continue; 6060 6061 // If this is an MS ABI dllexport default constructor, instantiate any 6062 // default arguments. 6063 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 6064 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6065 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) { 6066 S.InstantiateDefaultCtorDefaultArgs(CD); 6067 } 6068 } 6069 6070 S.MarkFunctionReferenced(Class->getLocation(), MD); 6071 6072 // The function will be passed to the consumer when its definition is 6073 // encountered. 6074 } else if (MD->isExplicitlyDefaulted()) { 6075 // Synthesize and instantiate explicitly defaulted methods. 6076 S.MarkFunctionReferenced(Class->getLocation(), MD); 6077 6078 if (TSK != TSK_ExplicitInstantiationDefinition) { 6079 // Except for explicit instantiation defs, we will not see the 6080 // definition again later, so pass it to the consumer now. 6081 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 6082 } 6083 } else if (!MD->isTrivial() || 6084 MD->isCopyAssignmentOperator() || 6085 MD->isMoveAssignmentOperator()) { 6086 // Synthesize and instantiate non-trivial implicit methods, and the copy 6087 // and move assignment operators. The latter are exported even if they 6088 // are trivial, because the address of an operator can be taken and 6089 // should compare equal across libraries. 6090 S.MarkFunctionReferenced(Class->getLocation(), MD); 6091 6092 // There is no later point when we will see the definition of this 6093 // function, so pass it to the consumer now. 6094 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 6095 } 6096 } 6097 } 6098 6099 static void checkForMultipleExportedDefaultConstructors(Sema &S, 6100 CXXRecordDecl *Class) { 6101 // Only the MS ABI has default constructor closures, so we don't need to do 6102 // this semantic checking anywhere else. 6103 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 6104 return; 6105 6106 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 6107 for (Decl *Member : Class->decls()) { 6108 // Look for exported default constructors. 6109 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 6110 if (!CD || !CD->isDefaultConstructor()) 6111 continue; 6112 auto *Attr = CD->getAttr<DLLExportAttr>(); 6113 if (!Attr) 6114 continue; 6115 6116 // If the class is non-dependent, mark the default arguments as ODR-used so 6117 // that we can properly codegen the constructor closure. 6118 if (!Class->isDependentContext()) { 6119 for (ParmVarDecl *PD : CD->parameters()) { 6120 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 6121 S.DiscardCleanupsInEvaluationContext(); 6122 } 6123 } 6124 6125 if (LastExportedDefaultCtor) { 6126 S.Diag(LastExportedDefaultCtor->getLocation(), 6127 diag::err_attribute_dll_ambiguous_default_ctor) 6128 << Class; 6129 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 6130 << CD->getDeclName(); 6131 return; 6132 } 6133 LastExportedDefaultCtor = CD; 6134 } 6135 } 6136 6137 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, 6138 CXXRecordDecl *Class) { 6139 bool ErrorReported = false; 6140 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6141 ClassTemplateDecl *TD) { 6142 if (ErrorReported) 6143 return; 6144 S.Diag(TD->getLocation(), 6145 diag::err_cuda_device_builtin_surftex_cls_template) 6146 << /*surface*/ 0 << TD; 6147 ErrorReported = true; 6148 }; 6149 6150 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6151 if (!TD) { 6152 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6153 if (!SD) { 6154 S.Diag(Class->getLocation(), 6155 diag::err_cuda_device_builtin_surftex_ref_decl) 6156 << /*surface*/ 0 << Class; 6157 S.Diag(Class->getLocation(), 6158 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6159 << Class; 6160 return; 6161 } 6162 TD = SD->getSpecializedTemplate(); 6163 } 6164 6165 TemplateParameterList *Params = TD->getTemplateParameters(); 6166 unsigned N = Params->size(); 6167 6168 if (N != 2) { 6169 reportIllegalClassTemplate(S, TD); 6170 S.Diag(TD->getLocation(), 6171 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6172 << TD << 2; 6173 } 6174 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6175 reportIllegalClassTemplate(S, TD); 6176 S.Diag(TD->getLocation(), 6177 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6178 << TD << /*1st*/ 0 << /*type*/ 0; 6179 } 6180 if (N > 1) { 6181 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6182 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6183 reportIllegalClassTemplate(S, TD); 6184 S.Diag(TD->getLocation(), 6185 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6186 << TD << /*2nd*/ 1 << /*integer*/ 1; 6187 } 6188 } 6189 } 6190 6191 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, 6192 CXXRecordDecl *Class) { 6193 bool ErrorReported = false; 6194 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6195 ClassTemplateDecl *TD) { 6196 if (ErrorReported) 6197 return; 6198 S.Diag(TD->getLocation(), 6199 diag::err_cuda_device_builtin_surftex_cls_template) 6200 << /*texture*/ 1 << TD; 6201 ErrorReported = true; 6202 }; 6203 6204 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6205 if (!TD) { 6206 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6207 if (!SD) { 6208 S.Diag(Class->getLocation(), 6209 diag::err_cuda_device_builtin_surftex_ref_decl) 6210 << /*texture*/ 1 << Class; 6211 S.Diag(Class->getLocation(), 6212 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6213 << Class; 6214 return; 6215 } 6216 TD = SD->getSpecializedTemplate(); 6217 } 6218 6219 TemplateParameterList *Params = TD->getTemplateParameters(); 6220 unsigned N = Params->size(); 6221 6222 if (N != 3) { 6223 reportIllegalClassTemplate(S, TD); 6224 S.Diag(TD->getLocation(), 6225 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6226 << TD << 3; 6227 } 6228 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6229 reportIllegalClassTemplate(S, TD); 6230 S.Diag(TD->getLocation(), 6231 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6232 << TD << /*1st*/ 0 << /*type*/ 0; 6233 } 6234 if (N > 1) { 6235 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6236 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6237 reportIllegalClassTemplate(S, TD); 6238 S.Diag(TD->getLocation(), 6239 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6240 << TD << /*2nd*/ 1 << /*integer*/ 1; 6241 } 6242 } 6243 if (N > 2) { 6244 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2)); 6245 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6246 reportIllegalClassTemplate(S, TD); 6247 S.Diag(TD->getLocation(), 6248 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6249 << TD << /*3rd*/ 2 << /*integer*/ 1; 6250 } 6251 } 6252 } 6253 6254 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 6255 // Mark any compiler-generated routines with the implicit code_seg attribute. 6256 for (auto *Method : Class->methods()) { 6257 if (Method->isUserProvided()) 6258 continue; 6259 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 6260 Method->addAttr(A); 6261 } 6262 } 6263 6264 /// Check class-level dllimport/dllexport attribute. 6265 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 6266 Attr *ClassAttr = getDLLAttr(Class); 6267 6268 // MSVC inherits DLL attributes to partial class template specializations. 6269 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) { 6270 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 6271 if (Attr *TemplateAttr = 6272 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 6273 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 6274 A->setInherited(true); 6275 ClassAttr = A; 6276 } 6277 } 6278 } 6279 6280 if (!ClassAttr) 6281 return; 6282 6283 if (!Class->isExternallyVisible()) { 6284 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 6285 << Class << ClassAttr; 6286 return; 6287 } 6288 6289 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6290 !ClassAttr->isInherited()) { 6291 // Diagnose dll attributes on members of class with dll attribute. 6292 for (Decl *Member : Class->decls()) { 6293 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 6294 continue; 6295 InheritableAttr *MemberAttr = getDLLAttr(Member); 6296 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 6297 continue; 6298 6299 Diag(MemberAttr->getLocation(), 6300 diag::err_attribute_dll_member_of_dll_class) 6301 << MemberAttr << ClassAttr; 6302 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 6303 Member->setInvalidDecl(); 6304 } 6305 } 6306 6307 if (Class->getDescribedClassTemplate()) 6308 // Don't inherit dll attribute until the template is instantiated. 6309 return; 6310 6311 // The class is either imported or exported. 6312 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 6313 6314 // Check if this was a dllimport attribute propagated from a derived class to 6315 // a base class template specialization. We don't apply these attributes to 6316 // static data members. 6317 const bool PropagatedImport = 6318 !ClassExported && 6319 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 6320 6321 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6322 6323 // Ignore explicit dllexport on explicit class template instantiation 6324 // declarations, except in MinGW mode. 6325 if (ClassExported && !ClassAttr->isInherited() && 6326 TSK == TSK_ExplicitInstantiationDeclaration && 6327 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 6328 Class->dropAttr<DLLExportAttr>(); 6329 return; 6330 } 6331 6332 // Force declaration of implicit members so they can inherit the attribute. 6333 ForceDeclarationOfImplicitMembers(Class); 6334 6335 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 6336 // seem to be true in practice? 6337 6338 for (Decl *Member : Class->decls()) { 6339 VarDecl *VD = dyn_cast<VarDecl>(Member); 6340 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 6341 6342 // Only methods and static fields inherit the attributes. 6343 if (!VD && !MD) 6344 continue; 6345 6346 if (MD) { 6347 // Don't process deleted methods. 6348 if (MD->isDeleted()) 6349 continue; 6350 6351 if (MD->isInlined()) { 6352 // MinGW does not import or export inline methods. But do it for 6353 // template instantiations. 6354 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6355 TSK != TSK_ExplicitInstantiationDeclaration && 6356 TSK != TSK_ExplicitInstantiationDefinition) 6357 continue; 6358 6359 // MSVC versions before 2015 don't export the move assignment operators 6360 // and move constructor, so don't attempt to import/export them if 6361 // we have a definition. 6362 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 6363 if ((MD->isMoveAssignmentOperator() || 6364 (Ctor && Ctor->isMoveConstructor())) && 6365 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 6366 continue; 6367 6368 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 6369 // operator is exported anyway. 6370 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6371 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 6372 continue; 6373 } 6374 } 6375 6376 // Don't apply dllimport attributes to static data members of class template 6377 // instantiations when the attribute is propagated from a derived class. 6378 if (VD && PropagatedImport) 6379 continue; 6380 6381 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6382 continue; 6383 6384 if (!getDLLAttr(Member)) { 6385 InheritableAttr *NewAttr = nullptr; 6386 6387 // Do not export/import inline function when -fno-dllexport-inlines is 6388 // passed. But add attribute for later local static var check. 6389 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6390 TSK != TSK_ExplicitInstantiationDeclaration && 6391 TSK != TSK_ExplicitInstantiationDefinition) { 6392 if (ClassExported) { 6393 NewAttr = ::new (getASTContext()) 6394 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6395 } else { 6396 NewAttr = ::new (getASTContext()) 6397 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6398 } 6399 } else { 6400 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6401 } 6402 6403 NewAttr->setInherited(true); 6404 Member->addAttr(NewAttr); 6405 6406 if (MD) { 6407 // Propagate DLLAttr to friend re-declarations of MD that have already 6408 // been constructed. 6409 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6410 FD = FD->getPreviousDecl()) { 6411 if (FD->getFriendObjectKind() == Decl::FOK_None) 6412 continue; 6413 assert(!getDLLAttr(FD) && 6414 "friend re-decl should not already have a DLLAttr"); 6415 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6416 NewAttr->setInherited(true); 6417 FD->addAttr(NewAttr); 6418 } 6419 } 6420 } 6421 } 6422 6423 if (ClassExported) 6424 DelayedDllExportClasses.push_back(Class); 6425 } 6426 6427 /// Perform propagation of DLL attributes from a derived class to a 6428 /// templated base class for MS compatibility. 6429 void Sema::propagateDLLAttrToBaseClassTemplate( 6430 CXXRecordDecl *Class, Attr *ClassAttr, 6431 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6432 if (getDLLAttr( 6433 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6434 // If the base class template has a DLL attribute, don't try to change it. 6435 return; 6436 } 6437 6438 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6439 if (!getDLLAttr(BaseTemplateSpec) && 6440 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6441 TSK == TSK_ImplicitInstantiation)) { 6442 // The template hasn't been instantiated yet (or it has, but only as an 6443 // explicit instantiation declaration or implicit instantiation, which means 6444 // we haven't codegenned any members yet), so propagate the attribute. 6445 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6446 NewAttr->setInherited(true); 6447 BaseTemplateSpec->addAttr(NewAttr); 6448 6449 // If this was an import, mark that we propagated it from a derived class to 6450 // a base class template specialization. 6451 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6452 ImportAttr->setPropagatedToBaseTemplate(); 6453 6454 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6455 // needs to be run again to work see the new attribute. Otherwise this will 6456 // get run whenever the template is instantiated. 6457 if (TSK != TSK_Undeclared) 6458 checkClassLevelDLLAttribute(BaseTemplateSpec); 6459 6460 return; 6461 } 6462 6463 if (getDLLAttr(BaseTemplateSpec)) { 6464 // The template has already been specialized or instantiated with an 6465 // attribute, explicitly or through propagation. We should not try to change 6466 // it. 6467 return; 6468 } 6469 6470 // The template was previously instantiated or explicitly specialized without 6471 // a dll attribute, It's too late for us to add an attribute, so warn that 6472 // this is unsupported. 6473 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6474 << BaseTemplateSpec->isExplicitSpecialization(); 6475 Diag(ClassAttr->getLocation(), diag::note_attribute); 6476 if (BaseTemplateSpec->isExplicitSpecialization()) { 6477 Diag(BaseTemplateSpec->getLocation(), 6478 diag::note_template_class_explicit_specialization_was_here) 6479 << BaseTemplateSpec; 6480 } else { 6481 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6482 diag::note_template_class_instantiation_was_here) 6483 << BaseTemplateSpec; 6484 } 6485 } 6486 6487 /// Determine the kind of defaulting that would be done for a given function. 6488 /// 6489 /// If the function is both a default constructor and a copy / move constructor 6490 /// (due to having a default argument for the first parameter), this picks 6491 /// CXXDefaultConstructor. 6492 /// 6493 /// FIXME: Check that case is properly handled by all callers. 6494 Sema::DefaultedFunctionKind 6495 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6496 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6497 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6498 if (Ctor->isDefaultConstructor()) 6499 return Sema::CXXDefaultConstructor; 6500 6501 if (Ctor->isCopyConstructor()) 6502 return Sema::CXXCopyConstructor; 6503 6504 if (Ctor->isMoveConstructor()) 6505 return Sema::CXXMoveConstructor; 6506 } 6507 6508 if (MD->isCopyAssignmentOperator()) 6509 return Sema::CXXCopyAssignment; 6510 6511 if (MD->isMoveAssignmentOperator()) 6512 return Sema::CXXMoveAssignment; 6513 6514 if (isa<CXXDestructorDecl>(FD)) 6515 return Sema::CXXDestructor; 6516 } 6517 6518 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6519 case OO_EqualEqual: 6520 return DefaultedComparisonKind::Equal; 6521 6522 case OO_ExclaimEqual: 6523 return DefaultedComparisonKind::NotEqual; 6524 6525 case OO_Spaceship: 6526 // No point allowing this if <=> doesn't exist in the current language mode. 6527 if (!getLangOpts().CPlusPlus20) 6528 break; 6529 return DefaultedComparisonKind::ThreeWay; 6530 6531 case OO_Less: 6532 case OO_LessEqual: 6533 case OO_Greater: 6534 case OO_GreaterEqual: 6535 // No point allowing this if <=> doesn't exist in the current language mode. 6536 if (!getLangOpts().CPlusPlus20) 6537 break; 6538 return DefaultedComparisonKind::Relational; 6539 6540 default: 6541 break; 6542 } 6543 6544 // Not defaultable. 6545 return DefaultedFunctionKind(); 6546 } 6547 6548 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, 6549 SourceLocation DefaultLoc) { 6550 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD); 6551 if (DFK.isComparison()) 6552 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison()); 6553 6554 switch (DFK.asSpecialMember()) { 6555 case Sema::CXXDefaultConstructor: 6556 S.DefineImplicitDefaultConstructor(DefaultLoc, 6557 cast<CXXConstructorDecl>(FD)); 6558 break; 6559 case Sema::CXXCopyConstructor: 6560 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6561 break; 6562 case Sema::CXXCopyAssignment: 6563 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6564 break; 6565 case Sema::CXXDestructor: 6566 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD)); 6567 break; 6568 case Sema::CXXMoveConstructor: 6569 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6570 break; 6571 case Sema::CXXMoveAssignment: 6572 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6573 break; 6574 case Sema::CXXInvalid: 6575 llvm_unreachable("Invalid special member."); 6576 } 6577 } 6578 6579 /// Determine whether a type is permitted to be passed or returned in 6580 /// registers, per C++ [class.temporary]p3. 6581 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6582 TargetInfo::CallingConvKind CCK) { 6583 if (D->isDependentType() || D->isInvalidDecl()) 6584 return false; 6585 6586 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6587 // The PS4 platform ABI follows the behavior of Clang 3.2. 6588 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6589 return !D->hasNonTrivialDestructorForCall() && 6590 !D->hasNonTrivialCopyConstructorForCall(); 6591 6592 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6593 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6594 bool DtorIsTrivialForCall = false; 6595 6596 // If a class has at least one non-deleted, trivial copy constructor, it 6597 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6598 // 6599 // Note: This permits classes with non-trivial copy or move ctors to be 6600 // passed in registers, so long as they *also* have a trivial copy ctor, 6601 // which is non-conforming. 6602 if (D->needsImplicitCopyConstructor()) { 6603 if (!D->defaultedCopyConstructorIsDeleted()) { 6604 if (D->hasTrivialCopyConstructor()) 6605 CopyCtorIsTrivial = true; 6606 if (D->hasTrivialCopyConstructorForCall()) 6607 CopyCtorIsTrivialForCall = true; 6608 } 6609 } else { 6610 for (const CXXConstructorDecl *CD : D->ctors()) { 6611 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6612 if (CD->isTrivial()) 6613 CopyCtorIsTrivial = true; 6614 if (CD->isTrivialForCall()) 6615 CopyCtorIsTrivialForCall = true; 6616 } 6617 } 6618 } 6619 6620 if (D->needsImplicitDestructor()) { 6621 if (!D->defaultedDestructorIsDeleted() && 6622 D->hasTrivialDestructorForCall()) 6623 DtorIsTrivialForCall = true; 6624 } else if (const auto *DD = D->getDestructor()) { 6625 if (!DD->isDeleted() && DD->isTrivialForCall()) 6626 DtorIsTrivialForCall = true; 6627 } 6628 6629 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6630 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6631 return true; 6632 6633 // If a class has a destructor, we'd really like to pass it indirectly 6634 // because it allows us to elide copies. Unfortunately, MSVC makes that 6635 // impossible for small types, which it will pass in a single register or 6636 // stack slot. Most objects with dtors are large-ish, so handle that early. 6637 // We can't call out all large objects as being indirect because there are 6638 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6639 // how we pass large POD types. 6640 6641 // Note: This permits small classes with nontrivial destructors to be 6642 // passed in registers, which is non-conforming. 6643 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6644 uint64_t TypeSize = isAArch64 ? 128 : 64; 6645 6646 if (CopyCtorIsTrivial && 6647 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6648 return true; 6649 return false; 6650 } 6651 6652 // Per C++ [class.temporary]p3, the relevant condition is: 6653 // each copy constructor, move constructor, and destructor of X is 6654 // either trivial or deleted, and X has at least one non-deleted copy 6655 // or move constructor 6656 bool HasNonDeletedCopyOrMove = false; 6657 6658 if (D->needsImplicitCopyConstructor() && 6659 !D->defaultedCopyConstructorIsDeleted()) { 6660 if (!D->hasTrivialCopyConstructorForCall()) 6661 return false; 6662 HasNonDeletedCopyOrMove = true; 6663 } 6664 6665 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6666 !D->defaultedMoveConstructorIsDeleted()) { 6667 if (!D->hasTrivialMoveConstructorForCall()) 6668 return false; 6669 HasNonDeletedCopyOrMove = true; 6670 } 6671 6672 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6673 !D->hasTrivialDestructorForCall()) 6674 return false; 6675 6676 for (const CXXMethodDecl *MD : D->methods()) { 6677 if (MD->isDeleted()) 6678 continue; 6679 6680 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6681 if (CD && CD->isCopyOrMoveConstructor()) 6682 HasNonDeletedCopyOrMove = true; 6683 else if (!isa<CXXDestructorDecl>(MD)) 6684 continue; 6685 6686 if (!MD->isTrivialForCall()) 6687 return false; 6688 } 6689 6690 return HasNonDeletedCopyOrMove; 6691 } 6692 6693 /// Report an error regarding overriding, along with any relevant 6694 /// overridden methods. 6695 /// 6696 /// \param DiagID the primary error to report. 6697 /// \param MD the overriding method. 6698 static bool 6699 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, 6700 llvm::function_ref<bool(const CXXMethodDecl *)> Report) { 6701 bool IssuedDiagnostic = false; 6702 for (const CXXMethodDecl *O : MD->overridden_methods()) { 6703 if (Report(O)) { 6704 if (!IssuedDiagnostic) { 6705 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6706 IssuedDiagnostic = true; 6707 } 6708 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 6709 } 6710 } 6711 return IssuedDiagnostic; 6712 } 6713 6714 /// Perform semantic checks on a class definition that has been 6715 /// completing, introducing implicitly-declared members, checking for 6716 /// abstract types, etc. 6717 /// 6718 /// \param S The scope in which the class was parsed. Null if we didn't just 6719 /// parse a class definition. 6720 /// \param Record The completed class. 6721 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6722 if (!Record) 6723 return; 6724 6725 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6726 AbstractUsageInfo Info(*this, Record); 6727 CheckAbstractClassUsage(Info, Record); 6728 } 6729 6730 // If this is not an aggregate type and has no user-declared constructor, 6731 // complain about any non-static data members of reference or const scalar 6732 // type, since they will never get initializers. 6733 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6734 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6735 !Record->isLambda()) { 6736 bool Complained = false; 6737 for (const auto *F : Record->fields()) { 6738 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6739 continue; 6740 6741 if (F->getType()->isReferenceType() || 6742 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6743 if (!Complained) { 6744 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6745 << Record->getTagKind() << Record; 6746 Complained = true; 6747 } 6748 6749 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6750 << F->getType()->isReferenceType() 6751 << F->getDeclName(); 6752 } 6753 } 6754 } 6755 6756 if (Record->getIdentifier()) { 6757 // C++ [class.mem]p13: 6758 // If T is the name of a class, then each of the following shall have a 6759 // name different from T: 6760 // - every member of every anonymous union that is a member of class T. 6761 // 6762 // C++ [class.mem]p14: 6763 // In addition, if class T has a user-declared constructor (12.1), every 6764 // non-static data member of class T shall have a name different from T. 6765 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6766 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6767 ++I) { 6768 NamedDecl *D = (*I)->getUnderlyingDecl(); 6769 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6770 Record->hasUserDeclaredConstructor()) || 6771 isa<IndirectFieldDecl>(D)) { 6772 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6773 << D->getDeclName(); 6774 break; 6775 } 6776 } 6777 } 6778 6779 // Warn if the class has virtual methods but non-virtual public destructor. 6780 if (Record->isPolymorphic() && !Record->isDependentType()) { 6781 CXXDestructorDecl *dtor = Record->getDestructor(); 6782 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6783 !Record->hasAttr<FinalAttr>()) 6784 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6785 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6786 } 6787 6788 if (Record->isAbstract()) { 6789 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6790 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6791 << FA->isSpelledAsSealed(); 6792 DiagnoseAbstractType(Record); 6793 } 6794 } 6795 6796 // Warn if the class has a final destructor but is not itself marked final. 6797 if (!Record->hasAttr<FinalAttr>()) { 6798 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6799 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6800 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6801 << FA->isSpelledAsSealed() 6802 << FixItHint::CreateInsertion( 6803 getLocForEndOfToken(Record->getLocation()), 6804 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6805 Diag(Record->getLocation(), 6806 diag::note_final_dtor_non_final_class_silence) 6807 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6808 } 6809 } 6810 } 6811 6812 // See if trivial_abi has to be dropped. 6813 if (Record->hasAttr<TrivialABIAttr>()) 6814 checkIllFormedTrivialABIStruct(*Record); 6815 6816 // Set HasTrivialSpecialMemberForCall if the record has attribute 6817 // "trivial_abi". 6818 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6819 6820 if (HasTrivialABI) 6821 Record->setHasTrivialSpecialMemberForCall(); 6822 6823 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6824 // We check these last because they can depend on the properties of the 6825 // primary comparison functions (==, <=>). 6826 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6827 6828 // Perform checks that can't be done until we know all the properties of a 6829 // member function (whether it's defaulted, deleted, virtual, overriding, 6830 // ...). 6831 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) { 6832 // A static function cannot override anything. 6833 if (MD->getStorageClass() == SC_Static) { 6834 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD, 6835 [](const CXXMethodDecl *) { return true; })) 6836 return; 6837 } 6838 6839 // A deleted function cannot override a non-deleted function and vice 6840 // versa. 6841 if (ReportOverrides(*this, 6842 MD->isDeleted() ? diag::err_deleted_override 6843 : diag::err_non_deleted_override, 6844 MD, [&](const CXXMethodDecl *V) { 6845 return MD->isDeleted() != V->isDeleted(); 6846 })) { 6847 if (MD->isDefaulted() && MD->isDeleted()) 6848 // Explain why this defaulted function was deleted. 6849 DiagnoseDeletedDefaultedFunction(MD); 6850 return; 6851 } 6852 6853 // A consteval function cannot override a non-consteval function and vice 6854 // versa. 6855 if (ReportOverrides(*this, 6856 MD->isConsteval() ? diag::err_consteval_override 6857 : diag::err_non_consteval_override, 6858 MD, [&](const CXXMethodDecl *V) { 6859 return MD->isConsteval() != V->isConsteval(); 6860 })) { 6861 if (MD->isDefaulted() && MD->isDeleted()) 6862 // Explain why this defaulted function was deleted. 6863 DiagnoseDeletedDefaultedFunction(MD); 6864 return; 6865 } 6866 }; 6867 6868 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool { 6869 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6870 return false; 6871 6872 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6873 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6874 DFK.asComparison() == DefaultedComparisonKind::Relational) { 6875 DefaultedSecondaryComparisons.push_back(FD); 6876 return true; 6877 } 6878 6879 CheckExplicitlyDefaultedFunction(S, FD); 6880 return false; 6881 }; 6882 6883 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6884 // Check whether the explicitly-defaulted members are valid. 6885 bool Incomplete = CheckForDefaultedFunction(M); 6886 6887 // Skip the rest of the checks for a member of a dependent class. 6888 if (Record->isDependentType()) 6889 return; 6890 6891 // For an explicitly defaulted or deleted special member, we defer 6892 // determining triviality until the class is complete. That time is now! 6893 CXXSpecialMember CSM = getSpecialMember(M); 6894 if (!M->isImplicit() && !M->isUserProvided()) { 6895 if (CSM != CXXInvalid) { 6896 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6897 // Inform the class that we've finished declaring this member. 6898 Record->finishedDefaultedOrDeletedMember(M); 6899 M->setTrivialForCall( 6900 HasTrivialABI || 6901 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6902 Record->setTrivialForCallFlags(M); 6903 } 6904 } 6905 6906 // Set triviality for the purpose of calls if this is a user-provided 6907 // copy/move constructor or destructor. 6908 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6909 CSM == CXXDestructor) && M->isUserProvided()) { 6910 M->setTrivialForCall(HasTrivialABI); 6911 Record->setTrivialForCallFlags(M); 6912 } 6913 6914 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6915 M->hasAttr<DLLExportAttr>()) { 6916 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6917 M->isTrivial() && 6918 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6919 CSM == CXXDestructor)) 6920 M->dropAttr<DLLExportAttr>(); 6921 6922 if (M->hasAttr<DLLExportAttr>()) { 6923 // Define after any fields with in-class initializers have been parsed. 6924 DelayedDllExportMemberFunctions.push_back(M); 6925 } 6926 } 6927 6928 // Define defaulted constexpr virtual functions that override a base class 6929 // function right away. 6930 // FIXME: We can defer doing this until the vtable is marked as used. 6931 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6932 DefineDefaultedFunction(*this, M, M->getLocation()); 6933 6934 if (!Incomplete) 6935 CheckCompletedMemberFunction(M); 6936 }; 6937 6938 // Check the destructor before any other member function. We need to 6939 // determine whether it's trivial in order to determine whether the claas 6940 // type is a literal type, which is a prerequisite for determining whether 6941 // other special member functions are valid and whether they're implicitly 6942 // 'constexpr'. 6943 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6944 CompleteMemberFunction(Dtor); 6945 6946 bool HasMethodWithOverrideControl = false, 6947 HasOverridingMethodWithoutOverrideControl = false; 6948 for (auto *D : Record->decls()) { 6949 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 6950 // FIXME: We could do this check for dependent types with non-dependent 6951 // bases. 6952 if (!Record->isDependentType()) { 6953 // See if a method overloads virtual methods in a base 6954 // class without overriding any. 6955 if (!M->isStatic()) 6956 DiagnoseHiddenVirtualMethods(M); 6957 if (M->hasAttr<OverrideAttr>()) 6958 HasMethodWithOverrideControl = true; 6959 else if (M->size_overridden_methods() > 0) 6960 HasOverridingMethodWithoutOverrideControl = true; 6961 } 6962 6963 if (!isa<CXXDestructorDecl>(M)) 6964 CompleteMemberFunction(M); 6965 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 6966 CheckForDefaultedFunction( 6967 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 6968 } 6969 } 6970 6971 if (HasOverridingMethodWithoutOverrideControl) { 6972 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl; 6973 for (auto *M : Record->methods()) 6974 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl); 6975 } 6976 6977 // Check the defaulted secondary comparisons after any other member functions. 6978 for (FunctionDecl *FD : DefaultedSecondaryComparisons) { 6979 CheckExplicitlyDefaultedFunction(S, FD); 6980 6981 // If this is a member function, we deferred checking it until now. 6982 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) 6983 CheckCompletedMemberFunction(MD); 6984 } 6985 6986 // ms_struct is a request to use the same ABI rules as MSVC. Check 6987 // whether this class uses any C++ features that are implemented 6988 // completely differently in MSVC, and if so, emit a diagnostic. 6989 // That diagnostic defaults to an error, but we allow projects to 6990 // map it down to a warning (or ignore it). It's a fairly common 6991 // practice among users of the ms_struct pragma to mass-annotate 6992 // headers, sweeping up a bunch of types that the project doesn't 6993 // really rely on MSVC-compatible layout for. We must therefore 6994 // support "ms_struct except for C++ stuff" as a secondary ABI. 6995 // Don't emit this diagnostic if the feature was enabled as a 6996 // language option (as opposed to via a pragma or attribute), as 6997 // the option -mms-bitfields otherwise essentially makes it impossible 6998 // to build C++ code, unless this diagnostic is turned off. 6999 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields && 7000 (Record->isPolymorphic() || Record->getNumBases())) { 7001 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 7002 } 7003 7004 checkClassLevelDLLAttribute(Record); 7005 checkClassLevelCodeSegAttribute(Record); 7006 7007 bool ClangABICompat4 = 7008 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 7009 TargetInfo::CallingConvKind CCK = 7010 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 7011 bool CanPass = canPassInRegisters(*this, Record, CCK); 7012 7013 // Do not change ArgPassingRestrictions if it has already been set to 7014 // APK_CanNeverPassInRegs. 7015 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 7016 Record->setArgPassingRestrictions(CanPass 7017 ? RecordDecl::APK_CanPassInRegs 7018 : RecordDecl::APK_CannotPassInRegs); 7019 7020 // If canPassInRegisters returns true despite the record having a non-trivial 7021 // destructor, the record is destructed in the callee. This happens only when 7022 // the record or one of its subobjects has a field annotated with trivial_abi 7023 // or a field qualified with ObjC __strong/__weak. 7024 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 7025 Record->setParamDestroyedInCallee(true); 7026 else if (Record->hasNonTrivialDestructor()) 7027 Record->setParamDestroyedInCallee(CanPass); 7028 7029 if (getLangOpts().ForceEmitVTables) { 7030 // If we want to emit all the vtables, we need to mark it as used. This 7031 // is especially required for cases like vtable assumption loads. 7032 MarkVTableUsed(Record->getInnerLocStart(), Record); 7033 } 7034 7035 if (getLangOpts().CUDA) { 7036 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) 7037 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record); 7038 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>()) 7039 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record); 7040 } 7041 } 7042 7043 /// Look up the special member function that would be called by a special 7044 /// member function for a subobject of class type. 7045 /// 7046 /// \param Class The class type of the subobject. 7047 /// \param CSM The kind of special member function. 7048 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 7049 /// \param ConstRHS True if this is a copy operation with a const object 7050 /// on its RHS, that is, if the argument to the outer special member 7051 /// function is 'const' and this is not a field marked 'mutable'. 7052 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 7053 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 7054 unsigned FieldQuals, bool ConstRHS) { 7055 unsigned LHSQuals = 0; 7056 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 7057 LHSQuals = FieldQuals; 7058 7059 unsigned RHSQuals = FieldQuals; 7060 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 7061 RHSQuals = 0; 7062 else if (ConstRHS) 7063 RHSQuals |= Qualifiers::Const; 7064 7065 return S.LookupSpecialMember(Class, CSM, 7066 RHSQuals & Qualifiers::Const, 7067 RHSQuals & Qualifiers::Volatile, 7068 false, 7069 LHSQuals & Qualifiers::Const, 7070 LHSQuals & Qualifiers::Volatile); 7071 } 7072 7073 class Sema::InheritedConstructorInfo { 7074 Sema &S; 7075 SourceLocation UseLoc; 7076 7077 /// A mapping from the base classes through which the constructor was 7078 /// inherited to the using shadow declaration in that base class (or a null 7079 /// pointer if the constructor was declared in that base class). 7080 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 7081 InheritedFromBases; 7082 7083 public: 7084 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 7085 ConstructorUsingShadowDecl *Shadow) 7086 : S(S), UseLoc(UseLoc) { 7087 bool DiagnosedMultipleConstructedBases = false; 7088 CXXRecordDecl *ConstructedBase = nullptr; 7089 BaseUsingDecl *ConstructedBaseIntroducer = nullptr; 7090 7091 // Find the set of such base class subobjects and check that there's a 7092 // unique constructed subobject. 7093 for (auto *D : Shadow->redecls()) { 7094 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 7095 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 7096 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 7097 7098 InheritedFromBases.insert( 7099 std::make_pair(DNominatedBase->getCanonicalDecl(), 7100 DShadow->getNominatedBaseClassShadowDecl())); 7101 if (DShadow->constructsVirtualBase()) 7102 InheritedFromBases.insert( 7103 std::make_pair(DConstructedBase->getCanonicalDecl(), 7104 DShadow->getConstructedBaseClassShadowDecl())); 7105 else 7106 assert(DNominatedBase == DConstructedBase); 7107 7108 // [class.inhctor.init]p2: 7109 // If the constructor was inherited from multiple base class subobjects 7110 // of type B, the program is ill-formed. 7111 if (!ConstructedBase) { 7112 ConstructedBase = DConstructedBase; 7113 ConstructedBaseIntroducer = D->getIntroducer(); 7114 } else if (ConstructedBase != DConstructedBase && 7115 !Shadow->isInvalidDecl()) { 7116 if (!DiagnosedMultipleConstructedBases) { 7117 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 7118 << Shadow->getTargetDecl(); 7119 S.Diag(ConstructedBaseIntroducer->getLocation(), 7120 diag::note_ambiguous_inherited_constructor_using) 7121 << ConstructedBase; 7122 DiagnosedMultipleConstructedBases = true; 7123 } 7124 S.Diag(D->getIntroducer()->getLocation(), 7125 diag::note_ambiguous_inherited_constructor_using) 7126 << DConstructedBase; 7127 } 7128 } 7129 7130 if (DiagnosedMultipleConstructedBases) 7131 Shadow->setInvalidDecl(); 7132 } 7133 7134 /// Find the constructor to use for inherited construction of a base class, 7135 /// and whether that base class constructor inherits the constructor from a 7136 /// virtual base class (in which case it won't actually invoke it). 7137 std::pair<CXXConstructorDecl *, bool> 7138 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 7139 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 7140 if (It == InheritedFromBases.end()) 7141 return std::make_pair(nullptr, false); 7142 7143 // This is an intermediary class. 7144 if (It->second) 7145 return std::make_pair( 7146 S.findInheritingConstructor(UseLoc, Ctor, It->second), 7147 It->second->constructsVirtualBase()); 7148 7149 // This is the base class from which the constructor was inherited. 7150 return std::make_pair(Ctor, false); 7151 } 7152 }; 7153 7154 /// Is the special member function which would be selected to perform the 7155 /// specified operation on the specified class type a constexpr constructor? 7156 static bool 7157 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 7158 Sema::CXXSpecialMember CSM, unsigned Quals, 7159 bool ConstRHS, 7160 CXXConstructorDecl *InheritedCtor = nullptr, 7161 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7162 // If we're inheriting a constructor, see if we need to call it for this base 7163 // class. 7164 if (InheritedCtor) { 7165 assert(CSM == Sema::CXXDefaultConstructor); 7166 auto BaseCtor = 7167 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 7168 if (BaseCtor) 7169 return BaseCtor->isConstexpr(); 7170 } 7171 7172 if (CSM == Sema::CXXDefaultConstructor) 7173 return ClassDecl->hasConstexprDefaultConstructor(); 7174 if (CSM == Sema::CXXDestructor) 7175 return ClassDecl->hasConstexprDestructor(); 7176 7177 Sema::SpecialMemberOverloadResult SMOR = 7178 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 7179 if (!SMOR.getMethod()) 7180 // A constructor we wouldn't select can't be "involved in initializing" 7181 // anything. 7182 return true; 7183 return SMOR.getMethod()->isConstexpr(); 7184 } 7185 7186 /// Determine whether the specified special member function would be constexpr 7187 /// if it were implicitly defined. 7188 static bool defaultedSpecialMemberIsConstexpr( 7189 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 7190 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 7191 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7192 if (!S.getLangOpts().CPlusPlus11) 7193 return false; 7194 7195 // C++11 [dcl.constexpr]p4: 7196 // In the definition of a constexpr constructor [...] 7197 bool Ctor = true; 7198 switch (CSM) { 7199 case Sema::CXXDefaultConstructor: 7200 if (Inherited) 7201 break; 7202 // Since default constructor lookup is essentially trivial (and cannot 7203 // involve, for instance, template instantiation), we compute whether a 7204 // defaulted default constructor is constexpr directly within CXXRecordDecl. 7205 // 7206 // This is important for performance; we need to know whether the default 7207 // constructor is constexpr to determine whether the type is a literal type. 7208 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 7209 7210 case Sema::CXXCopyConstructor: 7211 case Sema::CXXMoveConstructor: 7212 // For copy or move constructors, we need to perform overload resolution. 7213 break; 7214 7215 case Sema::CXXCopyAssignment: 7216 case Sema::CXXMoveAssignment: 7217 if (!S.getLangOpts().CPlusPlus14) 7218 return false; 7219 // In C++1y, we need to perform overload resolution. 7220 Ctor = false; 7221 break; 7222 7223 case Sema::CXXDestructor: 7224 return ClassDecl->defaultedDestructorIsConstexpr(); 7225 7226 case Sema::CXXInvalid: 7227 return false; 7228 } 7229 7230 // -- if the class is a non-empty union, or for each non-empty anonymous 7231 // union member of a non-union class, exactly one non-static data member 7232 // shall be initialized; [DR1359] 7233 // 7234 // If we squint, this is guaranteed, since exactly one non-static data member 7235 // will be initialized (if the constructor isn't deleted), we just don't know 7236 // which one. 7237 if (Ctor && ClassDecl->isUnion()) 7238 return CSM == Sema::CXXDefaultConstructor 7239 ? ClassDecl->hasInClassInitializer() || 7240 !ClassDecl->hasVariantMembers() 7241 : true; 7242 7243 // -- the class shall not have any virtual base classes; 7244 if (Ctor && ClassDecl->getNumVBases()) 7245 return false; 7246 7247 // C++1y [class.copy]p26: 7248 // -- [the class] is a literal type, and 7249 if (!Ctor && !ClassDecl->isLiteral()) 7250 return false; 7251 7252 // -- every constructor involved in initializing [...] base class 7253 // sub-objects shall be a constexpr constructor; 7254 // -- the assignment operator selected to copy/move each direct base 7255 // class is a constexpr function, and 7256 for (const auto &B : ClassDecl->bases()) { 7257 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 7258 if (!BaseType) continue; 7259 7260 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7261 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 7262 InheritedCtor, Inherited)) 7263 return false; 7264 } 7265 7266 // -- every constructor involved in initializing non-static data members 7267 // [...] shall be a constexpr constructor; 7268 // -- every non-static data member and base class sub-object shall be 7269 // initialized 7270 // -- for each non-static data member of X that is of class type (or array 7271 // thereof), the assignment operator selected to copy/move that member is 7272 // a constexpr function 7273 for (const auto *F : ClassDecl->fields()) { 7274 if (F->isInvalidDecl()) 7275 continue; 7276 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 7277 continue; 7278 QualType BaseType = S.Context.getBaseElementType(F->getType()); 7279 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 7280 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7281 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 7282 BaseType.getCVRQualifiers(), 7283 ConstArg && !F->isMutable())) 7284 return false; 7285 } else if (CSM == Sema::CXXDefaultConstructor) { 7286 return false; 7287 } 7288 } 7289 7290 // All OK, it's constexpr! 7291 return true; 7292 } 7293 7294 namespace { 7295 /// RAII object to register a defaulted function as having its exception 7296 /// specification computed. 7297 struct ComputingExceptionSpec { 7298 Sema &S; 7299 7300 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 7301 : S(S) { 7302 Sema::CodeSynthesisContext Ctx; 7303 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 7304 Ctx.PointOfInstantiation = Loc; 7305 Ctx.Entity = FD; 7306 S.pushCodeSynthesisContext(Ctx); 7307 } 7308 ~ComputingExceptionSpec() { 7309 S.popCodeSynthesisContext(); 7310 } 7311 }; 7312 } 7313 7314 static Sema::ImplicitExceptionSpecification 7315 ComputeDefaultedSpecialMemberExceptionSpec( 7316 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 7317 Sema::InheritedConstructorInfo *ICI); 7318 7319 static Sema::ImplicitExceptionSpecification 7320 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 7321 FunctionDecl *FD, 7322 Sema::DefaultedComparisonKind DCK); 7323 7324 static Sema::ImplicitExceptionSpecification 7325 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 7326 auto DFK = S.getDefaultedFunctionKind(FD); 7327 if (DFK.isSpecialMember()) 7328 return ComputeDefaultedSpecialMemberExceptionSpec( 7329 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 7330 if (DFK.isComparison()) 7331 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 7332 DFK.asComparison()); 7333 7334 auto *CD = cast<CXXConstructorDecl>(FD); 7335 assert(CD->getInheritedConstructor() && 7336 "only defaulted functions and inherited constructors have implicit " 7337 "exception specs"); 7338 Sema::InheritedConstructorInfo ICI( 7339 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 7340 return ComputeDefaultedSpecialMemberExceptionSpec( 7341 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 7342 } 7343 7344 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 7345 CXXMethodDecl *MD) { 7346 FunctionProtoType::ExtProtoInfo EPI; 7347 7348 // Build an exception specification pointing back at this member. 7349 EPI.ExceptionSpec.Type = EST_Unevaluated; 7350 EPI.ExceptionSpec.SourceDecl = MD; 7351 7352 // Set the calling convention to the default for C++ instance methods. 7353 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 7354 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 7355 /*IsCXXMethod=*/true)); 7356 return EPI; 7357 } 7358 7359 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 7360 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 7361 if (FPT->getExceptionSpecType() != EST_Unevaluated) 7362 return; 7363 7364 // Evaluate the exception specification. 7365 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 7366 auto ESI = IES.getExceptionSpec(); 7367 7368 // Update the type of the special member to use it. 7369 UpdateExceptionSpec(FD, ESI); 7370 } 7371 7372 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 7373 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted"); 7374 7375 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 7376 if (!DefKind) { 7377 assert(FD->getDeclContext()->isDependentContext()); 7378 return; 7379 } 7380 7381 if (DefKind.isComparison()) 7382 UnusedPrivateFields.clear(); 7383 7384 if (DefKind.isSpecialMember() 7385 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 7386 DefKind.asSpecialMember()) 7387 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 7388 FD->setInvalidDecl(); 7389 } 7390 7391 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7392 CXXSpecialMember CSM) { 7393 CXXRecordDecl *RD = MD->getParent(); 7394 7395 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 7396 "not an explicitly-defaulted special member"); 7397 7398 // Defer all checking for special members of a dependent type. 7399 if (RD->isDependentType()) 7400 return false; 7401 7402 // Whether this was the first-declared instance of the constructor. 7403 // This affects whether we implicitly add an exception spec and constexpr. 7404 bool First = MD == MD->getCanonicalDecl(); 7405 7406 bool HadError = false; 7407 7408 // C++11 [dcl.fct.def.default]p1: 7409 // A function that is explicitly defaulted shall 7410 // -- be a special member function [...] (checked elsewhere), 7411 // -- have the same type (except for ref-qualifiers, and except that a 7412 // copy operation can take a non-const reference) as an implicit 7413 // declaration, and 7414 // -- not have default arguments. 7415 // C++2a changes the second bullet to instead delete the function if it's 7416 // defaulted on its first declaration, unless it's "an assignment operator, 7417 // and its return type differs or its parameter type is not a reference". 7418 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First; 7419 bool ShouldDeleteForTypeMismatch = false; 7420 unsigned ExpectedParams = 1; 7421 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 7422 ExpectedParams = 0; 7423 if (MD->getNumParams() != ExpectedParams) { 7424 // This checks for default arguments: a copy or move constructor with a 7425 // default argument is classified as a default constructor, and assignment 7426 // operations and destructors can't have default arguments. 7427 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 7428 << CSM << MD->getSourceRange(); 7429 HadError = true; 7430 } else if (MD->isVariadic()) { 7431 if (DeleteOnTypeMismatch) 7432 ShouldDeleteForTypeMismatch = true; 7433 else { 7434 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 7435 << CSM << MD->getSourceRange(); 7436 HadError = true; 7437 } 7438 } 7439 7440 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 7441 7442 bool CanHaveConstParam = false; 7443 if (CSM == CXXCopyConstructor) 7444 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 7445 else if (CSM == CXXCopyAssignment) 7446 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 7447 7448 QualType ReturnType = Context.VoidTy; 7449 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 7450 // Check for return type matching. 7451 ReturnType = Type->getReturnType(); 7452 7453 QualType DeclType = Context.getTypeDeclType(RD); 7454 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 7455 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 7456 7457 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 7458 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 7459 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 7460 HadError = true; 7461 } 7462 7463 // A defaulted special member cannot have cv-qualifiers. 7464 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 7465 if (DeleteOnTypeMismatch) 7466 ShouldDeleteForTypeMismatch = true; 7467 else { 7468 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 7469 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 7470 HadError = true; 7471 } 7472 } 7473 } 7474 7475 // Check for parameter type matching. 7476 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 7477 bool HasConstParam = false; 7478 if (ExpectedParams && ArgType->isReferenceType()) { 7479 // Argument must be reference to possibly-const T. 7480 QualType ReferentType = ArgType->getPointeeType(); 7481 HasConstParam = ReferentType.isConstQualified(); 7482 7483 if (ReferentType.isVolatileQualified()) { 7484 if (DeleteOnTypeMismatch) 7485 ShouldDeleteForTypeMismatch = true; 7486 else { 7487 Diag(MD->getLocation(), 7488 diag::err_defaulted_special_member_volatile_param) << CSM; 7489 HadError = true; 7490 } 7491 } 7492 7493 if (HasConstParam && !CanHaveConstParam) { 7494 if (DeleteOnTypeMismatch) 7495 ShouldDeleteForTypeMismatch = true; 7496 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7497 Diag(MD->getLocation(), 7498 diag::err_defaulted_special_member_copy_const_param) 7499 << (CSM == CXXCopyAssignment); 7500 // FIXME: Explain why this special member can't be const. 7501 HadError = true; 7502 } else { 7503 Diag(MD->getLocation(), 7504 diag::err_defaulted_special_member_move_const_param) 7505 << (CSM == CXXMoveAssignment); 7506 HadError = true; 7507 } 7508 } 7509 } else if (ExpectedParams) { 7510 // A copy assignment operator can take its argument by value, but a 7511 // defaulted one cannot. 7512 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 7513 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7514 HadError = true; 7515 } 7516 7517 // C++11 [dcl.fct.def.default]p2: 7518 // An explicitly-defaulted function may be declared constexpr only if it 7519 // would have been implicitly declared as constexpr, 7520 // Do not apply this rule to members of class templates, since core issue 1358 7521 // makes such functions always instantiate to constexpr functions. For 7522 // functions which cannot be constexpr (for non-constructors in C++11 and for 7523 // destructors in C++14 and C++17), this is checked elsewhere. 7524 // 7525 // FIXME: This should not apply if the member is deleted. 7526 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7527 HasConstParam); 7528 if ((getLangOpts().CPlusPlus20 || 7529 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7530 : isa<CXXConstructorDecl>(MD))) && 7531 MD->isConstexpr() && !Constexpr && 7532 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7533 Diag(MD->getBeginLoc(), MD->isConsteval() 7534 ? diag::err_incorrect_defaulted_consteval 7535 : diag::err_incorrect_defaulted_constexpr) 7536 << CSM; 7537 // FIXME: Explain why the special member can't be constexpr. 7538 HadError = true; 7539 } 7540 7541 if (First) { 7542 // C++2a [dcl.fct.def.default]p3: 7543 // If a function is explicitly defaulted on its first declaration, it is 7544 // implicitly considered to be constexpr if the implicit declaration 7545 // would be. 7546 MD->setConstexprKind(Constexpr ? (MD->isConsteval() 7547 ? ConstexprSpecKind::Consteval 7548 : ConstexprSpecKind::Constexpr) 7549 : ConstexprSpecKind::Unspecified); 7550 7551 if (!Type->hasExceptionSpec()) { 7552 // C++2a [except.spec]p3: 7553 // If a declaration of a function does not have a noexcept-specifier 7554 // [and] is defaulted on its first declaration, [...] the exception 7555 // specification is as specified below 7556 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7557 EPI.ExceptionSpec.Type = EST_Unevaluated; 7558 EPI.ExceptionSpec.SourceDecl = MD; 7559 MD->setType(Context.getFunctionType(ReturnType, 7560 llvm::makeArrayRef(&ArgType, 7561 ExpectedParams), 7562 EPI)); 7563 } 7564 } 7565 7566 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7567 if (First) { 7568 SetDeclDeleted(MD, MD->getLocation()); 7569 if (!inTemplateInstantiation() && !HadError) { 7570 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7571 if (ShouldDeleteForTypeMismatch) { 7572 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7573 } else { 7574 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7575 } 7576 } 7577 if (ShouldDeleteForTypeMismatch && !HadError) { 7578 Diag(MD->getLocation(), 7579 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7580 } 7581 } else { 7582 // C++11 [dcl.fct.def.default]p4: 7583 // [For a] user-provided explicitly-defaulted function [...] if such a 7584 // function is implicitly defined as deleted, the program is ill-formed. 7585 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7586 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 7587 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7588 HadError = true; 7589 } 7590 } 7591 7592 return HadError; 7593 } 7594 7595 namespace { 7596 /// Helper class for building and checking a defaulted comparison. 7597 /// 7598 /// Defaulted functions are built in two phases: 7599 /// 7600 /// * First, the set of operations that the function will perform are 7601 /// identified, and some of them are checked. If any of the checked 7602 /// operations is invalid in certain ways, the comparison function is 7603 /// defined as deleted and no body is built. 7604 /// * Then, if the function is not defined as deleted, the body is built. 7605 /// 7606 /// This is accomplished by performing two visitation steps over the eventual 7607 /// body of the function. 7608 template<typename Derived, typename ResultList, typename Result, 7609 typename Subobject> 7610 class DefaultedComparisonVisitor { 7611 public: 7612 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7613 7614 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7615 DefaultedComparisonKind DCK) 7616 : S(S), RD(RD), FD(FD), DCK(DCK) { 7617 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7618 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7619 // UnresolvedSet to avoid this copy. 7620 Fns.assign(Info->getUnqualifiedLookups().begin(), 7621 Info->getUnqualifiedLookups().end()); 7622 } 7623 } 7624 7625 ResultList visit() { 7626 // The type of an lvalue naming a parameter of this function. 7627 QualType ParamLvalType = 7628 FD->getParamDecl(0)->getType().getNonReferenceType(); 7629 7630 ResultList Results; 7631 7632 switch (DCK) { 7633 case DefaultedComparisonKind::None: 7634 llvm_unreachable("not a defaulted comparison"); 7635 7636 case DefaultedComparisonKind::Equal: 7637 case DefaultedComparisonKind::ThreeWay: 7638 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7639 return Results; 7640 7641 case DefaultedComparisonKind::NotEqual: 7642 case DefaultedComparisonKind::Relational: 7643 Results.add(getDerived().visitExpandedSubobject( 7644 ParamLvalType, getDerived().getCompleteObject())); 7645 return Results; 7646 } 7647 llvm_unreachable(""); 7648 } 7649 7650 protected: 7651 Derived &getDerived() { return static_cast<Derived&>(*this); } 7652 7653 /// Visit the expanded list of subobjects of the given type, as specified in 7654 /// C++2a [class.compare.default]. 7655 /// 7656 /// \return \c true if the ResultList object said we're done, \c false if not. 7657 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7658 Qualifiers Quals) { 7659 // C++2a [class.compare.default]p4: 7660 // The direct base class subobjects of C 7661 for (CXXBaseSpecifier &Base : Record->bases()) 7662 if (Results.add(getDerived().visitSubobject( 7663 S.Context.getQualifiedType(Base.getType(), Quals), 7664 getDerived().getBase(&Base)))) 7665 return true; 7666 7667 // followed by the non-static data members of C 7668 for (FieldDecl *Field : Record->fields()) { 7669 // Recursively expand anonymous structs. 7670 if (Field->isAnonymousStructOrUnion()) { 7671 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7672 Quals)) 7673 return true; 7674 continue; 7675 } 7676 7677 // Figure out the type of an lvalue denoting this field. 7678 Qualifiers FieldQuals = Quals; 7679 if (Field->isMutable()) 7680 FieldQuals.removeConst(); 7681 QualType FieldType = 7682 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7683 7684 if (Results.add(getDerived().visitSubobject( 7685 FieldType, getDerived().getField(Field)))) 7686 return true; 7687 } 7688 7689 // form a list of subobjects. 7690 return false; 7691 } 7692 7693 Result visitSubobject(QualType Type, Subobject Subobj) { 7694 // In that list, any subobject of array type is recursively expanded 7695 const ArrayType *AT = S.Context.getAsArrayType(Type); 7696 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7697 return getDerived().visitSubobjectArray(CAT->getElementType(), 7698 CAT->getSize(), Subobj); 7699 return getDerived().visitExpandedSubobject(Type, Subobj); 7700 } 7701 7702 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7703 Subobject Subobj) { 7704 return getDerived().visitSubobject(Type, Subobj); 7705 } 7706 7707 protected: 7708 Sema &S; 7709 CXXRecordDecl *RD; 7710 FunctionDecl *FD; 7711 DefaultedComparisonKind DCK; 7712 UnresolvedSet<16> Fns; 7713 }; 7714 7715 /// Information about a defaulted comparison, as determined by 7716 /// DefaultedComparisonAnalyzer. 7717 struct DefaultedComparisonInfo { 7718 bool Deleted = false; 7719 bool Constexpr = true; 7720 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7721 7722 static DefaultedComparisonInfo deleted() { 7723 DefaultedComparisonInfo Deleted; 7724 Deleted.Deleted = true; 7725 return Deleted; 7726 } 7727 7728 bool add(const DefaultedComparisonInfo &R) { 7729 Deleted |= R.Deleted; 7730 Constexpr &= R.Constexpr; 7731 Category = commonComparisonType(Category, R.Category); 7732 return Deleted; 7733 } 7734 }; 7735 7736 /// An element in the expanded list of subobjects of a defaulted comparison, as 7737 /// specified in C++2a [class.compare.default]p4. 7738 struct DefaultedComparisonSubobject { 7739 enum { CompleteObject, Member, Base } Kind; 7740 NamedDecl *Decl; 7741 SourceLocation Loc; 7742 }; 7743 7744 /// A visitor over the notional body of a defaulted comparison that determines 7745 /// whether that body would be deleted or constexpr. 7746 class DefaultedComparisonAnalyzer 7747 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7748 DefaultedComparisonInfo, 7749 DefaultedComparisonInfo, 7750 DefaultedComparisonSubobject> { 7751 public: 7752 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7753 7754 private: 7755 DiagnosticKind Diagnose; 7756 7757 public: 7758 using Base = DefaultedComparisonVisitor; 7759 using Result = DefaultedComparisonInfo; 7760 using Subobject = DefaultedComparisonSubobject; 7761 7762 friend Base; 7763 7764 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7765 DefaultedComparisonKind DCK, 7766 DiagnosticKind Diagnose = NoDiagnostics) 7767 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7768 7769 Result visit() { 7770 if ((DCK == DefaultedComparisonKind::Equal || 7771 DCK == DefaultedComparisonKind::ThreeWay) && 7772 RD->hasVariantMembers()) { 7773 // C++2a [class.compare.default]p2 [P2002R0]: 7774 // A defaulted comparison operator function for class C is defined as 7775 // deleted if [...] C has variant members. 7776 if (Diagnose == ExplainDeleted) { 7777 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7778 << FD << RD->isUnion() << RD; 7779 } 7780 return Result::deleted(); 7781 } 7782 7783 return Base::visit(); 7784 } 7785 7786 private: 7787 Subobject getCompleteObject() { 7788 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()}; 7789 } 7790 7791 Subobject getBase(CXXBaseSpecifier *Base) { 7792 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7793 Base->getBaseTypeLoc()}; 7794 } 7795 7796 Subobject getField(FieldDecl *Field) { 7797 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7798 } 7799 7800 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7801 // C++2a [class.compare.default]p2 [P2002R0]: 7802 // A defaulted <=> or == operator function for class C is defined as 7803 // deleted if any non-static data member of C is of reference type 7804 if (Type->isReferenceType()) { 7805 if (Diagnose == ExplainDeleted) { 7806 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7807 << FD << RD; 7808 } 7809 return Result::deleted(); 7810 } 7811 7812 // [...] Let xi be an lvalue denoting the ith element [...] 7813 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7814 Expr *Args[] = {&Xi, &Xi}; 7815 7816 // All operators start by trying to apply that same operator recursively. 7817 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7818 assert(OO != OO_None && "not an overloaded operator!"); 7819 return visitBinaryOperator(OO, Args, Subobj); 7820 } 7821 7822 Result 7823 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7824 Subobject Subobj, 7825 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7826 // Note that there is no need to consider rewritten candidates here if 7827 // we've already found there is no viable 'operator<=>' candidate (and are 7828 // considering synthesizing a '<=>' from '==' and '<'). 7829 OverloadCandidateSet CandidateSet( 7830 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7831 OverloadCandidateSet::OperatorRewriteInfo( 7832 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7833 7834 /// C++2a [class.compare.default]p1 [P2002R0]: 7835 /// [...] the defaulted function itself is never a candidate for overload 7836 /// resolution [...] 7837 CandidateSet.exclude(FD); 7838 7839 if (Args[0]->getType()->isOverloadableType()) 7840 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7841 else 7842 // FIXME: We determine whether this is a valid expression by checking to 7843 // see if there's a viable builtin operator candidate for it. That isn't 7844 // really what the rules ask us to do, but should give the right results. 7845 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet); 7846 7847 Result R; 7848 7849 OverloadCandidateSet::iterator Best; 7850 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7851 case OR_Success: { 7852 // C++2a [class.compare.secondary]p2 [P2002R0]: 7853 // The operator function [...] is defined as deleted if [...] the 7854 // candidate selected by overload resolution is not a rewritten 7855 // candidate. 7856 if ((DCK == DefaultedComparisonKind::NotEqual || 7857 DCK == DefaultedComparisonKind::Relational) && 7858 !Best->RewriteKind) { 7859 if (Diagnose == ExplainDeleted) { 7860 if (Best->Function) { 7861 S.Diag(Best->Function->getLocation(), 7862 diag::note_defaulted_comparison_not_rewritten_callee) 7863 << FD; 7864 } else { 7865 assert(Best->Conversions.size() == 2 && 7866 Best->Conversions[0].isUserDefined() && 7867 "non-user-defined conversion from class to built-in " 7868 "comparison"); 7869 S.Diag(Best->Conversions[0] 7870 .UserDefined.FoundConversionFunction.getDecl() 7871 ->getLocation(), 7872 diag::note_defaulted_comparison_not_rewritten_conversion) 7873 << FD; 7874 } 7875 } 7876 return Result::deleted(); 7877 } 7878 7879 // Throughout C++2a [class.compare]: if overload resolution does not 7880 // result in a usable function, the candidate function is defined as 7881 // deleted. This requires that we selected an accessible function. 7882 // 7883 // Note that this only considers the access of the function when named 7884 // within the type of the subobject, and not the access path for any 7885 // derived-to-base conversion. 7886 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7887 if (ArgClass && Best->FoundDecl.getDecl() && 7888 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7889 QualType ObjectType = Subobj.Kind == Subobject::Member 7890 ? Args[0]->getType() 7891 : S.Context.getRecordType(RD); 7892 if (!S.isMemberAccessibleForDeletion( 7893 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7894 Diagnose == ExplainDeleted 7895 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7896 << FD << Subobj.Kind << Subobj.Decl 7897 : S.PDiag())) 7898 return Result::deleted(); 7899 } 7900 7901 bool NeedsDeducing = 7902 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType(); 7903 7904 if (FunctionDecl *BestFD = Best->Function) { 7905 // C++2a [class.compare.default]p3 [P2002R0]: 7906 // A defaulted comparison function is constexpr-compatible if 7907 // [...] no overlod resolution performed [...] results in a 7908 // non-constexpr function. 7909 assert(!BestFD->isDeleted() && "wrong overload resolution result"); 7910 // If it's not constexpr, explain why not. 7911 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 7912 if (Subobj.Kind != Subobject::CompleteObject) 7913 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7914 << Subobj.Kind << Subobj.Decl; 7915 S.Diag(BestFD->getLocation(), 7916 diag::note_defaulted_comparison_not_constexpr_here); 7917 // Bail out after explaining; we don't want any more notes. 7918 return Result::deleted(); 7919 } 7920 R.Constexpr &= BestFD->isConstexpr(); 7921 7922 if (NeedsDeducing) { 7923 // If any callee has an undeduced return type, deduce it now. 7924 // FIXME: It's not clear how a failure here should be handled. For 7925 // now, we produce an eager diagnostic, because that is forward 7926 // compatible with most (all?) other reasonable options. 7927 if (BestFD->getReturnType()->isUndeducedType() && 7928 S.DeduceReturnType(BestFD, FD->getLocation(), 7929 /*Diagnose=*/false)) { 7930 // Don't produce a duplicate error when asked to explain why the 7931 // comparison is deleted: we diagnosed that when initially checking 7932 // the defaulted operator. 7933 if (Diagnose == NoDiagnostics) { 7934 S.Diag( 7935 FD->getLocation(), 7936 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) 7937 << Subobj.Kind << Subobj.Decl; 7938 S.Diag( 7939 Subobj.Loc, 7940 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) 7941 << Subobj.Kind << Subobj.Decl; 7942 S.Diag(BestFD->getLocation(), 7943 diag::note_defaulted_comparison_cannot_deduce_callee) 7944 << Subobj.Kind << Subobj.Decl; 7945 } 7946 return Result::deleted(); 7947 } 7948 auto *Info = S.Context.CompCategories.lookupInfoForType( 7949 BestFD->getCallResultType()); 7950 if (!Info) { 7951 if (Diagnose == ExplainDeleted) { 7952 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 7953 << Subobj.Kind << Subobj.Decl 7954 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 7955 S.Diag(BestFD->getLocation(), 7956 diag::note_defaulted_comparison_cannot_deduce_callee) 7957 << Subobj.Kind << Subobj.Decl; 7958 } 7959 return Result::deleted(); 7960 } 7961 R.Category = Info->Kind; 7962 } 7963 } else { 7964 QualType T = Best->BuiltinParamTypes[0]; 7965 assert(T == Best->BuiltinParamTypes[1] && 7966 "builtin comparison for different types?"); 7967 assert(Best->BuiltinParamTypes[2].isNull() && 7968 "invalid builtin comparison"); 7969 7970 if (NeedsDeducing) { 7971 Optional<ComparisonCategoryType> Cat = 7972 getComparisonCategoryForBuiltinCmp(T); 7973 assert(Cat && "no category for builtin comparison?"); 7974 R.Category = *Cat; 7975 } 7976 } 7977 7978 // Note that we might be rewriting to a different operator. That call is 7979 // not considered until we come to actually build the comparison function. 7980 break; 7981 } 7982 7983 case OR_Ambiguous: 7984 if (Diagnose == ExplainDeleted) { 7985 unsigned Kind = 0; 7986 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 7987 Kind = OO == OO_EqualEqual ? 1 : 2; 7988 CandidateSet.NoteCandidates( 7989 PartialDiagnosticAt( 7990 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 7991 << FD << Kind << Subobj.Kind << Subobj.Decl), 7992 S, OCD_AmbiguousCandidates, Args); 7993 } 7994 R = Result::deleted(); 7995 break; 7996 7997 case OR_Deleted: 7998 if (Diagnose == ExplainDeleted) { 7999 if ((DCK == DefaultedComparisonKind::NotEqual || 8000 DCK == DefaultedComparisonKind::Relational) && 8001 !Best->RewriteKind) { 8002 S.Diag(Best->Function->getLocation(), 8003 diag::note_defaulted_comparison_not_rewritten_callee) 8004 << FD; 8005 } else { 8006 S.Diag(Subobj.Loc, 8007 diag::note_defaulted_comparison_calls_deleted) 8008 << FD << Subobj.Kind << Subobj.Decl; 8009 S.NoteDeletedFunction(Best->Function); 8010 } 8011 } 8012 R = Result::deleted(); 8013 break; 8014 8015 case OR_No_Viable_Function: 8016 // If there's no usable candidate, we're done unless we can rewrite a 8017 // '<=>' in terms of '==' and '<'. 8018 if (OO == OO_Spaceship && 8019 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 8020 // For any kind of comparison category return type, we need a usable 8021 // '==' and a usable '<'. 8022 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 8023 &CandidateSet))) 8024 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 8025 break; 8026 } 8027 8028 if (Diagnose == ExplainDeleted) { 8029 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 8030 << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl; 8031 8032 // For a three-way comparison, list both the candidates for the 8033 // original operator and the candidates for the synthesized operator. 8034 if (SpaceshipCandidates) { 8035 SpaceshipCandidates->NoteCandidates( 8036 S, Args, 8037 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 8038 Args, FD->getLocation())); 8039 S.Diag(Subobj.Loc, 8040 diag::note_defaulted_comparison_no_viable_function_synthesized) 8041 << (OO == OO_EqualEqual ? 0 : 1); 8042 } 8043 8044 CandidateSet.NoteCandidates( 8045 S, Args, 8046 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 8047 FD->getLocation())); 8048 } 8049 R = Result::deleted(); 8050 break; 8051 } 8052 8053 return R; 8054 } 8055 }; 8056 8057 /// A list of statements. 8058 struct StmtListResult { 8059 bool IsInvalid = false; 8060 llvm::SmallVector<Stmt*, 16> Stmts; 8061 8062 bool add(const StmtResult &S) { 8063 IsInvalid |= S.isInvalid(); 8064 if (IsInvalid) 8065 return true; 8066 Stmts.push_back(S.get()); 8067 return false; 8068 } 8069 }; 8070 8071 /// A visitor over the notional body of a defaulted comparison that synthesizes 8072 /// the actual body. 8073 class DefaultedComparisonSynthesizer 8074 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 8075 StmtListResult, StmtResult, 8076 std::pair<ExprResult, ExprResult>> { 8077 SourceLocation Loc; 8078 unsigned ArrayDepth = 0; 8079 8080 public: 8081 using Base = DefaultedComparisonVisitor; 8082 using ExprPair = std::pair<ExprResult, ExprResult>; 8083 8084 friend Base; 8085 8086 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 8087 DefaultedComparisonKind DCK, 8088 SourceLocation BodyLoc) 8089 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 8090 8091 /// Build a suitable function body for this defaulted comparison operator. 8092 StmtResult build() { 8093 Sema::CompoundScopeRAII CompoundScope(S); 8094 8095 StmtListResult Stmts = visit(); 8096 if (Stmts.IsInvalid) 8097 return StmtError(); 8098 8099 ExprResult RetVal; 8100 switch (DCK) { 8101 case DefaultedComparisonKind::None: 8102 llvm_unreachable("not a defaulted comparison"); 8103 8104 case DefaultedComparisonKind::Equal: { 8105 // C++2a [class.eq]p3: 8106 // [...] compar[e] the corresponding elements [...] until the first 8107 // index i where xi == yi yields [...] false. If no such index exists, 8108 // V is true. Otherwise, V is false. 8109 // 8110 // Join the comparisons with '&&'s and return the result. Use a right 8111 // fold (traversing the conditions right-to-left), because that 8112 // short-circuits more naturally. 8113 auto OldStmts = std::move(Stmts.Stmts); 8114 Stmts.Stmts.clear(); 8115 ExprResult CmpSoFar; 8116 // Finish a particular comparison chain. 8117 auto FinishCmp = [&] { 8118 if (Expr *Prior = CmpSoFar.get()) { 8119 // Convert the last expression to 'return ...;' 8120 if (RetVal.isUnset() && Stmts.Stmts.empty()) 8121 RetVal = CmpSoFar; 8122 // Convert any prior comparison to 'if (!(...)) return false;' 8123 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 8124 return true; 8125 CmpSoFar = ExprResult(); 8126 } 8127 return false; 8128 }; 8129 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 8130 Expr *E = dyn_cast<Expr>(EAsStmt); 8131 if (!E) { 8132 // Found an array comparison. 8133 if (FinishCmp() || Stmts.add(EAsStmt)) 8134 return StmtError(); 8135 continue; 8136 } 8137 8138 if (CmpSoFar.isUnset()) { 8139 CmpSoFar = E; 8140 continue; 8141 } 8142 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 8143 if (CmpSoFar.isInvalid()) 8144 return StmtError(); 8145 } 8146 if (FinishCmp()) 8147 return StmtError(); 8148 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 8149 // If no such index exists, V is true. 8150 if (RetVal.isUnset()) 8151 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 8152 break; 8153 } 8154 8155 case DefaultedComparisonKind::ThreeWay: { 8156 // Per C++2a [class.spaceship]p3, as a fallback add: 8157 // return static_cast<R>(std::strong_ordering::equal); 8158 QualType StrongOrdering = S.CheckComparisonCategoryType( 8159 ComparisonCategoryType::StrongOrdering, Loc, 8160 Sema::ComparisonCategoryUsage::DefaultedOperator); 8161 if (StrongOrdering.isNull()) 8162 return StmtError(); 8163 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 8164 .getValueInfo(ComparisonCategoryResult::Equal) 8165 ->VD; 8166 RetVal = getDecl(EqualVD); 8167 if (RetVal.isInvalid()) 8168 return StmtError(); 8169 RetVal = buildStaticCastToR(RetVal.get()); 8170 break; 8171 } 8172 8173 case DefaultedComparisonKind::NotEqual: 8174 case DefaultedComparisonKind::Relational: 8175 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 8176 break; 8177 } 8178 8179 // Build the final return statement. 8180 if (RetVal.isInvalid()) 8181 return StmtError(); 8182 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 8183 if (ReturnStmt.isInvalid()) 8184 return StmtError(); 8185 Stmts.Stmts.push_back(ReturnStmt.get()); 8186 8187 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 8188 } 8189 8190 private: 8191 ExprResult getDecl(ValueDecl *VD) { 8192 return S.BuildDeclarationNameExpr( 8193 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 8194 } 8195 8196 ExprResult getParam(unsigned I) { 8197 ParmVarDecl *PD = FD->getParamDecl(I); 8198 return getDecl(PD); 8199 } 8200 8201 ExprPair getCompleteObject() { 8202 unsigned Param = 0; 8203 ExprResult LHS; 8204 if (isa<CXXMethodDecl>(FD)) { 8205 // LHS is '*this'. 8206 LHS = S.ActOnCXXThis(Loc); 8207 if (!LHS.isInvalid()) 8208 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 8209 } else { 8210 LHS = getParam(Param++); 8211 } 8212 ExprResult RHS = getParam(Param++); 8213 assert(Param == FD->getNumParams()); 8214 return {LHS, RHS}; 8215 } 8216 8217 ExprPair getBase(CXXBaseSpecifier *Base) { 8218 ExprPair Obj = getCompleteObject(); 8219 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8220 return {ExprError(), ExprError()}; 8221 CXXCastPath Path = {Base}; 8222 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 8223 CK_DerivedToBase, VK_LValue, &Path), 8224 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 8225 CK_DerivedToBase, VK_LValue, &Path)}; 8226 } 8227 8228 ExprPair getField(FieldDecl *Field) { 8229 ExprPair Obj = getCompleteObject(); 8230 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8231 return {ExprError(), ExprError()}; 8232 8233 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 8234 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 8235 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 8236 CXXScopeSpec(), Field, Found, NameInfo), 8237 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 8238 CXXScopeSpec(), Field, Found, NameInfo)}; 8239 } 8240 8241 // FIXME: When expanding a subobject, register a note in the code synthesis 8242 // stack to say which subobject we're comparing. 8243 8244 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 8245 if (Cond.isInvalid()) 8246 return StmtError(); 8247 8248 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 8249 if (NotCond.isInvalid()) 8250 return StmtError(); 8251 8252 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 8253 assert(!False.isInvalid() && "should never fail"); 8254 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 8255 if (ReturnFalse.isInvalid()) 8256 return StmtError(); 8257 8258 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr, 8259 S.ActOnCondition(nullptr, Loc, NotCond.get(), 8260 Sema::ConditionKind::Boolean), 8261 Loc, ReturnFalse.get(), SourceLocation(), nullptr); 8262 } 8263 8264 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 8265 ExprPair Subobj) { 8266 QualType SizeType = S.Context.getSizeType(); 8267 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 8268 8269 // Build 'size_t i$n = 0'. 8270 IdentifierInfo *IterationVarName = nullptr; 8271 { 8272 SmallString<8> Str; 8273 llvm::raw_svector_ostream OS(Str); 8274 OS << "i" << ArrayDepth; 8275 IterationVarName = &S.Context.Idents.get(OS.str()); 8276 } 8277 VarDecl *IterationVar = VarDecl::Create( 8278 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 8279 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 8280 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8281 IterationVar->setInit( 8282 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8283 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 8284 8285 auto IterRef = [&] { 8286 ExprResult Ref = S.BuildDeclarationNameExpr( 8287 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 8288 IterationVar); 8289 assert(!Ref.isInvalid() && "can't reference our own variable?"); 8290 return Ref.get(); 8291 }; 8292 8293 // Build 'i$n != Size'. 8294 ExprResult Cond = S.CreateBuiltinBinOp( 8295 Loc, BO_NE, IterRef(), 8296 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 8297 assert(!Cond.isInvalid() && "should never fail"); 8298 8299 // Build '++i$n'. 8300 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 8301 assert(!Inc.isInvalid() && "should never fail"); 8302 8303 // Build 'a[i$n]' and 'b[i$n]'. 8304 auto Index = [&](ExprResult E) { 8305 if (E.isInvalid()) 8306 return ExprError(); 8307 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 8308 }; 8309 Subobj.first = Index(Subobj.first); 8310 Subobj.second = Index(Subobj.second); 8311 8312 // Compare the array elements. 8313 ++ArrayDepth; 8314 StmtResult Substmt = visitSubobject(Type, Subobj); 8315 --ArrayDepth; 8316 8317 if (Substmt.isInvalid()) 8318 return StmtError(); 8319 8320 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 8321 // For outer levels or for an 'operator<=>' we already have a suitable 8322 // statement that returns as necessary. 8323 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 8324 assert(DCK == DefaultedComparisonKind::Equal && 8325 "should have non-expression statement"); 8326 Substmt = buildIfNotCondReturnFalse(ElemCmp); 8327 if (Substmt.isInvalid()) 8328 return StmtError(); 8329 } 8330 8331 // Build 'for (...) ...' 8332 return S.ActOnForStmt(Loc, Loc, Init, 8333 S.ActOnCondition(nullptr, Loc, Cond.get(), 8334 Sema::ConditionKind::Boolean), 8335 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 8336 Substmt.get()); 8337 } 8338 8339 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 8340 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8341 return StmtError(); 8342 8343 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 8344 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); 8345 ExprResult Op; 8346 if (Type->isOverloadableType()) 8347 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(), 8348 Obj.second.get(), /*PerformADL=*/true, 8349 /*AllowRewrittenCandidates=*/true, FD); 8350 else 8351 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get()); 8352 if (Op.isInvalid()) 8353 return StmtError(); 8354 8355 switch (DCK) { 8356 case DefaultedComparisonKind::None: 8357 llvm_unreachable("not a defaulted comparison"); 8358 8359 case DefaultedComparisonKind::Equal: 8360 // Per C++2a [class.eq]p2, each comparison is individually contextually 8361 // converted to bool. 8362 Op = S.PerformContextuallyConvertToBool(Op.get()); 8363 if (Op.isInvalid()) 8364 return StmtError(); 8365 return Op.get(); 8366 8367 case DefaultedComparisonKind::ThreeWay: { 8368 // Per C++2a [class.spaceship]p3, form: 8369 // if (R cmp = static_cast<R>(op); cmp != 0) 8370 // return cmp; 8371 QualType R = FD->getReturnType(); 8372 Op = buildStaticCastToR(Op.get()); 8373 if (Op.isInvalid()) 8374 return StmtError(); 8375 8376 // R cmp = ...; 8377 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 8378 VarDecl *VD = 8379 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 8380 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 8381 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 8382 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 8383 8384 // cmp != 0 8385 ExprResult VDRef = getDecl(VD); 8386 if (VDRef.isInvalid()) 8387 return StmtError(); 8388 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 8389 Expr *Zero = 8390 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 8391 ExprResult Comp; 8392 if (VDRef.get()->getType()->isOverloadableType()) 8393 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true, 8394 true, FD); 8395 else 8396 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero); 8397 if (Comp.isInvalid()) 8398 return StmtError(); 8399 Sema::ConditionResult Cond = S.ActOnCondition( 8400 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 8401 if (Cond.isInvalid()) 8402 return StmtError(); 8403 8404 // return cmp; 8405 VDRef = getDecl(VD); 8406 if (VDRef.isInvalid()) 8407 return StmtError(); 8408 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 8409 if (ReturnStmt.isInvalid()) 8410 return StmtError(); 8411 8412 // if (...) 8413 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond, 8414 Loc, ReturnStmt.get(), 8415 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr); 8416 } 8417 8418 case DefaultedComparisonKind::NotEqual: 8419 case DefaultedComparisonKind::Relational: 8420 // C++2a [class.compare.secondary]p2: 8421 // Otherwise, the operator function yields x @ y. 8422 return Op.get(); 8423 } 8424 llvm_unreachable(""); 8425 } 8426 8427 /// Build "static_cast<R>(E)". 8428 ExprResult buildStaticCastToR(Expr *E) { 8429 QualType R = FD->getReturnType(); 8430 assert(!R->isUndeducedType() && "type should have been deduced already"); 8431 8432 // Don't bother forming a no-op cast in the common case. 8433 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R)) 8434 return E; 8435 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 8436 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 8437 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 8438 } 8439 }; 8440 } 8441 8442 /// Perform the unqualified lookups that might be needed to form a defaulted 8443 /// comparison function for the given operator. 8444 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 8445 UnresolvedSetImpl &Operators, 8446 OverloadedOperatorKind Op) { 8447 auto Lookup = [&](OverloadedOperatorKind OO) { 8448 Self.LookupOverloadedOperatorName(OO, S, Operators); 8449 }; 8450 8451 // Every defaulted operator looks up itself. 8452 Lookup(Op); 8453 // ... and the rewritten form of itself, if any. 8454 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 8455 Lookup(ExtraOp); 8456 8457 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 8458 // synthesize a three-way comparison from '<' and '=='. In a dependent 8459 // context, we also need to look up '==' in case we implicitly declare a 8460 // defaulted 'operator=='. 8461 if (Op == OO_Spaceship) { 8462 Lookup(OO_ExclaimEqual); 8463 Lookup(OO_Less); 8464 Lookup(OO_EqualEqual); 8465 } 8466 } 8467 8468 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 8469 DefaultedComparisonKind DCK) { 8470 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison"); 8471 8472 // Perform any unqualified lookups we're going to need to default this 8473 // function. 8474 if (S) { 8475 UnresolvedSet<32> Operators; 8476 lookupOperatorsForDefaultedComparison(*this, S, Operators, 8477 FD->getOverloadedOperator()); 8478 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 8479 Context, Operators.pairs())); 8480 } 8481 8482 // C++2a [class.compare.default]p1: 8483 // A defaulted comparison operator function for some class C shall be a 8484 // non-template function declared in the member-specification of C that is 8485 // -- a non-static const member of C having one parameter of type 8486 // const C&, or 8487 // -- a friend of C having two parameters of type const C& or two 8488 // parameters of type C. 8489 8490 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 8491 bool IsMethod = isa<CXXMethodDecl>(FD); 8492 if (IsMethod) { 8493 auto *MD = cast<CXXMethodDecl>(FD); 8494 assert(!MD->isStatic() && "comparison function cannot be a static member"); 8495 8496 // If we're out-of-class, this is the class we're comparing. 8497 if (!RD) 8498 RD = MD->getParent(); 8499 8500 if (!MD->isConst()) { 8501 SourceLocation InsertLoc; 8502 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 8503 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 8504 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8505 // corresponding defaulted 'operator<=>' already. 8506 if (!MD->isImplicit()) { 8507 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 8508 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 8509 } 8510 8511 // Add the 'const' to the type to recover. 8512 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 8513 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8514 EPI.TypeQuals.addConst(); 8515 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8516 FPT->getParamTypes(), EPI)); 8517 } 8518 } 8519 8520 if (FD->getNumParams() != (IsMethod ? 1 : 2)) { 8521 // Let's not worry about using a variadic template pack here -- who would do 8522 // such a thing? 8523 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args) 8524 << int(IsMethod) << int(DCK); 8525 return true; 8526 } 8527 8528 const ParmVarDecl *KnownParm = nullptr; 8529 for (const ParmVarDecl *Param : FD->parameters()) { 8530 QualType ParmTy = Param->getType(); 8531 if (ParmTy->isDependentType()) 8532 continue; 8533 if (!KnownParm) { 8534 auto CTy = ParmTy; 8535 // Is it `T const &`? 8536 bool Ok = !IsMethod; 8537 QualType ExpectedTy; 8538 if (RD) 8539 ExpectedTy = Context.getRecordType(RD); 8540 if (auto *Ref = CTy->getAs<ReferenceType>()) { 8541 CTy = Ref->getPointeeType(); 8542 if (RD) 8543 ExpectedTy.addConst(); 8544 Ok = true; 8545 } 8546 8547 // Is T a class? 8548 if (!Ok) { 8549 } else if (RD) { 8550 if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy)) 8551 Ok = false; 8552 } else if (auto *CRD = CTy->getAsRecordDecl()) { 8553 RD = cast<CXXRecordDecl>(CRD); 8554 } else { 8555 Ok = false; 8556 } 8557 8558 if (Ok) { 8559 KnownParm = Param; 8560 } else { 8561 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8562 // corresponding defaulted 'operator<=>' already. 8563 if (!FD->isImplicit()) { 8564 if (RD) { 8565 QualType PlainTy = Context.getRecordType(RD); 8566 QualType RefTy = 8567 Context.getLValueReferenceType(PlainTy.withConst()); 8568 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 8569 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy 8570 << Param->getSourceRange(); 8571 } else { 8572 assert(!IsMethod && "should know expected type for method"); 8573 Diag(FD->getLocation(), 8574 diag::err_defaulted_comparison_param_unknown) 8575 << int(DCK) << ParmTy << Param->getSourceRange(); 8576 } 8577 } 8578 return true; 8579 } 8580 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) { 8581 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 8582 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange() 8583 << ParmTy << Param->getSourceRange(); 8584 return true; 8585 } 8586 } 8587 8588 assert(RD && "must have determined class"); 8589 if (IsMethod) { 8590 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 8591 // In-class, must be a friend decl. 8592 assert(FD->getFriendObjectKind() && "expected a friend declaration"); 8593 } else { 8594 // Out of class, require the defaulted comparison to be a friend (of a 8595 // complete type). 8596 if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD), 8597 diag::err_defaulted_comparison_not_friend, int(DCK), 8598 int(1))) 8599 return true; 8600 8601 if (llvm::find_if(RD->friends(), [&](const FriendDecl *F) { 8602 return FD->getCanonicalDecl() == 8603 F->getFriendDecl()->getCanonicalDecl(); 8604 }) == RD->friends().end()) { 8605 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend) 8606 << int(DCK) << int(0) << RD; 8607 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at); 8608 return true; 8609 } 8610 } 8611 8612 // C++2a [class.eq]p1, [class.rel]p1: 8613 // A [defaulted comparison other than <=>] shall have a declared return 8614 // type bool. 8615 if (DCK != DefaultedComparisonKind::ThreeWay && 8616 !FD->getDeclaredReturnType()->isDependentType() && 8617 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8618 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8619 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8620 << FD->getReturnTypeSourceRange(); 8621 return true; 8622 } 8623 // C++2a [class.spaceship]p2 [P2002R0]: 8624 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8625 // R shall not contain a placeholder type. 8626 if (DCK == DefaultedComparisonKind::ThreeWay && 8627 FD->getDeclaredReturnType()->getContainedDeducedType() && 8628 !Context.hasSameType(FD->getDeclaredReturnType(), 8629 Context.getAutoDeductType())) { 8630 Diag(FD->getLocation(), 8631 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8632 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8633 << FD->getReturnTypeSourceRange(); 8634 return true; 8635 } 8636 8637 // For a defaulted function in a dependent class, defer all remaining checks 8638 // until instantiation. 8639 if (RD->isDependentType()) 8640 return false; 8641 8642 // Determine whether the function should be defined as deleted. 8643 DefaultedComparisonInfo Info = 8644 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8645 8646 bool First = FD == FD->getCanonicalDecl(); 8647 8648 // If we want to delete the function, then do so; there's nothing else to 8649 // check in that case. 8650 if (Info.Deleted) { 8651 if (!First) { 8652 // C++11 [dcl.fct.def.default]p4: 8653 // [For a] user-provided explicitly-defaulted function [...] if such a 8654 // function is implicitly defined as deleted, the program is ill-formed. 8655 // 8656 // This is really just a consequence of the general rule that you can 8657 // only delete a function on its first declaration. 8658 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8659 << FD->isImplicit() << (int)DCK; 8660 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8661 DefaultedComparisonAnalyzer::ExplainDeleted) 8662 .visit(); 8663 return true; 8664 } 8665 8666 SetDeclDeleted(FD, FD->getLocation()); 8667 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8668 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8669 << (int)DCK; 8670 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8671 DefaultedComparisonAnalyzer::ExplainDeleted) 8672 .visit(); 8673 } 8674 return false; 8675 } 8676 8677 // C++2a [class.spaceship]p2: 8678 // The return type is deduced as the common comparison type of R0, R1, ... 8679 if (DCK == DefaultedComparisonKind::ThreeWay && 8680 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8681 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8682 if (RetLoc.isInvalid()) 8683 RetLoc = FD->getBeginLoc(); 8684 // FIXME: Should we really care whether we have the complete type and the 8685 // 'enumerator' constants here? A forward declaration seems sufficient. 8686 QualType Cat = CheckComparisonCategoryType( 8687 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8688 if (Cat.isNull()) 8689 return true; 8690 Context.adjustDeducedFunctionResultType( 8691 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8692 } 8693 8694 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8695 // An explicitly-defaulted function that is not defined as deleted may be 8696 // declared constexpr or consteval only if it is constexpr-compatible. 8697 // C++2a [class.compare.default]p3 [P2002R0]: 8698 // A defaulted comparison function is constexpr-compatible if it satisfies 8699 // the requirements for a constexpr function [...] 8700 // The only relevant requirements are that the parameter and return types are 8701 // literal types. The remaining conditions are checked by the analyzer. 8702 if (FD->isConstexpr()) { 8703 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8704 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8705 !Info.Constexpr) { 8706 Diag(FD->getBeginLoc(), 8707 diag::err_incorrect_defaulted_comparison_constexpr) 8708 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8709 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8710 DefaultedComparisonAnalyzer::ExplainConstexpr) 8711 .visit(); 8712 } 8713 } 8714 8715 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8716 // If a constexpr-compatible function is explicitly defaulted on its first 8717 // declaration, it is implicitly considered to be constexpr. 8718 // FIXME: Only applying this to the first declaration seems problematic, as 8719 // simple reorderings can affect the meaning of the program. 8720 if (First && !FD->isConstexpr() && Info.Constexpr) 8721 FD->setConstexprKind(ConstexprSpecKind::Constexpr); 8722 8723 // C++2a [except.spec]p3: 8724 // If a declaration of a function does not have a noexcept-specifier 8725 // [and] is defaulted on its first declaration, [...] the exception 8726 // specification is as specified below 8727 if (FD->getExceptionSpecType() == EST_None) { 8728 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8729 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8730 EPI.ExceptionSpec.Type = EST_Unevaluated; 8731 EPI.ExceptionSpec.SourceDecl = FD; 8732 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8733 FPT->getParamTypes(), EPI)); 8734 } 8735 8736 return false; 8737 } 8738 8739 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8740 FunctionDecl *Spaceship) { 8741 Sema::CodeSynthesisContext Ctx; 8742 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8743 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8744 Ctx.Entity = Spaceship; 8745 pushCodeSynthesisContext(Ctx); 8746 8747 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8748 EqualEqual->setImplicit(); 8749 8750 popCodeSynthesisContext(); 8751 } 8752 8753 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8754 DefaultedComparisonKind DCK) { 8755 assert(FD->isDefaulted() && !FD->isDeleted() && 8756 !FD->doesThisDeclarationHaveABody()); 8757 if (FD->willHaveBody() || FD->isInvalidDecl()) 8758 return; 8759 8760 SynthesizedFunctionScope Scope(*this, FD); 8761 8762 // Add a context note for diagnostics produced after this point. 8763 Scope.addContextNote(UseLoc); 8764 8765 { 8766 // Build and set up the function body. 8767 // The first parameter has type maybe-ref-to maybe-const T, use that to get 8768 // the type of the class being compared. 8769 auto PT = FD->getParamDecl(0)->getType(); 8770 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl(); 8771 SourceLocation BodyLoc = 8772 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8773 StmtResult Body = 8774 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8775 if (Body.isInvalid()) { 8776 FD->setInvalidDecl(); 8777 return; 8778 } 8779 FD->setBody(Body.get()); 8780 FD->markUsed(Context); 8781 } 8782 8783 // The exception specification is needed because we are defining the 8784 // function. Note that this will reuse the body we just built. 8785 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8786 8787 if (ASTMutationListener *L = getASTMutationListener()) 8788 L->CompletedImplicitDefinition(FD); 8789 } 8790 8791 static Sema::ImplicitExceptionSpecification 8792 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8793 FunctionDecl *FD, 8794 Sema::DefaultedComparisonKind DCK) { 8795 ComputingExceptionSpec CES(S, FD, Loc); 8796 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8797 8798 if (FD->isInvalidDecl()) 8799 return ExceptSpec; 8800 8801 // The common case is that we just defined the comparison function. In that 8802 // case, just look at whether the body can throw. 8803 if (FD->hasBody()) { 8804 ExceptSpec.CalledStmt(FD->getBody()); 8805 } else { 8806 // Otherwise, build a body so we can check it. This should ideally only 8807 // happen when we're not actually marking the function referenced. (This is 8808 // only really important for efficiency: we don't want to build and throw 8809 // away bodies for comparison functions more than we strictly need to.) 8810 8811 // Pretend to synthesize the function body in an unevaluated context. 8812 // Note that we can't actually just go ahead and define the function here: 8813 // we are not permitted to mark its callees as referenced. 8814 Sema::SynthesizedFunctionScope Scope(S, FD); 8815 EnterExpressionEvaluationContext Context( 8816 S, Sema::ExpressionEvaluationContext::Unevaluated); 8817 8818 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8819 SourceLocation BodyLoc = 8820 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8821 StmtResult Body = 8822 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8823 if (!Body.isInvalid()) 8824 ExceptSpec.CalledStmt(Body.get()); 8825 8826 // FIXME: Can we hold onto this body and just transform it to potentially 8827 // evaluated when we're asked to define the function rather than rebuilding 8828 // it? Either that, or we should only build the bits of the body that we 8829 // need (the expressions, not the statements). 8830 } 8831 8832 return ExceptSpec; 8833 } 8834 8835 void Sema::CheckDelayedMemberExceptionSpecs() { 8836 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8837 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8838 8839 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8840 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8841 8842 // Perform any deferred checking of exception specifications for virtual 8843 // destructors. 8844 for (auto &Check : Overriding) 8845 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8846 8847 // Perform any deferred checking of exception specifications for befriended 8848 // special members. 8849 for (auto &Check : Equivalent) 8850 CheckEquivalentExceptionSpec(Check.second, Check.first); 8851 } 8852 8853 namespace { 8854 /// CRTP base class for visiting operations performed by a special member 8855 /// function (or inherited constructor). 8856 template<typename Derived> 8857 struct SpecialMemberVisitor { 8858 Sema &S; 8859 CXXMethodDecl *MD; 8860 Sema::CXXSpecialMember CSM; 8861 Sema::InheritedConstructorInfo *ICI; 8862 8863 // Properties of the special member, computed for convenience. 8864 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8865 8866 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8867 Sema::InheritedConstructorInfo *ICI) 8868 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8869 switch (CSM) { 8870 case Sema::CXXDefaultConstructor: 8871 case Sema::CXXCopyConstructor: 8872 case Sema::CXXMoveConstructor: 8873 IsConstructor = true; 8874 break; 8875 case Sema::CXXCopyAssignment: 8876 case Sema::CXXMoveAssignment: 8877 IsAssignment = true; 8878 break; 8879 case Sema::CXXDestructor: 8880 break; 8881 case Sema::CXXInvalid: 8882 llvm_unreachable("invalid special member kind"); 8883 } 8884 8885 if (MD->getNumParams()) { 8886 if (const ReferenceType *RT = 8887 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8888 ConstArg = RT->getPointeeType().isConstQualified(); 8889 } 8890 } 8891 8892 Derived &getDerived() { return static_cast<Derived&>(*this); } 8893 8894 /// Is this a "move" special member? 8895 bool isMove() const { 8896 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8897 } 8898 8899 /// Look up the corresponding special member in the given class. 8900 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8901 unsigned Quals, bool IsMutable) { 8902 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8903 ConstArg && !IsMutable); 8904 } 8905 8906 /// Look up the constructor for the specified base class to see if it's 8907 /// overridden due to this being an inherited constructor. 8908 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8909 if (!ICI) 8910 return {}; 8911 assert(CSM == Sema::CXXDefaultConstructor); 8912 auto *BaseCtor = 8913 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8914 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8915 return MD; 8916 return {}; 8917 } 8918 8919 /// A base or member subobject. 8920 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8921 8922 /// Get the location to use for a subobject in diagnostics. 8923 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8924 // FIXME: For an indirect virtual base, the direct base leading to 8925 // the indirect virtual base would be a more useful choice. 8926 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8927 return B->getBaseTypeLoc(); 8928 else 8929 return Subobj.get<FieldDecl*>()->getLocation(); 8930 } 8931 8932 enum BasesToVisit { 8933 /// Visit all non-virtual (direct) bases. 8934 VisitNonVirtualBases, 8935 /// Visit all direct bases, virtual or not. 8936 VisitDirectBases, 8937 /// Visit all non-virtual bases, and all virtual bases if the class 8938 /// is not abstract. 8939 VisitPotentiallyConstructedBases, 8940 /// Visit all direct or virtual bases. 8941 VisitAllBases 8942 }; 8943 8944 // Visit the bases and members of the class. 8945 bool visit(BasesToVisit Bases) { 8946 CXXRecordDecl *RD = MD->getParent(); 8947 8948 if (Bases == VisitPotentiallyConstructedBases) 8949 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8950 8951 for (auto &B : RD->bases()) 8952 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8953 getDerived().visitBase(&B)) 8954 return true; 8955 8956 if (Bases == VisitAllBases) 8957 for (auto &B : RD->vbases()) 8958 if (getDerived().visitBase(&B)) 8959 return true; 8960 8961 for (auto *F : RD->fields()) 8962 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8963 getDerived().visitField(F)) 8964 return true; 8965 8966 return false; 8967 } 8968 }; 8969 } 8970 8971 namespace { 8972 struct SpecialMemberDeletionInfo 8973 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8974 bool Diagnose; 8975 8976 SourceLocation Loc; 8977 8978 bool AllFieldsAreConst; 8979 8980 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 8981 Sema::CXXSpecialMember CSM, 8982 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 8983 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 8984 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 8985 8986 bool inUnion() const { return MD->getParent()->isUnion(); } 8987 8988 Sema::CXXSpecialMember getEffectiveCSM() { 8989 return ICI ? Sema::CXXInvalid : CSM; 8990 } 8991 8992 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 8993 8994 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 8995 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 8996 8997 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 8998 bool shouldDeleteForField(FieldDecl *FD); 8999 bool shouldDeleteForAllConstMembers(); 9000 9001 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 9002 unsigned Quals); 9003 bool shouldDeleteForSubobjectCall(Subobject Subobj, 9004 Sema::SpecialMemberOverloadResult SMOR, 9005 bool IsDtorCallInCtor); 9006 9007 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 9008 }; 9009 } 9010 9011 /// Is the given special member inaccessible when used on the given 9012 /// sub-object. 9013 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 9014 CXXMethodDecl *target) { 9015 /// If we're operating on a base class, the object type is the 9016 /// type of this special member. 9017 QualType objectTy; 9018 AccessSpecifier access = target->getAccess(); 9019 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 9020 objectTy = S.Context.getTypeDeclType(MD->getParent()); 9021 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 9022 9023 // If we're operating on a field, the object type is the type of the field. 9024 } else { 9025 objectTy = S.Context.getTypeDeclType(target->getParent()); 9026 } 9027 9028 return S.isMemberAccessibleForDeletion( 9029 target->getParent(), DeclAccessPair::make(target, access), objectTy); 9030 } 9031 9032 /// Check whether we should delete a special member due to the implicit 9033 /// definition containing a call to a special member of a subobject. 9034 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 9035 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 9036 bool IsDtorCallInCtor) { 9037 CXXMethodDecl *Decl = SMOR.getMethod(); 9038 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 9039 9040 int DiagKind = -1; 9041 9042 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 9043 DiagKind = !Decl ? 0 : 1; 9044 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9045 DiagKind = 2; 9046 else if (!isAccessible(Subobj, Decl)) 9047 DiagKind = 3; 9048 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 9049 !Decl->isTrivial()) { 9050 // A member of a union must have a trivial corresponding special member. 9051 // As a weird special case, a destructor call from a union's constructor 9052 // must be accessible and non-deleted, but need not be trivial. Such a 9053 // destructor is never actually called, but is semantically checked as 9054 // if it were. 9055 DiagKind = 4; 9056 } 9057 9058 if (DiagKind == -1) 9059 return false; 9060 9061 if (Diagnose) { 9062 if (Field) { 9063 S.Diag(Field->getLocation(), 9064 diag::note_deleted_special_member_class_subobject) 9065 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 9066 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 9067 } else { 9068 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 9069 S.Diag(Base->getBeginLoc(), 9070 diag::note_deleted_special_member_class_subobject) 9071 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 9072 << Base->getType() << DiagKind << IsDtorCallInCtor 9073 << /*IsObjCPtr*/false; 9074 } 9075 9076 if (DiagKind == 1) 9077 S.NoteDeletedFunction(Decl); 9078 // FIXME: Explain inaccessibility if DiagKind == 3. 9079 } 9080 9081 return true; 9082 } 9083 9084 /// Check whether we should delete a special member function due to having a 9085 /// direct or virtual base class or non-static data member of class type M. 9086 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 9087 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 9088 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 9089 bool IsMutable = Field && Field->isMutable(); 9090 9091 // C++11 [class.ctor]p5: 9092 // -- any direct or virtual base class, or non-static data member with no 9093 // brace-or-equal-initializer, has class type M (or array thereof) and 9094 // either M has no default constructor or overload resolution as applied 9095 // to M's default constructor results in an ambiguity or in a function 9096 // that is deleted or inaccessible 9097 // C++11 [class.copy]p11, C++11 [class.copy]p23: 9098 // -- a direct or virtual base class B that cannot be copied/moved because 9099 // overload resolution, as applied to B's corresponding special member, 9100 // results in an ambiguity or a function that is deleted or inaccessible 9101 // from the defaulted special member 9102 // C++11 [class.dtor]p5: 9103 // -- any direct or virtual base class [...] has a type with a destructor 9104 // that is deleted or inaccessible 9105 if (!(CSM == Sema::CXXDefaultConstructor && 9106 Field && Field->hasInClassInitializer()) && 9107 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 9108 false)) 9109 return true; 9110 9111 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 9112 // -- any direct or virtual base class or non-static data member has a 9113 // type with a destructor that is deleted or inaccessible 9114 if (IsConstructor) { 9115 Sema::SpecialMemberOverloadResult SMOR = 9116 S.LookupSpecialMember(Class, Sema::CXXDestructor, 9117 false, false, false, false, false); 9118 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 9119 return true; 9120 } 9121 9122 return false; 9123 } 9124 9125 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 9126 FieldDecl *FD, QualType FieldType) { 9127 // The defaulted special functions are defined as deleted if this is a variant 9128 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 9129 // type under ARC. 9130 if (!FieldType.hasNonTrivialObjCLifetime()) 9131 return false; 9132 9133 // Don't make the defaulted default constructor defined as deleted if the 9134 // member has an in-class initializer. 9135 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 9136 return false; 9137 9138 if (Diagnose) { 9139 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 9140 S.Diag(FD->getLocation(), 9141 diag::note_deleted_special_member_class_subobject) 9142 << getEffectiveCSM() << ParentClass << /*IsField*/true 9143 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 9144 } 9145 9146 return true; 9147 } 9148 9149 /// Check whether we should delete a special member function due to the class 9150 /// having a particular direct or virtual base class. 9151 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 9152 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 9153 // If program is correct, BaseClass cannot be null, but if it is, the error 9154 // must be reported elsewhere. 9155 if (!BaseClass) 9156 return false; 9157 // If we have an inheriting constructor, check whether we're calling an 9158 // inherited constructor instead of a default constructor. 9159 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 9160 if (auto *BaseCtor = SMOR.getMethod()) { 9161 // Note that we do not check access along this path; other than that, 9162 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 9163 // FIXME: Check that the base has a usable destructor! Sink this into 9164 // shouldDeleteForClassSubobject. 9165 if (BaseCtor->isDeleted() && Diagnose) { 9166 S.Diag(Base->getBeginLoc(), 9167 diag::note_deleted_special_member_class_subobject) 9168 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 9169 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 9170 << /*IsObjCPtr*/false; 9171 S.NoteDeletedFunction(BaseCtor); 9172 } 9173 return BaseCtor->isDeleted(); 9174 } 9175 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 9176 } 9177 9178 /// Check whether we should delete a special member function due to the class 9179 /// having a particular non-static data member. 9180 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 9181 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 9182 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 9183 9184 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 9185 return true; 9186 9187 if (CSM == Sema::CXXDefaultConstructor) { 9188 // For a default constructor, all references must be initialized in-class 9189 // and, if a union, it must have a non-const member. 9190 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 9191 if (Diagnose) 9192 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9193 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 9194 return true; 9195 } 9196 // C++11 [class.ctor]p5: any non-variant non-static data member of 9197 // const-qualified type (or array thereof) with no 9198 // brace-or-equal-initializer does not have a user-provided default 9199 // constructor. 9200 if (!inUnion() && FieldType.isConstQualified() && 9201 !FD->hasInClassInitializer() && 9202 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 9203 if (Diagnose) 9204 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9205 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 9206 return true; 9207 } 9208 9209 if (inUnion() && !FieldType.isConstQualified()) 9210 AllFieldsAreConst = false; 9211 } else if (CSM == Sema::CXXCopyConstructor) { 9212 // For a copy constructor, data members must not be of rvalue reference 9213 // type. 9214 if (FieldType->isRValueReferenceType()) { 9215 if (Diagnose) 9216 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 9217 << MD->getParent() << FD << FieldType; 9218 return true; 9219 } 9220 } else if (IsAssignment) { 9221 // For an assignment operator, data members must not be of reference type. 9222 if (FieldType->isReferenceType()) { 9223 if (Diagnose) 9224 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9225 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 9226 return true; 9227 } 9228 if (!FieldRecord && FieldType.isConstQualified()) { 9229 // C++11 [class.copy]p23: 9230 // -- a non-static data member of const non-class type (or array thereof) 9231 if (Diagnose) 9232 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9233 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 9234 return true; 9235 } 9236 } 9237 9238 if (FieldRecord) { 9239 // Some additional restrictions exist on the variant members. 9240 if (!inUnion() && FieldRecord->isUnion() && 9241 FieldRecord->isAnonymousStructOrUnion()) { 9242 bool AllVariantFieldsAreConst = true; 9243 9244 // FIXME: Handle anonymous unions declared within anonymous unions. 9245 for (auto *UI : FieldRecord->fields()) { 9246 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 9247 9248 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 9249 return true; 9250 9251 if (!UnionFieldType.isConstQualified()) 9252 AllVariantFieldsAreConst = false; 9253 9254 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 9255 if (UnionFieldRecord && 9256 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 9257 UnionFieldType.getCVRQualifiers())) 9258 return true; 9259 } 9260 9261 // At least one member in each anonymous union must be non-const 9262 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 9263 !FieldRecord->field_empty()) { 9264 if (Diagnose) 9265 S.Diag(FieldRecord->getLocation(), 9266 diag::note_deleted_default_ctor_all_const) 9267 << !!ICI << MD->getParent() << /*anonymous union*/1; 9268 return true; 9269 } 9270 9271 // Don't check the implicit member of the anonymous union type. 9272 // This is technically non-conformant but supported, and we have a 9273 // diagnostic for this elsewhere. 9274 return false; 9275 } 9276 9277 if (shouldDeleteForClassSubobject(FieldRecord, FD, 9278 FieldType.getCVRQualifiers())) 9279 return true; 9280 } 9281 9282 return false; 9283 } 9284 9285 /// C++11 [class.ctor] p5: 9286 /// A defaulted default constructor for a class X is defined as deleted if 9287 /// X is a union and all of its variant members are of const-qualified type. 9288 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 9289 // This is a silly definition, because it gives an empty union a deleted 9290 // default constructor. Don't do that. 9291 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 9292 bool AnyFields = false; 9293 for (auto *F : MD->getParent()->fields()) 9294 if ((AnyFields = !F->isUnnamedBitfield())) 9295 break; 9296 if (!AnyFields) 9297 return false; 9298 if (Diagnose) 9299 S.Diag(MD->getParent()->getLocation(), 9300 diag::note_deleted_default_ctor_all_const) 9301 << !!ICI << MD->getParent() << /*not anonymous union*/0; 9302 return true; 9303 } 9304 return false; 9305 } 9306 9307 /// Determine whether a defaulted special member function should be defined as 9308 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 9309 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 9310 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 9311 InheritedConstructorInfo *ICI, 9312 bool Diagnose) { 9313 if (MD->isInvalidDecl()) 9314 return false; 9315 CXXRecordDecl *RD = MD->getParent(); 9316 assert(!RD->isDependentType() && "do deletion after instantiation"); 9317 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 9318 return false; 9319 9320 // C++11 [expr.lambda.prim]p19: 9321 // The closure type associated with a lambda-expression has a 9322 // deleted (8.4.3) default constructor and a deleted copy 9323 // assignment operator. 9324 // C++2a adds back these operators if the lambda has no lambda-capture. 9325 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 9326 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 9327 if (Diagnose) 9328 Diag(RD->getLocation(), diag::note_lambda_decl); 9329 return true; 9330 } 9331 9332 // For an anonymous struct or union, the copy and assignment special members 9333 // will never be used, so skip the check. For an anonymous union declared at 9334 // namespace scope, the constructor and destructor are used. 9335 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 9336 RD->isAnonymousStructOrUnion()) 9337 return false; 9338 9339 // C++11 [class.copy]p7, p18: 9340 // If the class definition declares a move constructor or move assignment 9341 // operator, an implicitly declared copy constructor or copy assignment 9342 // operator is defined as deleted. 9343 if (MD->isImplicit() && 9344 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 9345 CXXMethodDecl *UserDeclaredMove = nullptr; 9346 9347 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 9348 // deletion of the corresponding copy operation, not both copy operations. 9349 // MSVC 2015 has adopted the standards conforming behavior. 9350 bool DeletesOnlyMatchingCopy = 9351 getLangOpts().MSVCCompat && 9352 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 9353 9354 if (RD->hasUserDeclaredMoveConstructor() && 9355 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 9356 if (!Diagnose) return true; 9357 9358 // Find any user-declared move constructor. 9359 for (auto *I : RD->ctors()) { 9360 if (I->isMoveConstructor()) { 9361 UserDeclaredMove = I; 9362 break; 9363 } 9364 } 9365 assert(UserDeclaredMove); 9366 } else if (RD->hasUserDeclaredMoveAssignment() && 9367 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 9368 if (!Diagnose) return true; 9369 9370 // Find any user-declared move assignment operator. 9371 for (auto *I : RD->methods()) { 9372 if (I->isMoveAssignmentOperator()) { 9373 UserDeclaredMove = I; 9374 break; 9375 } 9376 } 9377 assert(UserDeclaredMove); 9378 } 9379 9380 if (UserDeclaredMove) { 9381 Diag(UserDeclaredMove->getLocation(), 9382 diag::note_deleted_copy_user_declared_move) 9383 << (CSM == CXXCopyAssignment) << RD 9384 << UserDeclaredMove->isMoveAssignmentOperator(); 9385 return true; 9386 } 9387 } 9388 9389 // Do access control from the special member function 9390 ContextRAII MethodContext(*this, MD); 9391 9392 // C++11 [class.dtor]p5: 9393 // -- for a virtual destructor, lookup of the non-array deallocation function 9394 // results in an ambiguity or in a function that is deleted or inaccessible 9395 if (CSM == CXXDestructor && MD->isVirtual()) { 9396 FunctionDecl *OperatorDelete = nullptr; 9397 DeclarationName Name = 9398 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 9399 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 9400 OperatorDelete, /*Diagnose*/false)) { 9401 if (Diagnose) 9402 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 9403 return true; 9404 } 9405 } 9406 9407 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 9408 9409 // Per DR1611, do not consider virtual bases of constructors of abstract 9410 // classes, since we are not going to construct them. 9411 // Per DR1658, do not consider virtual bases of destructors of abstract 9412 // classes either. 9413 // Per DR2180, for assignment operators we only assign (and thus only 9414 // consider) direct bases. 9415 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 9416 : SMI.VisitPotentiallyConstructedBases)) 9417 return true; 9418 9419 if (SMI.shouldDeleteForAllConstMembers()) 9420 return true; 9421 9422 if (getLangOpts().CUDA) { 9423 // We should delete the special member in CUDA mode if target inference 9424 // failed. 9425 // For inherited constructors (non-null ICI), CSM may be passed so that MD 9426 // is treated as certain special member, which may not reflect what special 9427 // member MD really is. However inferCUDATargetForImplicitSpecialMember 9428 // expects CSM to match MD, therefore recalculate CSM. 9429 assert(ICI || CSM == getSpecialMember(MD)); 9430 auto RealCSM = CSM; 9431 if (ICI) 9432 RealCSM = getSpecialMember(MD); 9433 9434 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 9435 SMI.ConstArg, Diagnose); 9436 } 9437 9438 return false; 9439 } 9440 9441 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 9442 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 9443 assert(DFK && "not a defaultable function"); 9444 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted"); 9445 9446 if (DFK.isSpecialMember()) { 9447 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 9448 nullptr, /*Diagnose=*/true); 9449 } else { 9450 DefaultedComparisonAnalyzer( 9451 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 9452 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 9453 .visit(); 9454 } 9455 } 9456 9457 /// Perform lookup for a special member of the specified kind, and determine 9458 /// whether it is trivial. If the triviality can be determined without the 9459 /// lookup, skip it. This is intended for use when determining whether a 9460 /// special member of a containing object is trivial, and thus does not ever 9461 /// perform overload resolution for default constructors. 9462 /// 9463 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 9464 /// member that was most likely to be intended to be trivial, if any. 9465 /// 9466 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 9467 /// determine whether the special member is trivial. 9468 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 9469 Sema::CXXSpecialMember CSM, unsigned Quals, 9470 bool ConstRHS, 9471 Sema::TrivialABIHandling TAH, 9472 CXXMethodDecl **Selected) { 9473 if (Selected) 9474 *Selected = nullptr; 9475 9476 switch (CSM) { 9477 case Sema::CXXInvalid: 9478 llvm_unreachable("not a special member"); 9479 9480 case Sema::CXXDefaultConstructor: 9481 // C++11 [class.ctor]p5: 9482 // A default constructor is trivial if: 9483 // - all the [direct subobjects] have trivial default constructors 9484 // 9485 // Note, no overload resolution is performed in this case. 9486 if (RD->hasTrivialDefaultConstructor()) 9487 return true; 9488 9489 if (Selected) { 9490 // If there's a default constructor which could have been trivial, dig it 9491 // out. Otherwise, if there's any user-provided default constructor, point 9492 // to that as an example of why there's not a trivial one. 9493 CXXConstructorDecl *DefCtor = nullptr; 9494 if (RD->needsImplicitDefaultConstructor()) 9495 S.DeclareImplicitDefaultConstructor(RD); 9496 for (auto *CI : RD->ctors()) { 9497 if (!CI->isDefaultConstructor()) 9498 continue; 9499 DefCtor = CI; 9500 if (!DefCtor->isUserProvided()) 9501 break; 9502 } 9503 9504 *Selected = DefCtor; 9505 } 9506 9507 return false; 9508 9509 case Sema::CXXDestructor: 9510 // C++11 [class.dtor]p5: 9511 // A destructor is trivial if: 9512 // - all the direct [subobjects] have trivial destructors 9513 if (RD->hasTrivialDestructor() || 9514 (TAH == Sema::TAH_ConsiderTrivialABI && 9515 RD->hasTrivialDestructorForCall())) 9516 return true; 9517 9518 if (Selected) { 9519 if (RD->needsImplicitDestructor()) 9520 S.DeclareImplicitDestructor(RD); 9521 *Selected = RD->getDestructor(); 9522 } 9523 9524 return false; 9525 9526 case Sema::CXXCopyConstructor: 9527 // C++11 [class.copy]p12: 9528 // A copy constructor is trivial if: 9529 // - the constructor selected to copy each direct [subobject] is trivial 9530 if (RD->hasTrivialCopyConstructor() || 9531 (TAH == Sema::TAH_ConsiderTrivialABI && 9532 RD->hasTrivialCopyConstructorForCall())) { 9533 if (Quals == Qualifiers::Const) 9534 // We must either select the trivial copy constructor or reach an 9535 // ambiguity; no need to actually perform overload resolution. 9536 return true; 9537 } else if (!Selected) { 9538 return false; 9539 } 9540 // In C++98, we are not supposed to perform overload resolution here, but we 9541 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 9542 // cases like B as having a non-trivial copy constructor: 9543 // struct A { template<typename T> A(T&); }; 9544 // struct B { mutable A a; }; 9545 goto NeedOverloadResolution; 9546 9547 case Sema::CXXCopyAssignment: 9548 // C++11 [class.copy]p25: 9549 // A copy assignment operator is trivial if: 9550 // - the assignment operator selected to copy each direct [subobject] is 9551 // trivial 9552 if (RD->hasTrivialCopyAssignment()) { 9553 if (Quals == Qualifiers::Const) 9554 return true; 9555 } else if (!Selected) { 9556 return false; 9557 } 9558 // In C++98, we are not supposed to perform overload resolution here, but we 9559 // treat that as a language defect. 9560 goto NeedOverloadResolution; 9561 9562 case Sema::CXXMoveConstructor: 9563 case Sema::CXXMoveAssignment: 9564 NeedOverloadResolution: 9565 Sema::SpecialMemberOverloadResult SMOR = 9566 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 9567 9568 // The standard doesn't describe how to behave if the lookup is ambiguous. 9569 // We treat it as not making the member non-trivial, just like the standard 9570 // mandates for the default constructor. This should rarely matter, because 9571 // the member will also be deleted. 9572 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9573 return true; 9574 9575 if (!SMOR.getMethod()) { 9576 assert(SMOR.getKind() == 9577 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 9578 return false; 9579 } 9580 9581 // We deliberately don't check if we found a deleted special member. We're 9582 // not supposed to! 9583 if (Selected) 9584 *Selected = SMOR.getMethod(); 9585 9586 if (TAH == Sema::TAH_ConsiderTrivialABI && 9587 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 9588 return SMOR.getMethod()->isTrivialForCall(); 9589 return SMOR.getMethod()->isTrivial(); 9590 } 9591 9592 llvm_unreachable("unknown special method kind"); 9593 } 9594 9595 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 9596 for (auto *CI : RD->ctors()) 9597 if (!CI->isImplicit()) 9598 return CI; 9599 9600 // Look for constructor templates. 9601 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 9602 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 9603 if (CXXConstructorDecl *CD = 9604 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 9605 return CD; 9606 } 9607 9608 return nullptr; 9609 } 9610 9611 /// The kind of subobject we are checking for triviality. The values of this 9612 /// enumeration are used in diagnostics. 9613 enum TrivialSubobjectKind { 9614 /// The subobject is a base class. 9615 TSK_BaseClass, 9616 /// The subobject is a non-static data member. 9617 TSK_Field, 9618 /// The object is actually the complete object. 9619 TSK_CompleteObject 9620 }; 9621 9622 /// Check whether the special member selected for a given type would be trivial. 9623 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9624 QualType SubType, bool ConstRHS, 9625 Sema::CXXSpecialMember CSM, 9626 TrivialSubobjectKind Kind, 9627 Sema::TrivialABIHandling TAH, bool Diagnose) { 9628 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9629 if (!SubRD) 9630 return true; 9631 9632 CXXMethodDecl *Selected; 9633 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9634 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9635 return true; 9636 9637 if (Diagnose) { 9638 if (ConstRHS) 9639 SubType.addConst(); 9640 9641 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9642 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9643 << Kind << SubType.getUnqualifiedType(); 9644 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9645 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9646 } else if (!Selected) 9647 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9648 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9649 else if (Selected->isUserProvided()) { 9650 if (Kind == TSK_CompleteObject) 9651 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9652 << Kind << SubType.getUnqualifiedType() << CSM; 9653 else { 9654 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9655 << Kind << SubType.getUnqualifiedType() << CSM; 9656 S.Diag(Selected->getLocation(), diag::note_declared_at); 9657 } 9658 } else { 9659 if (Kind != TSK_CompleteObject) 9660 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9661 << Kind << SubType.getUnqualifiedType() << CSM; 9662 9663 // Explain why the defaulted or deleted special member isn't trivial. 9664 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9665 Diagnose); 9666 } 9667 } 9668 9669 return false; 9670 } 9671 9672 /// Check whether the members of a class type allow a special member to be 9673 /// trivial. 9674 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9675 Sema::CXXSpecialMember CSM, 9676 bool ConstArg, 9677 Sema::TrivialABIHandling TAH, 9678 bool Diagnose) { 9679 for (const auto *FI : RD->fields()) { 9680 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9681 continue; 9682 9683 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9684 9685 // Pretend anonymous struct or union members are members of this class. 9686 if (FI->isAnonymousStructOrUnion()) { 9687 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9688 CSM, ConstArg, TAH, Diagnose)) 9689 return false; 9690 continue; 9691 } 9692 9693 // C++11 [class.ctor]p5: 9694 // A default constructor is trivial if [...] 9695 // -- no non-static data member of its class has a 9696 // brace-or-equal-initializer 9697 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9698 if (Diagnose) 9699 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init) 9700 << FI; 9701 return false; 9702 } 9703 9704 // Objective C ARC 4.3.5: 9705 // [...] nontrivally ownership-qualified types are [...] not trivially 9706 // default constructible, copy constructible, move constructible, copy 9707 // assignable, move assignable, or destructible [...] 9708 if (FieldType.hasNonTrivialObjCLifetime()) { 9709 if (Diagnose) 9710 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9711 << RD << FieldType.getObjCLifetime(); 9712 return false; 9713 } 9714 9715 bool ConstRHS = ConstArg && !FI->isMutable(); 9716 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9717 CSM, TSK_Field, TAH, Diagnose)) 9718 return false; 9719 } 9720 9721 return true; 9722 } 9723 9724 /// Diagnose why the specified class does not have a trivial special member of 9725 /// the given kind. 9726 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9727 QualType Ty = Context.getRecordType(RD); 9728 9729 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9730 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9731 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9732 /*Diagnose*/true); 9733 } 9734 9735 /// Determine whether a defaulted or deleted special member function is trivial, 9736 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9737 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9738 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9739 TrivialABIHandling TAH, bool Diagnose) { 9740 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 9741 9742 CXXRecordDecl *RD = MD->getParent(); 9743 9744 bool ConstArg = false; 9745 9746 // C++11 [class.copy]p12, p25: [DR1593] 9747 // A [special member] is trivial if [...] its parameter-type-list is 9748 // equivalent to the parameter-type-list of an implicit declaration [...] 9749 switch (CSM) { 9750 case CXXDefaultConstructor: 9751 case CXXDestructor: 9752 // Trivial default constructors and destructors cannot have parameters. 9753 break; 9754 9755 case CXXCopyConstructor: 9756 case CXXCopyAssignment: { 9757 // Trivial copy operations always have const, non-volatile parameter types. 9758 ConstArg = true; 9759 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9760 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9761 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 9762 if (Diagnose) 9763 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9764 << Param0->getSourceRange() << Param0->getType() 9765 << Context.getLValueReferenceType( 9766 Context.getRecordType(RD).withConst()); 9767 return false; 9768 } 9769 break; 9770 } 9771 9772 case CXXMoveConstructor: 9773 case CXXMoveAssignment: { 9774 // Trivial move operations always have non-cv-qualified parameters. 9775 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9776 const RValueReferenceType *RT = 9777 Param0->getType()->getAs<RValueReferenceType>(); 9778 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9779 if (Diagnose) 9780 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9781 << Param0->getSourceRange() << Param0->getType() 9782 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9783 return false; 9784 } 9785 break; 9786 } 9787 9788 case CXXInvalid: 9789 llvm_unreachable("not a special member"); 9790 } 9791 9792 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9793 if (Diagnose) 9794 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9795 diag::note_nontrivial_default_arg) 9796 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9797 return false; 9798 } 9799 if (MD->isVariadic()) { 9800 if (Diagnose) 9801 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9802 return false; 9803 } 9804 9805 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9806 // A copy/move [constructor or assignment operator] is trivial if 9807 // -- the [member] selected to copy/move each direct base class subobject 9808 // is trivial 9809 // 9810 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9811 // A [default constructor or destructor] is trivial if 9812 // -- all the direct base classes have trivial [default constructors or 9813 // destructors] 9814 for (const auto &BI : RD->bases()) 9815 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9816 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9817 return false; 9818 9819 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9820 // A copy/move [constructor or assignment operator] for a class X is 9821 // trivial if 9822 // -- for each non-static data member of X that is of class type (or array 9823 // thereof), the constructor selected to copy/move that member is 9824 // trivial 9825 // 9826 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9827 // A [default constructor or destructor] is trivial if 9828 // -- for all of the non-static data members of its class that are of class 9829 // type (or array thereof), each such class has a trivial [default 9830 // constructor or destructor] 9831 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9832 return false; 9833 9834 // C++11 [class.dtor]p5: 9835 // A destructor is trivial if [...] 9836 // -- the destructor is not virtual 9837 if (CSM == CXXDestructor && MD->isVirtual()) { 9838 if (Diagnose) 9839 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9840 return false; 9841 } 9842 9843 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9844 // A [special member] for class X is trivial if [...] 9845 // -- class X has no virtual functions and no virtual base classes 9846 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9847 if (!Diagnose) 9848 return false; 9849 9850 if (RD->getNumVBases()) { 9851 // Check for virtual bases. We already know that the corresponding 9852 // member in all bases is trivial, so vbases must all be direct. 9853 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9854 assert(BS.isVirtual()); 9855 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9856 return false; 9857 } 9858 9859 // Must have a virtual method. 9860 for (const auto *MI : RD->methods()) { 9861 if (MI->isVirtual()) { 9862 SourceLocation MLoc = MI->getBeginLoc(); 9863 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9864 return false; 9865 } 9866 } 9867 9868 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 9869 } 9870 9871 // Looks like it's trivial! 9872 return true; 9873 } 9874 9875 namespace { 9876 struct FindHiddenVirtualMethod { 9877 Sema *S; 9878 CXXMethodDecl *Method; 9879 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9880 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9881 9882 private: 9883 /// Check whether any most overridden method from MD in Methods 9884 static bool CheckMostOverridenMethods( 9885 const CXXMethodDecl *MD, 9886 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9887 if (MD->size_overridden_methods() == 0) 9888 return Methods.count(MD->getCanonicalDecl()); 9889 for (const CXXMethodDecl *O : MD->overridden_methods()) 9890 if (CheckMostOverridenMethods(O, Methods)) 9891 return true; 9892 return false; 9893 } 9894 9895 public: 9896 /// Member lookup function that determines whether a given C++ 9897 /// method overloads virtual methods in a base class without overriding any, 9898 /// to be used with CXXRecordDecl::lookupInBases(). 9899 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9900 RecordDecl *BaseRecord = 9901 Specifier->getType()->castAs<RecordType>()->getDecl(); 9902 9903 DeclarationName Name = Method->getDeclName(); 9904 assert(Name.getNameKind() == DeclarationName::Identifier); 9905 9906 bool foundSameNameMethod = false; 9907 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9908 for (Path.Decls = BaseRecord->lookup(Name).begin(); 9909 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) { 9910 NamedDecl *D = *Path.Decls; 9911 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9912 MD = MD->getCanonicalDecl(); 9913 foundSameNameMethod = true; 9914 // Interested only in hidden virtual methods. 9915 if (!MD->isVirtual()) 9916 continue; 9917 // If the method we are checking overrides a method from its base 9918 // don't warn about the other overloaded methods. Clang deviates from 9919 // GCC by only diagnosing overloads of inherited virtual functions that 9920 // do not override any other virtual functions in the base. GCC's 9921 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9922 // function from a base class. These cases may be better served by a 9923 // warning (not specific to virtual functions) on call sites when the 9924 // call would select a different function from the base class, were it 9925 // visible. 9926 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9927 if (!S->IsOverload(Method, MD, false)) 9928 return true; 9929 // Collect the overload only if its hidden. 9930 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9931 overloadedMethods.push_back(MD); 9932 } 9933 } 9934 9935 if (foundSameNameMethod) 9936 OverloadedMethods.append(overloadedMethods.begin(), 9937 overloadedMethods.end()); 9938 return foundSameNameMethod; 9939 } 9940 }; 9941 } // end anonymous namespace 9942 9943 /// Add the most overridden methods from MD to Methods 9944 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9945 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9946 if (MD->size_overridden_methods() == 0) 9947 Methods.insert(MD->getCanonicalDecl()); 9948 else 9949 for (const CXXMethodDecl *O : MD->overridden_methods()) 9950 AddMostOverridenMethods(O, Methods); 9951 } 9952 9953 /// Check if a method overloads virtual methods in a base class without 9954 /// overriding any. 9955 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9956 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9957 if (!MD->getDeclName().isIdentifier()) 9958 return; 9959 9960 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9961 /*bool RecordPaths=*/false, 9962 /*bool DetectVirtual=*/false); 9963 FindHiddenVirtualMethod FHVM; 9964 FHVM.Method = MD; 9965 FHVM.S = this; 9966 9967 // Keep the base methods that were overridden or introduced in the subclass 9968 // by 'using' in a set. A base method not in this set is hidden. 9969 CXXRecordDecl *DC = MD->getParent(); 9970 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9971 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9972 NamedDecl *ND = *I; 9973 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9974 ND = shad->getTargetDecl(); 9975 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9976 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9977 } 9978 9979 if (DC->lookupInBases(FHVM, Paths)) 9980 OverloadedMethods = FHVM.OverloadedMethods; 9981 } 9982 9983 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 9984 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9985 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 9986 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 9987 PartialDiagnostic PD = PDiag( 9988 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 9989 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 9990 Diag(overloadedMD->getLocation(), PD); 9991 } 9992 } 9993 9994 /// Diagnose methods which overload virtual methods in a base class 9995 /// without overriding any. 9996 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 9997 if (MD->isInvalidDecl()) 9998 return; 9999 10000 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 10001 return; 10002 10003 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 10004 FindHiddenVirtualMethods(MD, OverloadedMethods); 10005 if (!OverloadedMethods.empty()) { 10006 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 10007 << MD << (OverloadedMethods.size() > 1); 10008 10009 NoteHiddenVirtualMethods(MD, OverloadedMethods); 10010 } 10011 } 10012 10013 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 10014 auto PrintDiagAndRemoveAttr = [&](unsigned N) { 10015 // No diagnostics if this is a template instantiation. 10016 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) { 10017 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 10018 diag::ext_cannot_use_trivial_abi) << &RD; 10019 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 10020 diag::note_cannot_use_trivial_abi_reason) << &RD << N; 10021 } 10022 RD.dropAttr<TrivialABIAttr>(); 10023 }; 10024 10025 // Ill-formed if the copy and move constructors are deleted. 10026 auto HasNonDeletedCopyOrMoveConstructor = [&]() { 10027 // If the type is dependent, then assume it might have 10028 // implicit copy or move ctor because we won't know yet at this point. 10029 if (RD.isDependentType()) 10030 return true; 10031 if (RD.needsImplicitCopyConstructor() && 10032 !RD.defaultedCopyConstructorIsDeleted()) 10033 return true; 10034 if (RD.needsImplicitMoveConstructor() && 10035 !RD.defaultedMoveConstructorIsDeleted()) 10036 return true; 10037 for (const CXXConstructorDecl *CD : RD.ctors()) 10038 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted()) 10039 return true; 10040 return false; 10041 }; 10042 10043 if (!HasNonDeletedCopyOrMoveConstructor()) { 10044 PrintDiagAndRemoveAttr(0); 10045 return; 10046 } 10047 10048 // Ill-formed if the struct has virtual functions. 10049 if (RD.isPolymorphic()) { 10050 PrintDiagAndRemoveAttr(1); 10051 return; 10052 } 10053 10054 for (const auto &B : RD.bases()) { 10055 // Ill-formed if the base class is non-trivial for the purpose of calls or a 10056 // virtual base. 10057 if (!B.getType()->isDependentType() && 10058 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) { 10059 PrintDiagAndRemoveAttr(2); 10060 return; 10061 } 10062 10063 if (B.isVirtual()) { 10064 PrintDiagAndRemoveAttr(3); 10065 return; 10066 } 10067 } 10068 10069 for (const auto *FD : RD.fields()) { 10070 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 10071 // non-trivial for the purpose of calls. 10072 QualType FT = FD->getType(); 10073 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 10074 PrintDiagAndRemoveAttr(4); 10075 return; 10076 } 10077 10078 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 10079 if (!RT->isDependentType() && 10080 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 10081 PrintDiagAndRemoveAttr(5); 10082 return; 10083 } 10084 } 10085 } 10086 10087 void Sema::ActOnFinishCXXMemberSpecification( 10088 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 10089 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 10090 if (!TagDecl) 10091 return; 10092 10093 AdjustDeclIfTemplate(TagDecl); 10094 10095 for (const ParsedAttr &AL : AttrList) { 10096 if (AL.getKind() != ParsedAttr::AT_Visibility) 10097 continue; 10098 AL.setInvalid(); 10099 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 10100 } 10101 10102 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 10103 // strict aliasing violation! 10104 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 10105 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 10106 10107 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 10108 } 10109 10110 /// Find the equality comparison functions that should be implicitly declared 10111 /// in a given class definition, per C++2a [class.compare.default]p3. 10112 static void findImplicitlyDeclaredEqualityComparisons( 10113 ASTContext &Ctx, CXXRecordDecl *RD, 10114 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 10115 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 10116 if (!RD->lookup(EqEq).empty()) 10117 // Member operator== explicitly declared: no implicit operator==s. 10118 return; 10119 10120 // Traverse friends looking for an '==' or a '<=>'. 10121 for (FriendDecl *Friend : RD->friends()) { 10122 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 10123 if (!FD) continue; 10124 10125 if (FD->getOverloadedOperator() == OO_EqualEqual) { 10126 // Friend operator== explicitly declared: no implicit operator==s. 10127 Spaceships.clear(); 10128 return; 10129 } 10130 10131 if (FD->getOverloadedOperator() == OO_Spaceship && 10132 FD->isExplicitlyDefaulted()) 10133 Spaceships.push_back(FD); 10134 } 10135 10136 // Look for members named 'operator<=>'. 10137 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 10138 for (NamedDecl *ND : RD->lookup(Cmp)) { 10139 // Note that we could find a non-function here (either a function template 10140 // or a using-declaration). Neither case results in an implicit 10141 // 'operator=='. 10142 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 10143 if (FD->isExplicitlyDefaulted()) 10144 Spaceships.push_back(FD); 10145 } 10146 } 10147 10148 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 10149 /// special functions, such as the default constructor, copy 10150 /// constructor, or destructor, to the given C++ class (C++ 10151 /// [special]p1). This routine can only be executed just before the 10152 /// definition of the class is complete. 10153 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 10154 // Don't add implicit special members to templated classes. 10155 // FIXME: This means unqualified lookups for 'operator=' within a class 10156 // template don't work properly. 10157 if (!ClassDecl->isDependentType()) { 10158 if (ClassDecl->needsImplicitDefaultConstructor()) { 10159 ++getASTContext().NumImplicitDefaultConstructors; 10160 10161 if (ClassDecl->hasInheritedConstructor()) 10162 DeclareImplicitDefaultConstructor(ClassDecl); 10163 } 10164 10165 if (ClassDecl->needsImplicitCopyConstructor()) { 10166 ++getASTContext().NumImplicitCopyConstructors; 10167 10168 // If the properties or semantics of the copy constructor couldn't be 10169 // determined while the class was being declared, force a declaration 10170 // of it now. 10171 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 10172 ClassDecl->hasInheritedConstructor()) 10173 DeclareImplicitCopyConstructor(ClassDecl); 10174 // For the MS ABI we need to know whether the copy ctor is deleted. A 10175 // prerequisite for deleting the implicit copy ctor is that the class has 10176 // a move ctor or move assignment that is either user-declared or whose 10177 // semantics are inherited from a subobject. FIXME: We should provide a 10178 // more direct way for CodeGen to ask whether the constructor was deleted. 10179 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 10180 (ClassDecl->hasUserDeclaredMoveConstructor() || 10181 ClassDecl->needsOverloadResolutionForMoveConstructor() || 10182 ClassDecl->hasUserDeclaredMoveAssignment() || 10183 ClassDecl->needsOverloadResolutionForMoveAssignment())) 10184 DeclareImplicitCopyConstructor(ClassDecl); 10185 } 10186 10187 if (getLangOpts().CPlusPlus11 && 10188 ClassDecl->needsImplicitMoveConstructor()) { 10189 ++getASTContext().NumImplicitMoveConstructors; 10190 10191 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 10192 ClassDecl->hasInheritedConstructor()) 10193 DeclareImplicitMoveConstructor(ClassDecl); 10194 } 10195 10196 if (ClassDecl->needsImplicitCopyAssignment()) { 10197 ++getASTContext().NumImplicitCopyAssignmentOperators; 10198 10199 // If we have a dynamic class, then the copy assignment operator may be 10200 // virtual, so we have to declare it immediately. This ensures that, e.g., 10201 // it shows up in the right place in the vtable and that we diagnose 10202 // problems with the implicit exception specification. 10203 if (ClassDecl->isDynamicClass() || 10204 ClassDecl->needsOverloadResolutionForCopyAssignment() || 10205 ClassDecl->hasInheritedAssignment()) 10206 DeclareImplicitCopyAssignment(ClassDecl); 10207 } 10208 10209 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 10210 ++getASTContext().NumImplicitMoveAssignmentOperators; 10211 10212 // Likewise for the move assignment operator. 10213 if (ClassDecl->isDynamicClass() || 10214 ClassDecl->needsOverloadResolutionForMoveAssignment() || 10215 ClassDecl->hasInheritedAssignment()) 10216 DeclareImplicitMoveAssignment(ClassDecl); 10217 } 10218 10219 if (ClassDecl->needsImplicitDestructor()) { 10220 ++getASTContext().NumImplicitDestructors; 10221 10222 // If we have a dynamic class, then the destructor may be virtual, so we 10223 // have to declare the destructor immediately. This ensures that, e.g., it 10224 // shows up in the right place in the vtable and that we diagnose problems 10225 // with the implicit exception specification. 10226 if (ClassDecl->isDynamicClass() || 10227 ClassDecl->needsOverloadResolutionForDestructor()) 10228 DeclareImplicitDestructor(ClassDecl); 10229 } 10230 } 10231 10232 // C++2a [class.compare.default]p3: 10233 // If the member-specification does not explicitly declare any member or 10234 // friend named operator==, an == operator function is declared implicitly 10235 // for each defaulted three-way comparison operator function defined in 10236 // the member-specification 10237 // FIXME: Consider doing this lazily. 10238 // We do this during the initial parse for a class template, not during 10239 // instantiation, so that we can handle unqualified lookups for 'operator==' 10240 // when parsing the template. 10241 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) { 10242 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships; 10243 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 10244 DefaultedSpaceships); 10245 for (auto *FD : DefaultedSpaceships) 10246 DeclareImplicitEqualityComparison(ClassDecl, FD); 10247 } 10248 } 10249 10250 unsigned 10251 Sema::ActOnReenterTemplateScope(Decl *D, 10252 llvm::function_ref<Scope *()> EnterScope) { 10253 if (!D) 10254 return 0; 10255 AdjustDeclIfTemplate(D); 10256 10257 // In order to get name lookup right, reenter template scopes in order from 10258 // outermost to innermost. 10259 SmallVector<TemplateParameterList *, 4> ParameterLists; 10260 DeclContext *LookupDC = dyn_cast<DeclContext>(D); 10261 10262 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 10263 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 10264 ParameterLists.push_back(DD->getTemplateParameterList(i)); 10265 10266 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10267 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 10268 ParameterLists.push_back(FTD->getTemplateParameters()); 10269 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 10270 LookupDC = VD->getDeclContext(); 10271 10272 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate()) 10273 ParameterLists.push_back(VTD->getTemplateParameters()); 10274 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) 10275 ParameterLists.push_back(PSD->getTemplateParameters()); 10276 } 10277 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 10278 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 10279 ParameterLists.push_back(TD->getTemplateParameterList(i)); 10280 10281 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 10282 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 10283 ParameterLists.push_back(CTD->getTemplateParameters()); 10284 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 10285 ParameterLists.push_back(PSD->getTemplateParameters()); 10286 } 10287 } 10288 // FIXME: Alias declarations and concepts. 10289 10290 unsigned Count = 0; 10291 Scope *InnermostTemplateScope = nullptr; 10292 for (TemplateParameterList *Params : ParameterLists) { 10293 // Ignore explicit specializations; they don't contribute to the template 10294 // depth. 10295 if (Params->size() == 0) 10296 continue; 10297 10298 InnermostTemplateScope = EnterScope(); 10299 for (NamedDecl *Param : *Params) { 10300 if (Param->getDeclName()) { 10301 InnermostTemplateScope->AddDecl(Param); 10302 IdResolver.AddDecl(Param); 10303 } 10304 } 10305 ++Count; 10306 } 10307 10308 // Associate the new template scopes with the corresponding entities. 10309 if (InnermostTemplateScope) { 10310 assert(LookupDC && "no enclosing DeclContext for template lookup"); 10311 EnterTemplatedContext(InnermostTemplateScope, LookupDC); 10312 } 10313 10314 return Count; 10315 } 10316 10317 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10318 if (!RecordD) return; 10319 AdjustDeclIfTemplate(RecordD); 10320 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 10321 PushDeclContext(S, Record); 10322 } 10323 10324 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10325 if (!RecordD) return; 10326 PopDeclContext(); 10327 } 10328 10329 /// This is used to implement the constant expression evaluation part of the 10330 /// attribute enable_if extension. There is nothing in standard C++ which would 10331 /// require reentering parameters. 10332 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 10333 if (!Param) 10334 return; 10335 10336 S->AddDecl(Param); 10337 if (Param->getDeclName()) 10338 IdResolver.AddDecl(Param); 10339 } 10340 10341 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 10342 /// parsing a top-level (non-nested) C++ class, and we are now 10343 /// parsing those parts of the given Method declaration that could 10344 /// not be parsed earlier (C++ [class.mem]p2), such as default 10345 /// arguments. This action should enter the scope of the given 10346 /// Method declaration as if we had just parsed the qualified method 10347 /// name. However, it should not bring the parameters into scope; 10348 /// that will be performed by ActOnDelayedCXXMethodParameter. 10349 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10350 } 10351 10352 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 10353 /// C++ method declaration. We're (re-)introducing the given 10354 /// function parameter into scope for use in parsing later parts of 10355 /// the method declaration. For example, we could see an 10356 /// ActOnParamDefaultArgument event for this parameter. 10357 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 10358 if (!ParamD) 10359 return; 10360 10361 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 10362 10363 S->AddDecl(Param); 10364 if (Param->getDeclName()) 10365 IdResolver.AddDecl(Param); 10366 } 10367 10368 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 10369 /// processing the delayed method declaration for Method. The method 10370 /// declaration is now considered finished. There may be a separate 10371 /// ActOnStartOfFunctionDef action later (not necessarily 10372 /// immediately!) for this method, if it was also defined inside the 10373 /// class body. 10374 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10375 if (!MethodD) 10376 return; 10377 10378 AdjustDeclIfTemplate(MethodD); 10379 10380 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 10381 10382 // Now that we have our default arguments, check the constructor 10383 // again. It could produce additional diagnostics or affect whether 10384 // the class has implicitly-declared destructors, among other 10385 // things. 10386 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 10387 CheckConstructor(Constructor); 10388 10389 // Check the default arguments, which we may have added. 10390 if (!Method->isInvalidDecl()) 10391 CheckCXXDefaultArguments(Method); 10392 } 10393 10394 // Emit the given diagnostic for each non-address-space qualifier. 10395 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 10396 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 10397 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10398 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 10399 bool DiagOccured = false; 10400 FTI.MethodQualifiers->forEachQualifier( 10401 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 10402 SourceLocation SL) { 10403 // This diagnostic should be emitted on any qualifier except an addr 10404 // space qualifier. However, forEachQualifier currently doesn't visit 10405 // addr space qualifiers, so there's no way to write this condition 10406 // right now; we just diagnose on everything. 10407 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 10408 DiagOccured = true; 10409 }); 10410 if (DiagOccured) 10411 D.setInvalidType(); 10412 } 10413 } 10414 10415 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 10416 /// the well-formedness of the constructor declarator @p D with type @p 10417 /// R. If there are any errors in the declarator, this routine will 10418 /// emit diagnostics and set the invalid bit to true. In any case, the type 10419 /// will be updated to reflect a well-formed type for the constructor and 10420 /// returned. 10421 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 10422 StorageClass &SC) { 10423 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 10424 10425 // C++ [class.ctor]p3: 10426 // A constructor shall not be virtual (10.3) or static (9.4). A 10427 // constructor can be invoked for a const, volatile or const 10428 // volatile object. A constructor shall not be declared const, 10429 // volatile, or const volatile (9.3.2). 10430 if (isVirtual) { 10431 if (!D.isInvalidType()) 10432 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10433 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 10434 << SourceRange(D.getIdentifierLoc()); 10435 D.setInvalidType(); 10436 } 10437 if (SC == SC_Static) { 10438 if (!D.isInvalidType()) 10439 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10440 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10441 << SourceRange(D.getIdentifierLoc()); 10442 D.setInvalidType(); 10443 SC = SC_None; 10444 } 10445 10446 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10447 diagnoseIgnoredQualifiers( 10448 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 10449 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 10450 D.getDeclSpec().getRestrictSpecLoc(), 10451 D.getDeclSpec().getAtomicSpecLoc()); 10452 D.setInvalidType(); 10453 } 10454 10455 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 10456 10457 // C++0x [class.ctor]p4: 10458 // A constructor shall not be declared with a ref-qualifier. 10459 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10460 if (FTI.hasRefQualifier()) { 10461 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 10462 << FTI.RefQualifierIsLValueRef 10463 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10464 D.setInvalidType(); 10465 } 10466 10467 // Rebuild the function type "R" without any type qualifiers (in 10468 // case any of the errors above fired) and with "void" as the 10469 // return type, since constructors don't have return types. 10470 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10471 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 10472 return R; 10473 10474 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10475 EPI.TypeQuals = Qualifiers(); 10476 EPI.RefQualifier = RQ_None; 10477 10478 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 10479 } 10480 10481 /// CheckConstructor - Checks a fully-formed constructor for 10482 /// well-formedness, issuing any diagnostics required. Returns true if 10483 /// the constructor declarator is invalid. 10484 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 10485 CXXRecordDecl *ClassDecl 10486 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 10487 if (!ClassDecl) 10488 return Constructor->setInvalidDecl(); 10489 10490 // C++ [class.copy]p3: 10491 // A declaration of a constructor for a class X is ill-formed if 10492 // its first parameter is of type (optionally cv-qualified) X and 10493 // either there are no other parameters or else all other 10494 // parameters have default arguments. 10495 if (!Constructor->isInvalidDecl() && 10496 Constructor->hasOneParamOrDefaultArgs() && 10497 Constructor->getTemplateSpecializationKind() != 10498 TSK_ImplicitInstantiation) { 10499 QualType ParamType = Constructor->getParamDecl(0)->getType(); 10500 QualType ClassTy = Context.getTagDeclType(ClassDecl); 10501 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 10502 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 10503 const char *ConstRef 10504 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 10505 : " const &"; 10506 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 10507 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 10508 10509 // FIXME: Rather that making the constructor invalid, we should endeavor 10510 // to fix the type. 10511 Constructor->setInvalidDecl(); 10512 } 10513 } 10514 } 10515 10516 /// CheckDestructor - Checks a fully-formed destructor definition for 10517 /// well-formedness, issuing any diagnostics required. Returns true 10518 /// on error. 10519 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 10520 CXXRecordDecl *RD = Destructor->getParent(); 10521 10522 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 10523 SourceLocation Loc; 10524 10525 if (!Destructor->isImplicit()) 10526 Loc = Destructor->getLocation(); 10527 else 10528 Loc = RD->getLocation(); 10529 10530 // If we have a virtual destructor, look up the deallocation function 10531 if (FunctionDecl *OperatorDelete = 10532 FindDeallocationFunctionForDestructor(Loc, RD)) { 10533 Expr *ThisArg = nullptr; 10534 10535 // If the notional 'delete this' expression requires a non-trivial 10536 // conversion from 'this' to the type of a destroying operator delete's 10537 // first parameter, perform that conversion now. 10538 if (OperatorDelete->isDestroyingOperatorDelete()) { 10539 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 10540 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 10541 // C++ [class.dtor]p13: 10542 // ... as if for the expression 'delete this' appearing in a 10543 // non-virtual destructor of the destructor's class. 10544 ContextRAII SwitchContext(*this, Destructor); 10545 ExprResult This = 10546 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 10547 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 10548 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 10549 if (This.isInvalid()) { 10550 // FIXME: Register this as a context note so that it comes out 10551 // in the right order. 10552 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 10553 return true; 10554 } 10555 ThisArg = This.get(); 10556 } 10557 } 10558 10559 DiagnoseUseOfDecl(OperatorDelete, Loc); 10560 MarkFunctionReferenced(Loc, OperatorDelete); 10561 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 10562 } 10563 } 10564 10565 return false; 10566 } 10567 10568 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 10569 /// the well-formednes of the destructor declarator @p D with type @p 10570 /// R. If there are any errors in the declarator, this routine will 10571 /// emit diagnostics and set the declarator to invalid. Even if this happens, 10572 /// will be updated to reflect a well-formed type for the destructor and 10573 /// returned. 10574 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 10575 StorageClass& SC) { 10576 // C++ [class.dtor]p1: 10577 // [...] A typedef-name that names a class is a class-name 10578 // (7.1.3); however, a typedef-name that names a class shall not 10579 // be used as the identifier in the declarator for a destructor 10580 // declaration. 10581 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 10582 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 10583 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10584 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 10585 else if (const TemplateSpecializationType *TST = 10586 DeclaratorType->getAs<TemplateSpecializationType>()) 10587 if (TST->isTypeAlias()) 10588 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10589 << DeclaratorType << 1; 10590 10591 // C++ [class.dtor]p2: 10592 // A destructor is used to destroy objects of its class type. A 10593 // destructor takes no parameters, and no return type can be 10594 // specified for it (not even void). The address of a destructor 10595 // shall not be taken. A destructor shall not be static. A 10596 // destructor can be invoked for a const, volatile or const 10597 // volatile object. A destructor shall not be declared const, 10598 // volatile or const volatile (9.3.2). 10599 if (SC == SC_Static) { 10600 if (!D.isInvalidType()) 10601 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 10602 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10603 << SourceRange(D.getIdentifierLoc()) 10604 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10605 10606 SC = SC_None; 10607 } 10608 if (!D.isInvalidType()) { 10609 // Destructors don't have return types, but the parser will 10610 // happily parse something like: 10611 // 10612 // class X { 10613 // float ~X(); 10614 // }; 10615 // 10616 // The return type will be eliminated later. 10617 if (D.getDeclSpec().hasTypeSpecifier()) 10618 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 10619 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 10620 << SourceRange(D.getIdentifierLoc()); 10621 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10622 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 10623 SourceLocation(), 10624 D.getDeclSpec().getConstSpecLoc(), 10625 D.getDeclSpec().getVolatileSpecLoc(), 10626 D.getDeclSpec().getRestrictSpecLoc(), 10627 D.getDeclSpec().getAtomicSpecLoc()); 10628 D.setInvalidType(); 10629 } 10630 } 10631 10632 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 10633 10634 // C++0x [class.dtor]p2: 10635 // A destructor shall not be declared with a ref-qualifier. 10636 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10637 if (FTI.hasRefQualifier()) { 10638 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 10639 << FTI.RefQualifierIsLValueRef 10640 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10641 D.setInvalidType(); 10642 } 10643 10644 // Make sure we don't have any parameters. 10645 if (FTIHasNonVoidParameters(FTI)) { 10646 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 10647 10648 // Delete the parameters. 10649 FTI.freeParams(); 10650 D.setInvalidType(); 10651 } 10652 10653 // Make sure the destructor isn't variadic. 10654 if (FTI.isVariadic) { 10655 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10656 D.setInvalidType(); 10657 } 10658 10659 // Rebuild the function type "R" without any type qualifiers or 10660 // parameters (in case any of the errors above fired) and with 10661 // "void" as the return type, since destructors don't have return 10662 // types. 10663 if (!D.isInvalidType()) 10664 return R; 10665 10666 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10667 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10668 EPI.Variadic = false; 10669 EPI.TypeQuals = Qualifiers(); 10670 EPI.RefQualifier = RQ_None; 10671 return Context.getFunctionType(Context.VoidTy, None, EPI); 10672 } 10673 10674 static void extendLeft(SourceRange &R, SourceRange Before) { 10675 if (Before.isInvalid()) 10676 return; 10677 R.setBegin(Before.getBegin()); 10678 if (R.getEnd().isInvalid()) 10679 R.setEnd(Before.getEnd()); 10680 } 10681 10682 static void extendRight(SourceRange &R, SourceRange After) { 10683 if (After.isInvalid()) 10684 return; 10685 if (R.getBegin().isInvalid()) 10686 R.setBegin(After.getBegin()); 10687 R.setEnd(After.getEnd()); 10688 } 10689 10690 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10691 /// well-formednes of the conversion function declarator @p D with 10692 /// type @p R. If there are any errors in the declarator, this routine 10693 /// will emit diagnostics and return true. Otherwise, it will return 10694 /// false. Either way, the type @p R will be updated to reflect a 10695 /// well-formed type for the conversion operator. 10696 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10697 StorageClass& SC) { 10698 // C++ [class.conv.fct]p1: 10699 // Neither parameter types nor return type can be specified. The 10700 // type of a conversion function (8.3.5) is "function taking no 10701 // parameter returning conversion-type-id." 10702 if (SC == SC_Static) { 10703 if (!D.isInvalidType()) 10704 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10705 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10706 << D.getName().getSourceRange(); 10707 D.setInvalidType(); 10708 SC = SC_None; 10709 } 10710 10711 TypeSourceInfo *ConvTSI = nullptr; 10712 QualType ConvType = 10713 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10714 10715 const DeclSpec &DS = D.getDeclSpec(); 10716 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10717 // Conversion functions don't have return types, but the parser will 10718 // happily parse something like: 10719 // 10720 // class X { 10721 // float operator bool(); 10722 // }; 10723 // 10724 // The return type will be changed later anyway. 10725 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10726 << SourceRange(DS.getTypeSpecTypeLoc()) 10727 << SourceRange(D.getIdentifierLoc()); 10728 D.setInvalidType(); 10729 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10730 // It's also plausible that the user writes type qualifiers in the wrong 10731 // place, such as: 10732 // struct S { const operator int(); }; 10733 // FIXME: we could provide a fixit to move the qualifiers onto the 10734 // conversion type. 10735 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10736 << SourceRange(D.getIdentifierLoc()) << 0; 10737 D.setInvalidType(); 10738 } 10739 10740 const auto *Proto = R->castAs<FunctionProtoType>(); 10741 10742 // Make sure we don't have any parameters. 10743 if (Proto->getNumParams() > 0) { 10744 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10745 10746 // Delete the parameters. 10747 D.getFunctionTypeInfo().freeParams(); 10748 D.setInvalidType(); 10749 } else if (Proto->isVariadic()) { 10750 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10751 D.setInvalidType(); 10752 } 10753 10754 // Diagnose "&operator bool()" and other such nonsense. This 10755 // is actually a gcc extension which we don't support. 10756 if (Proto->getReturnType() != ConvType) { 10757 bool NeedsTypedef = false; 10758 SourceRange Before, After; 10759 10760 // Walk the chunks and extract information on them for our diagnostic. 10761 bool PastFunctionChunk = false; 10762 for (auto &Chunk : D.type_objects()) { 10763 switch (Chunk.Kind) { 10764 case DeclaratorChunk::Function: 10765 if (!PastFunctionChunk) { 10766 if (Chunk.Fun.HasTrailingReturnType) { 10767 TypeSourceInfo *TRT = nullptr; 10768 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10769 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10770 } 10771 PastFunctionChunk = true; 10772 break; 10773 } 10774 LLVM_FALLTHROUGH; 10775 case DeclaratorChunk::Array: 10776 NeedsTypedef = true; 10777 extendRight(After, Chunk.getSourceRange()); 10778 break; 10779 10780 case DeclaratorChunk::Pointer: 10781 case DeclaratorChunk::BlockPointer: 10782 case DeclaratorChunk::Reference: 10783 case DeclaratorChunk::MemberPointer: 10784 case DeclaratorChunk::Pipe: 10785 extendLeft(Before, Chunk.getSourceRange()); 10786 break; 10787 10788 case DeclaratorChunk::Paren: 10789 extendLeft(Before, Chunk.Loc); 10790 extendRight(After, Chunk.EndLoc); 10791 break; 10792 } 10793 } 10794 10795 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10796 After.isValid() ? After.getBegin() : 10797 D.getIdentifierLoc(); 10798 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10799 DB << Before << After; 10800 10801 if (!NeedsTypedef) { 10802 DB << /*don't need a typedef*/0; 10803 10804 // If we can provide a correct fix-it hint, do so. 10805 if (After.isInvalid() && ConvTSI) { 10806 SourceLocation InsertLoc = 10807 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10808 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10809 << FixItHint::CreateInsertionFromRange( 10810 InsertLoc, CharSourceRange::getTokenRange(Before)) 10811 << FixItHint::CreateRemoval(Before); 10812 } 10813 } else if (!Proto->getReturnType()->isDependentType()) { 10814 DB << /*typedef*/1 << Proto->getReturnType(); 10815 } else if (getLangOpts().CPlusPlus11) { 10816 DB << /*alias template*/2 << Proto->getReturnType(); 10817 } else { 10818 DB << /*might not be fixable*/3; 10819 } 10820 10821 // Recover by incorporating the other type chunks into the result type. 10822 // Note, this does *not* change the name of the function. This is compatible 10823 // with the GCC extension: 10824 // struct S { &operator int(); } s; 10825 // int &r = s.operator int(); // ok in GCC 10826 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10827 ConvType = Proto->getReturnType(); 10828 } 10829 10830 // C++ [class.conv.fct]p4: 10831 // The conversion-type-id shall not represent a function type nor 10832 // an array type. 10833 if (ConvType->isArrayType()) { 10834 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10835 ConvType = Context.getPointerType(ConvType); 10836 D.setInvalidType(); 10837 } else if (ConvType->isFunctionType()) { 10838 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10839 ConvType = Context.getPointerType(ConvType); 10840 D.setInvalidType(); 10841 } 10842 10843 // Rebuild the function type "R" without any parameters (in case any 10844 // of the errors above fired) and with the conversion type as the 10845 // return type. 10846 if (D.isInvalidType()) 10847 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 10848 10849 // C++0x explicit conversion operators. 10850 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20) 10851 Diag(DS.getExplicitSpecLoc(), 10852 getLangOpts().CPlusPlus11 10853 ? diag::warn_cxx98_compat_explicit_conversion_functions 10854 : diag::ext_explicit_conversion_functions) 10855 << SourceRange(DS.getExplicitSpecRange()); 10856 } 10857 10858 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 10859 /// the declaration of the given C++ conversion function. This routine 10860 /// is responsible for recording the conversion function in the C++ 10861 /// class, if possible. 10862 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 10863 assert(Conversion && "Expected to receive a conversion function declaration"); 10864 10865 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 10866 10867 // Make sure we aren't redeclaring the conversion function. 10868 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 10869 // C++ [class.conv.fct]p1: 10870 // [...] A conversion function is never used to convert a 10871 // (possibly cv-qualified) object to the (possibly cv-qualified) 10872 // same object type (or a reference to it), to a (possibly 10873 // cv-qualified) base class of that type (or a reference to it), 10874 // or to (possibly cv-qualified) void. 10875 QualType ClassType 10876 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10877 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 10878 ConvType = ConvTypeRef->getPointeeType(); 10879 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 10880 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 10881 /* Suppress diagnostics for instantiations. */; 10882 else if (Conversion->size_overridden_methods() != 0) 10883 /* Suppress diagnostics for overriding virtual function in a base class. */; 10884 else if (ConvType->isRecordType()) { 10885 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 10886 if (ConvType == ClassType) 10887 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 10888 << ClassType; 10889 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 10890 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 10891 << ClassType << ConvType; 10892 } else if (ConvType->isVoidType()) { 10893 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 10894 << ClassType << ConvType; 10895 } 10896 10897 if (FunctionTemplateDecl *ConversionTemplate 10898 = Conversion->getDescribedFunctionTemplate()) 10899 return ConversionTemplate; 10900 10901 return Conversion; 10902 } 10903 10904 namespace { 10905 /// Utility class to accumulate and print a diagnostic listing the invalid 10906 /// specifier(s) on a declaration. 10907 struct BadSpecifierDiagnoser { 10908 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10909 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10910 ~BadSpecifierDiagnoser() { 10911 Diagnostic << Specifiers; 10912 } 10913 10914 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10915 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10916 } 10917 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10918 return check(SpecLoc, 10919 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10920 } 10921 void check(SourceLocation SpecLoc, const char *Spec) { 10922 if (SpecLoc.isInvalid()) return; 10923 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10924 if (!Specifiers.empty()) Specifiers += " "; 10925 Specifiers += Spec; 10926 } 10927 10928 Sema &S; 10929 Sema::SemaDiagnosticBuilder Diagnostic; 10930 std::string Specifiers; 10931 }; 10932 } 10933 10934 /// Check the validity of a declarator that we parsed for a deduction-guide. 10935 /// These aren't actually declarators in the grammar, so we need to check that 10936 /// the user didn't specify any pieces that are not part of the deduction-guide 10937 /// grammar. 10938 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10939 StorageClass &SC) { 10940 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10941 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10942 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 10943 10944 // C++ [temp.deduct.guide]p3: 10945 // A deduction-gide shall be declared in the same scope as the 10946 // corresponding class template. 10947 if (!CurContext->getRedeclContext()->Equals( 10948 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10949 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10950 << GuidedTemplateDecl; 10951 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10952 } 10953 10954 auto &DS = D.getMutableDeclSpec(); 10955 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10956 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10957 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10958 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10959 BadSpecifierDiagnoser Diagnoser( 10960 *this, D.getIdentifierLoc(), 10961 diag::err_deduction_guide_invalid_specifier); 10962 10963 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10964 DS.ClearStorageClassSpecs(); 10965 SC = SC_None; 10966 10967 // 'explicit' is permitted. 10968 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10969 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10970 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10971 DS.ClearConstexprSpec(); 10972 10973 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10974 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10975 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10976 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10977 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10978 DS.ClearTypeQualifiers(); 10979 10980 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 10981 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 10982 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 10983 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 10984 DS.ClearTypeSpecType(); 10985 } 10986 10987 if (D.isInvalidType()) 10988 return; 10989 10990 // Check the declarator is simple enough. 10991 bool FoundFunction = false; 10992 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 10993 if (Chunk.Kind == DeclaratorChunk::Paren) 10994 continue; 10995 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 10996 Diag(D.getDeclSpec().getBeginLoc(), 10997 diag::err_deduction_guide_with_complex_decl) 10998 << D.getSourceRange(); 10999 break; 11000 } 11001 if (!Chunk.Fun.hasTrailingReturnType()) { 11002 Diag(D.getName().getBeginLoc(), 11003 diag::err_deduction_guide_no_trailing_return_type); 11004 break; 11005 } 11006 11007 // Check that the return type is written as a specialization of 11008 // the template specified as the deduction-guide's name. 11009 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 11010 TypeSourceInfo *TSI = nullptr; 11011 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 11012 assert(TSI && "deduction guide has valid type but invalid return type?"); 11013 bool AcceptableReturnType = false; 11014 bool MightInstantiateToSpecialization = false; 11015 if (auto RetTST = 11016 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 11017 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 11018 bool TemplateMatches = 11019 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 11020 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 11021 AcceptableReturnType = true; 11022 else { 11023 // This could still instantiate to the right type, unless we know it 11024 // names the wrong class template. 11025 auto *TD = SpecifiedName.getAsTemplateDecl(); 11026 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 11027 !TemplateMatches); 11028 } 11029 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 11030 MightInstantiateToSpecialization = true; 11031 } 11032 11033 if (!AcceptableReturnType) { 11034 Diag(TSI->getTypeLoc().getBeginLoc(), 11035 diag::err_deduction_guide_bad_trailing_return_type) 11036 << GuidedTemplate << TSI->getType() 11037 << MightInstantiateToSpecialization 11038 << TSI->getTypeLoc().getSourceRange(); 11039 } 11040 11041 // Keep going to check that we don't have any inner declarator pieces (we 11042 // could still have a function returning a pointer to a function). 11043 FoundFunction = true; 11044 } 11045 11046 if (D.isFunctionDefinition()) 11047 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 11048 } 11049 11050 //===----------------------------------------------------------------------===// 11051 // Namespace Handling 11052 //===----------------------------------------------------------------------===// 11053 11054 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 11055 /// reopened. 11056 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 11057 SourceLocation Loc, 11058 IdentifierInfo *II, bool *IsInline, 11059 NamespaceDecl *PrevNS) { 11060 assert(*IsInline != PrevNS->isInline()); 11061 11062 // 'inline' must appear on the original definition, but not necessarily 11063 // on all extension definitions, so the note should point to the first 11064 // definition to avoid confusion. 11065 PrevNS = PrevNS->getFirstDecl(); 11066 11067 if (PrevNS->isInline()) 11068 // The user probably just forgot the 'inline', so suggest that it 11069 // be added back. 11070 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 11071 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 11072 else 11073 S.Diag(Loc, diag::err_inline_namespace_mismatch); 11074 11075 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 11076 *IsInline = PrevNS->isInline(); 11077 } 11078 11079 /// ActOnStartNamespaceDef - This is called at the start of a namespace 11080 /// definition. 11081 Decl *Sema::ActOnStartNamespaceDef( 11082 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 11083 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 11084 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 11085 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 11086 // For anonymous namespace, take the location of the left brace. 11087 SourceLocation Loc = II ? IdentLoc : LBrace; 11088 bool IsInline = InlineLoc.isValid(); 11089 bool IsInvalid = false; 11090 bool IsStd = false; 11091 bool AddToKnown = false; 11092 Scope *DeclRegionScope = NamespcScope->getParent(); 11093 11094 NamespaceDecl *PrevNS = nullptr; 11095 if (II) { 11096 // C++ [namespace.def]p2: 11097 // The identifier in an original-namespace-definition shall not 11098 // have been previously defined in the declarative region in 11099 // which the original-namespace-definition appears. The 11100 // identifier in an original-namespace-definition is the name of 11101 // the namespace. Subsequently in that declarative region, it is 11102 // treated as an original-namespace-name. 11103 // 11104 // Since namespace names are unique in their scope, and we don't 11105 // look through using directives, just look for any ordinary names 11106 // as if by qualified name lookup. 11107 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 11108 ForExternalRedeclaration); 11109 LookupQualifiedName(R, CurContext->getRedeclContext()); 11110 NamedDecl *PrevDecl = 11111 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 11112 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 11113 11114 if (PrevNS) { 11115 // This is an extended namespace definition. 11116 if (IsInline != PrevNS->isInline()) 11117 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 11118 &IsInline, PrevNS); 11119 } else if (PrevDecl) { 11120 // This is an invalid name redefinition. 11121 Diag(Loc, diag::err_redefinition_different_kind) 11122 << II; 11123 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11124 IsInvalid = true; 11125 // Continue on to push Namespc as current DeclContext and return it. 11126 } else if (II->isStr("std") && 11127 CurContext->getRedeclContext()->isTranslationUnit()) { 11128 // This is the first "real" definition of the namespace "std", so update 11129 // our cache of the "std" namespace to point at this definition. 11130 PrevNS = getStdNamespace(); 11131 IsStd = true; 11132 AddToKnown = !IsInline; 11133 } else { 11134 // We've seen this namespace for the first time. 11135 AddToKnown = !IsInline; 11136 } 11137 } else { 11138 // Anonymous namespaces. 11139 11140 // Determine whether the parent already has an anonymous namespace. 11141 DeclContext *Parent = CurContext->getRedeclContext(); 11142 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11143 PrevNS = TU->getAnonymousNamespace(); 11144 } else { 11145 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 11146 PrevNS = ND->getAnonymousNamespace(); 11147 } 11148 11149 if (PrevNS && IsInline != PrevNS->isInline()) 11150 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 11151 &IsInline, PrevNS); 11152 } 11153 11154 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 11155 StartLoc, Loc, II, PrevNS); 11156 if (IsInvalid) 11157 Namespc->setInvalidDecl(); 11158 11159 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 11160 AddPragmaAttributes(DeclRegionScope, Namespc); 11161 11162 // FIXME: Should we be merging attributes? 11163 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 11164 PushNamespaceVisibilityAttr(Attr, Loc); 11165 11166 if (IsStd) 11167 StdNamespace = Namespc; 11168 if (AddToKnown) 11169 KnownNamespaces[Namespc] = false; 11170 11171 if (II) { 11172 PushOnScopeChains(Namespc, DeclRegionScope); 11173 } else { 11174 // Link the anonymous namespace into its parent. 11175 DeclContext *Parent = CurContext->getRedeclContext(); 11176 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11177 TU->setAnonymousNamespace(Namespc); 11178 } else { 11179 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 11180 } 11181 11182 CurContext->addDecl(Namespc); 11183 11184 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 11185 // behaves as if it were replaced by 11186 // namespace unique { /* empty body */ } 11187 // using namespace unique; 11188 // namespace unique { namespace-body } 11189 // where all occurrences of 'unique' in a translation unit are 11190 // replaced by the same identifier and this identifier differs 11191 // from all other identifiers in the entire program. 11192 11193 // We just create the namespace with an empty name and then add an 11194 // implicit using declaration, just like the standard suggests. 11195 // 11196 // CodeGen enforces the "universally unique" aspect by giving all 11197 // declarations semantically contained within an anonymous 11198 // namespace internal linkage. 11199 11200 if (!PrevNS) { 11201 UD = UsingDirectiveDecl::Create(Context, Parent, 11202 /* 'using' */ LBrace, 11203 /* 'namespace' */ SourceLocation(), 11204 /* qualifier */ NestedNameSpecifierLoc(), 11205 /* identifier */ SourceLocation(), 11206 Namespc, 11207 /* Ancestor */ Parent); 11208 UD->setImplicit(); 11209 Parent->addDecl(UD); 11210 } 11211 } 11212 11213 ActOnDocumentableDecl(Namespc); 11214 11215 // Although we could have an invalid decl (i.e. the namespace name is a 11216 // redefinition), push it as current DeclContext and try to continue parsing. 11217 // FIXME: We should be able to push Namespc here, so that the each DeclContext 11218 // for the namespace has the declarations that showed up in that particular 11219 // namespace definition. 11220 PushDeclContext(NamespcScope, Namespc); 11221 return Namespc; 11222 } 11223 11224 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 11225 /// is a namespace alias, returns the namespace it points to. 11226 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 11227 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 11228 return AD->getNamespace(); 11229 return dyn_cast_or_null<NamespaceDecl>(D); 11230 } 11231 11232 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 11233 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 11234 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 11235 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 11236 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 11237 Namespc->setRBraceLoc(RBrace); 11238 PopDeclContext(); 11239 if (Namespc->hasAttr<VisibilityAttr>()) 11240 PopPragmaVisibility(true, RBrace); 11241 // If this namespace contains an export-declaration, export it now. 11242 if (DeferredExportedNamespaces.erase(Namespc)) 11243 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 11244 } 11245 11246 CXXRecordDecl *Sema::getStdBadAlloc() const { 11247 return cast_or_null<CXXRecordDecl>( 11248 StdBadAlloc.get(Context.getExternalSource())); 11249 } 11250 11251 EnumDecl *Sema::getStdAlignValT() const { 11252 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 11253 } 11254 11255 NamespaceDecl *Sema::getStdNamespace() const { 11256 return cast_or_null<NamespaceDecl>( 11257 StdNamespace.get(Context.getExternalSource())); 11258 } 11259 11260 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 11261 if (!StdExperimentalNamespaceCache) { 11262 if (auto Std = getStdNamespace()) { 11263 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 11264 SourceLocation(), LookupNamespaceName); 11265 if (!LookupQualifiedName(Result, Std) || 11266 !(StdExperimentalNamespaceCache = 11267 Result.getAsSingle<NamespaceDecl>())) 11268 Result.suppressDiagnostics(); 11269 } 11270 } 11271 return StdExperimentalNamespaceCache; 11272 } 11273 11274 namespace { 11275 11276 enum UnsupportedSTLSelect { 11277 USS_InvalidMember, 11278 USS_MissingMember, 11279 USS_NonTrivial, 11280 USS_Other 11281 }; 11282 11283 struct InvalidSTLDiagnoser { 11284 Sema &S; 11285 SourceLocation Loc; 11286 QualType TyForDiags; 11287 11288 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 11289 const VarDecl *VD = nullptr) { 11290 { 11291 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 11292 << TyForDiags << ((int)Sel); 11293 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 11294 assert(!Name.empty()); 11295 D << Name; 11296 } 11297 } 11298 if (Sel == USS_InvalidMember) { 11299 S.Diag(VD->getLocation(), diag::note_var_declared_here) 11300 << VD << VD->getSourceRange(); 11301 } 11302 return QualType(); 11303 } 11304 }; 11305 } // namespace 11306 11307 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 11308 SourceLocation Loc, 11309 ComparisonCategoryUsage Usage) { 11310 assert(getLangOpts().CPlusPlus && 11311 "Looking for comparison category type outside of C++."); 11312 11313 // Use an elaborated type for diagnostics which has a name containing the 11314 // prepended 'std' namespace but not any inline namespace names. 11315 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 11316 auto *NNS = 11317 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 11318 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 11319 }; 11320 11321 // Check if we've already successfully checked the comparison category type 11322 // before. If so, skip checking it again. 11323 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 11324 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 11325 // The only thing we need to check is that the type has a reachable 11326 // definition in the current context. 11327 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11328 return QualType(); 11329 11330 return Info->getType(); 11331 } 11332 11333 // If lookup failed 11334 if (!Info) { 11335 std::string NameForDiags = "std::"; 11336 NameForDiags += ComparisonCategories::getCategoryString(Kind); 11337 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 11338 << NameForDiags << (int)Usage; 11339 return QualType(); 11340 } 11341 11342 assert(Info->Kind == Kind); 11343 assert(Info->Record); 11344 11345 // Update the Record decl in case we encountered a forward declaration on our 11346 // first pass. FIXME: This is a bit of a hack. 11347 if (Info->Record->hasDefinition()) 11348 Info->Record = Info->Record->getDefinition(); 11349 11350 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11351 return QualType(); 11352 11353 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 11354 11355 if (!Info->Record->isTriviallyCopyable()) 11356 return UnsupportedSTLError(USS_NonTrivial); 11357 11358 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 11359 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 11360 // Tolerate empty base classes. 11361 if (Base->isEmpty()) 11362 continue; 11363 // Reject STL implementations which have at least one non-empty base. 11364 return UnsupportedSTLError(); 11365 } 11366 11367 // Check that the STL has implemented the types using a single integer field. 11368 // This expectation allows better codegen for builtin operators. We require: 11369 // (1) The class has exactly one field. 11370 // (2) The field is an integral or enumeration type. 11371 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 11372 if (std::distance(FIt, FEnd) != 1 || 11373 !FIt->getType()->isIntegralOrEnumerationType()) { 11374 return UnsupportedSTLError(); 11375 } 11376 11377 // Build each of the require values and store them in Info. 11378 for (ComparisonCategoryResult CCR : 11379 ComparisonCategories::getPossibleResultsForType(Kind)) { 11380 StringRef MemName = ComparisonCategories::getResultString(CCR); 11381 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 11382 11383 if (!ValInfo) 11384 return UnsupportedSTLError(USS_MissingMember, MemName); 11385 11386 VarDecl *VD = ValInfo->VD; 11387 assert(VD && "should not be null!"); 11388 11389 // Attempt to diagnose reasons why the STL definition of this type 11390 // might be foobar, including it failing to be a constant expression. 11391 // TODO Handle more ways the lookup or result can be invalid. 11392 if (!VD->isStaticDataMember() || 11393 !VD->isUsableInConstantExpressions(Context)) 11394 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 11395 11396 // Attempt to evaluate the var decl as a constant expression and extract 11397 // the value of its first field as a ICE. If this fails, the STL 11398 // implementation is not supported. 11399 if (!ValInfo->hasValidIntValue()) 11400 return UnsupportedSTLError(); 11401 11402 MarkVariableReferenced(Loc, VD); 11403 } 11404 11405 // We've successfully built the required types and expressions. Update 11406 // the cache and return the newly cached value. 11407 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 11408 return Info->getType(); 11409 } 11410 11411 /// Retrieve the special "std" namespace, which may require us to 11412 /// implicitly define the namespace. 11413 NamespaceDecl *Sema::getOrCreateStdNamespace() { 11414 if (!StdNamespace) { 11415 // The "std" namespace has not yet been defined, so build one implicitly. 11416 StdNamespace = NamespaceDecl::Create(Context, 11417 Context.getTranslationUnitDecl(), 11418 /*Inline=*/false, 11419 SourceLocation(), SourceLocation(), 11420 &PP.getIdentifierTable().get("std"), 11421 /*PrevDecl=*/nullptr); 11422 getStdNamespace()->setImplicit(true); 11423 } 11424 11425 return getStdNamespace(); 11426 } 11427 11428 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 11429 assert(getLangOpts().CPlusPlus && 11430 "Looking for std::initializer_list outside of C++."); 11431 11432 // We're looking for implicit instantiations of 11433 // template <typename E> class std::initializer_list. 11434 11435 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 11436 return false; 11437 11438 ClassTemplateDecl *Template = nullptr; 11439 const TemplateArgument *Arguments = nullptr; 11440 11441 if (const RecordType *RT = Ty->getAs<RecordType>()) { 11442 11443 ClassTemplateSpecializationDecl *Specialization = 11444 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 11445 if (!Specialization) 11446 return false; 11447 11448 Template = Specialization->getSpecializedTemplate(); 11449 Arguments = Specialization->getTemplateArgs().data(); 11450 } else if (const TemplateSpecializationType *TST = 11451 Ty->getAs<TemplateSpecializationType>()) { 11452 Template = dyn_cast_or_null<ClassTemplateDecl>( 11453 TST->getTemplateName().getAsTemplateDecl()); 11454 Arguments = TST->getArgs(); 11455 } 11456 if (!Template) 11457 return false; 11458 11459 if (!StdInitializerList) { 11460 // Haven't recognized std::initializer_list yet, maybe this is it. 11461 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 11462 if (TemplateClass->getIdentifier() != 11463 &PP.getIdentifierTable().get("initializer_list") || 11464 !getStdNamespace()->InEnclosingNamespaceSetOf( 11465 TemplateClass->getDeclContext())) 11466 return false; 11467 // This is a template called std::initializer_list, but is it the right 11468 // template? 11469 TemplateParameterList *Params = Template->getTemplateParameters(); 11470 if (Params->getMinRequiredArguments() != 1) 11471 return false; 11472 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 11473 return false; 11474 11475 // It's the right template. 11476 StdInitializerList = Template; 11477 } 11478 11479 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 11480 return false; 11481 11482 // This is an instance of std::initializer_list. Find the argument type. 11483 if (Element) 11484 *Element = Arguments[0].getAsType(); 11485 return true; 11486 } 11487 11488 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 11489 NamespaceDecl *Std = S.getStdNamespace(); 11490 if (!Std) { 11491 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11492 return nullptr; 11493 } 11494 11495 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 11496 Loc, Sema::LookupOrdinaryName); 11497 if (!S.LookupQualifiedName(Result, Std)) { 11498 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11499 return nullptr; 11500 } 11501 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 11502 if (!Template) { 11503 Result.suppressDiagnostics(); 11504 // We found something weird. Complain about the first thing we found. 11505 NamedDecl *Found = *Result.begin(); 11506 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 11507 return nullptr; 11508 } 11509 11510 // We found some template called std::initializer_list. Now verify that it's 11511 // correct. 11512 TemplateParameterList *Params = Template->getTemplateParameters(); 11513 if (Params->getMinRequiredArguments() != 1 || 11514 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 11515 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 11516 return nullptr; 11517 } 11518 11519 return Template; 11520 } 11521 11522 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 11523 if (!StdInitializerList) { 11524 StdInitializerList = LookupStdInitializerList(*this, Loc); 11525 if (!StdInitializerList) 11526 return QualType(); 11527 } 11528 11529 TemplateArgumentListInfo Args(Loc, Loc); 11530 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 11531 Context.getTrivialTypeSourceInfo(Element, 11532 Loc))); 11533 return Context.getCanonicalType( 11534 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 11535 } 11536 11537 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 11538 // C++ [dcl.init.list]p2: 11539 // A constructor is an initializer-list constructor if its first parameter 11540 // is of type std::initializer_list<E> or reference to possibly cv-qualified 11541 // std::initializer_list<E> for some type E, and either there are no other 11542 // parameters or else all other parameters have default arguments. 11543 if (!Ctor->hasOneParamOrDefaultArgs()) 11544 return false; 11545 11546 QualType ArgType = Ctor->getParamDecl(0)->getType(); 11547 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 11548 ArgType = RT->getPointeeType().getUnqualifiedType(); 11549 11550 return isStdInitializerList(ArgType, nullptr); 11551 } 11552 11553 /// Determine whether a using statement is in a context where it will be 11554 /// apply in all contexts. 11555 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 11556 switch (CurContext->getDeclKind()) { 11557 case Decl::TranslationUnit: 11558 return true; 11559 case Decl::LinkageSpec: 11560 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 11561 default: 11562 return false; 11563 } 11564 } 11565 11566 namespace { 11567 11568 // Callback to only accept typo corrections that are namespaces. 11569 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 11570 public: 11571 bool ValidateCandidate(const TypoCorrection &candidate) override { 11572 if (NamedDecl *ND = candidate.getCorrectionDecl()) 11573 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 11574 return false; 11575 } 11576 11577 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11578 return std::make_unique<NamespaceValidatorCCC>(*this); 11579 } 11580 }; 11581 11582 } 11583 11584 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 11585 CXXScopeSpec &SS, 11586 SourceLocation IdentLoc, 11587 IdentifierInfo *Ident) { 11588 R.clear(); 11589 NamespaceValidatorCCC CCC{}; 11590 if (TypoCorrection Corrected = 11591 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 11592 Sema::CTK_ErrorRecovery)) { 11593 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 11594 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 11595 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 11596 Ident->getName().equals(CorrectedStr); 11597 S.diagnoseTypo(Corrected, 11598 S.PDiag(diag::err_using_directive_member_suggest) 11599 << Ident << DC << DroppedSpecifier << SS.getRange(), 11600 S.PDiag(diag::note_namespace_defined_here)); 11601 } else { 11602 S.diagnoseTypo(Corrected, 11603 S.PDiag(diag::err_using_directive_suggest) << Ident, 11604 S.PDiag(diag::note_namespace_defined_here)); 11605 } 11606 R.addDecl(Corrected.getFoundDecl()); 11607 return true; 11608 } 11609 return false; 11610 } 11611 11612 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 11613 SourceLocation NamespcLoc, CXXScopeSpec &SS, 11614 SourceLocation IdentLoc, 11615 IdentifierInfo *NamespcName, 11616 const ParsedAttributesView &AttrList) { 11617 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11618 assert(NamespcName && "Invalid NamespcName."); 11619 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 11620 11621 // This can only happen along a recovery path. 11622 while (S->isTemplateParamScope()) 11623 S = S->getParent(); 11624 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11625 11626 UsingDirectiveDecl *UDir = nullptr; 11627 NestedNameSpecifier *Qualifier = nullptr; 11628 if (SS.isSet()) 11629 Qualifier = SS.getScopeRep(); 11630 11631 // Lookup namespace name. 11632 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 11633 LookupParsedName(R, S, &SS); 11634 if (R.isAmbiguous()) 11635 return nullptr; 11636 11637 if (R.empty()) { 11638 R.clear(); 11639 // Allow "using namespace std;" or "using namespace ::std;" even if 11640 // "std" hasn't been defined yet, for GCC compatibility. 11641 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11642 NamespcName->isStr("std")) { 11643 Diag(IdentLoc, diag::ext_using_undefined_std); 11644 R.addDecl(getOrCreateStdNamespace()); 11645 R.resolveKind(); 11646 } 11647 // Otherwise, attempt typo correction. 11648 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11649 } 11650 11651 if (!R.empty()) { 11652 NamedDecl *Named = R.getRepresentativeDecl(); 11653 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11654 assert(NS && "expected namespace decl"); 11655 11656 // The use of a nested name specifier may trigger deprecation warnings. 11657 DiagnoseUseOfDecl(Named, IdentLoc); 11658 11659 // C++ [namespace.udir]p1: 11660 // A using-directive specifies that the names in the nominated 11661 // namespace can be used in the scope in which the 11662 // using-directive appears after the using-directive. During 11663 // unqualified name lookup (3.4.1), the names appear as if they 11664 // were declared in the nearest enclosing namespace which 11665 // contains both the using-directive and the nominated 11666 // namespace. [Note: in this context, "contains" means "contains 11667 // directly or indirectly". ] 11668 11669 // Find enclosing context containing both using-directive and 11670 // nominated namespace. 11671 DeclContext *CommonAncestor = NS; 11672 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11673 CommonAncestor = CommonAncestor->getParent(); 11674 11675 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11676 SS.getWithLocInContext(Context), 11677 IdentLoc, Named, CommonAncestor); 11678 11679 if (IsUsingDirectiveInToplevelContext(CurContext) && 11680 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11681 Diag(IdentLoc, diag::warn_using_directive_in_header); 11682 } 11683 11684 PushUsingDirective(S, UDir); 11685 } else { 11686 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11687 } 11688 11689 if (UDir) 11690 ProcessDeclAttributeList(S, UDir, AttrList); 11691 11692 return UDir; 11693 } 11694 11695 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11696 // If the scope has an associated entity and the using directive is at 11697 // namespace or translation unit scope, add the UsingDirectiveDecl into 11698 // its lookup structure so qualified name lookup can find it. 11699 DeclContext *Ctx = S->getEntity(); 11700 if (Ctx && !Ctx->isFunctionOrMethod()) 11701 Ctx->addDecl(UDir); 11702 else 11703 // Otherwise, it is at block scope. The using-directives will affect lookup 11704 // only to the end of the scope. 11705 S->PushUsingDirective(UDir); 11706 } 11707 11708 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11709 SourceLocation UsingLoc, 11710 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11711 UnqualifiedId &Name, 11712 SourceLocation EllipsisLoc, 11713 const ParsedAttributesView &AttrList) { 11714 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11715 11716 if (SS.isEmpty()) { 11717 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11718 return nullptr; 11719 } 11720 11721 switch (Name.getKind()) { 11722 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11723 case UnqualifiedIdKind::IK_Identifier: 11724 case UnqualifiedIdKind::IK_OperatorFunctionId: 11725 case UnqualifiedIdKind::IK_LiteralOperatorId: 11726 case UnqualifiedIdKind::IK_ConversionFunctionId: 11727 break; 11728 11729 case UnqualifiedIdKind::IK_ConstructorName: 11730 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11731 // C++11 inheriting constructors. 11732 Diag(Name.getBeginLoc(), 11733 getLangOpts().CPlusPlus11 11734 ? diag::warn_cxx98_compat_using_decl_constructor 11735 : diag::err_using_decl_constructor) 11736 << SS.getRange(); 11737 11738 if (getLangOpts().CPlusPlus11) break; 11739 11740 return nullptr; 11741 11742 case UnqualifiedIdKind::IK_DestructorName: 11743 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11744 return nullptr; 11745 11746 case UnqualifiedIdKind::IK_TemplateId: 11747 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11748 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11749 return nullptr; 11750 11751 case UnqualifiedIdKind::IK_DeductionGuideName: 11752 llvm_unreachable("cannot parse qualified deduction guide name"); 11753 } 11754 11755 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11756 DeclarationName TargetName = TargetNameInfo.getName(); 11757 if (!TargetName) 11758 return nullptr; 11759 11760 // Warn about access declarations. 11761 if (UsingLoc.isInvalid()) { 11762 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11763 ? diag::err_access_decl 11764 : diag::warn_access_decl_deprecated) 11765 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11766 } 11767 11768 if (EllipsisLoc.isInvalid()) { 11769 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11770 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11771 return nullptr; 11772 } else { 11773 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11774 !TargetNameInfo.containsUnexpandedParameterPack()) { 11775 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11776 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11777 EllipsisLoc = SourceLocation(); 11778 } 11779 } 11780 11781 NamedDecl *UD = 11782 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 11783 SS, TargetNameInfo, EllipsisLoc, AttrList, 11784 /*IsInstantiation*/ false, 11785 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists)); 11786 if (UD) 11787 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11788 11789 return UD; 11790 } 11791 11792 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 11793 SourceLocation UsingLoc, 11794 SourceLocation EnumLoc, 11795 const DeclSpec &DS) { 11796 switch (DS.getTypeSpecType()) { 11797 case DeclSpec::TST_error: 11798 // This will already have been diagnosed 11799 return nullptr; 11800 11801 case DeclSpec::TST_enum: 11802 break; 11803 11804 case DeclSpec::TST_typename: 11805 Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent); 11806 return nullptr; 11807 11808 default: 11809 llvm_unreachable("unexpected DeclSpec type"); 11810 } 11811 11812 // As with enum-decls, we ignore attributes for now. 11813 auto *Enum = cast<EnumDecl>(DS.getRepAsDecl()); 11814 if (auto *Def = Enum->getDefinition()) 11815 Enum = Def; 11816 11817 auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, 11818 DS.getTypeSpecTypeNameLoc(), Enum); 11819 if (UD) 11820 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11821 11822 return UD; 11823 } 11824 11825 /// Determine whether a using declaration considers the given 11826 /// declarations as "equivalent", e.g., if they are redeclarations of 11827 /// the same entity or are both typedefs of the same type. 11828 static bool 11829 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11830 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11831 return true; 11832 11833 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11834 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11835 return Context.hasSameType(TD1->getUnderlyingType(), 11836 TD2->getUnderlyingType()); 11837 11838 // Two using_if_exists using-declarations are equivalent if both are 11839 // unresolved. 11840 if (isa<UnresolvedUsingIfExistsDecl>(D1) && 11841 isa<UnresolvedUsingIfExistsDecl>(D2)) 11842 return true; 11843 11844 return false; 11845 } 11846 11847 11848 /// Determines whether to create a using shadow decl for a particular 11849 /// decl, given the set of decls existing prior to this using lookup. 11850 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig, 11851 const LookupResult &Previous, 11852 UsingShadowDecl *&PrevShadow) { 11853 // Diagnose finding a decl which is not from a base class of the 11854 // current class. We do this now because there are cases where this 11855 // function will silently decide not to build a shadow decl, which 11856 // will pre-empt further diagnostics. 11857 // 11858 // We don't need to do this in C++11 because we do the check once on 11859 // the qualifier. 11860 // 11861 // FIXME: diagnose the following if we care enough: 11862 // struct A { int foo; }; 11863 // struct B : A { using A::foo; }; 11864 // template <class T> struct C : A {}; 11865 // template <class T> struct D : C<T> { using B::foo; } // <--- 11866 // This is invalid (during instantiation) in C++03 because B::foo 11867 // resolves to the using decl in B, which is not a base class of D<T>. 11868 // We can't diagnose it immediately because C<T> is an unknown 11869 // specialization. The UsingShadowDecl in D<T> then points directly 11870 // to A::foo, which will look well-formed when we instantiate. 11871 // The right solution is to not collapse the shadow-decl chain. 11872 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) 11873 if (auto *Using = dyn_cast<UsingDecl>(BUD)) { 11874 DeclContext *OrigDC = Orig->getDeclContext(); 11875 11876 // Handle enums and anonymous structs. 11877 if (isa<EnumDecl>(OrigDC)) 11878 OrigDC = OrigDC->getParent(); 11879 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 11880 while (OrigRec->isAnonymousStructOrUnion()) 11881 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 11882 11883 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 11884 if (OrigDC == CurContext) { 11885 Diag(Using->getLocation(), 11886 diag::err_using_decl_nested_name_specifier_is_current_class) 11887 << Using->getQualifierLoc().getSourceRange(); 11888 Diag(Orig->getLocation(), diag::note_using_decl_target); 11889 Using->setInvalidDecl(); 11890 return true; 11891 } 11892 11893 Diag(Using->getQualifierLoc().getBeginLoc(), 11894 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11895 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext) 11896 << Using->getQualifierLoc().getSourceRange(); 11897 Diag(Orig->getLocation(), diag::note_using_decl_target); 11898 Using->setInvalidDecl(); 11899 return true; 11900 } 11901 } 11902 11903 if (Previous.empty()) return false; 11904 11905 NamedDecl *Target = Orig; 11906 if (isa<UsingShadowDecl>(Target)) 11907 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11908 11909 // If the target happens to be one of the previous declarations, we 11910 // don't have a conflict. 11911 // 11912 // FIXME: but we might be increasing its access, in which case we 11913 // should redeclare it. 11914 NamedDecl *NonTag = nullptr, *Tag = nullptr; 11915 bool FoundEquivalentDecl = false; 11916 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 11917 I != E; ++I) { 11918 NamedDecl *D = (*I)->getUnderlyingDecl(); 11919 // We can have UsingDecls in our Previous results because we use the same 11920 // LookupResult for checking whether the UsingDecl itself is a valid 11921 // redeclaration. 11922 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D)) 11923 continue; 11924 11925 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 11926 // C++ [class.mem]p19: 11927 // If T is the name of a class, then [every named member other than 11928 // a non-static data member] shall have a name different from T 11929 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11930 !isa<IndirectFieldDecl>(Target) && 11931 !isa<UnresolvedUsingValueDecl>(Target) && 11932 DiagnoseClassNameShadow( 11933 CurContext, 11934 DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation()))) 11935 return true; 11936 } 11937 11938 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11939 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11940 PrevShadow = Shadow; 11941 FoundEquivalentDecl = true; 11942 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11943 // We don't conflict with an existing using shadow decl of an equivalent 11944 // declaration, but we're not a redeclaration of it. 11945 FoundEquivalentDecl = true; 11946 } 11947 11948 if (isVisible(D)) 11949 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11950 } 11951 11952 if (FoundEquivalentDecl) 11953 return false; 11954 11955 // Always emit a diagnostic for a mismatch between an unresolved 11956 // using_if_exists and a resolved using declaration in either direction. 11957 if (isa<UnresolvedUsingIfExistsDecl>(Target) != 11958 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) { 11959 if (!NonTag && !Tag) 11960 return false; 11961 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11962 Diag(Target->getLocation(), diag::note_using_decl_target); 11963 Diag((NonTag ? NonTag : Tag)->getLocation(), 11964 diag::note_using_decl_conflict); 11965 BUD->setInvalidDecl(); 11966 return true; 11967 } 11968 11969 if (FunctionDecl *FD = Target->getAsFunction()) { 11970 NamedDecl *OldDecl = nullptr; 11971 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11972 /*IsForUsingDecl*/ true)) { 11973 case Ovl_Overload: 11974 return false; 11975 11976 case Ovl_NonFunction: 11977 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11978 break; 11979 11980 // We found a decl with the exact signature. 11981 case Ovl_Match: 11982 // If we're in a record, we want to hide the target, so we 11983 // return true (without a diagnostic) to tell the caller not to 11984 // build a shadow decl. 11985 if (CurContext->isRecord()) 11986 return true; 11987 11988 // If we're not in a record, this is an error. 11989 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11990 break; 11991 } 11992 11993 Diag(Target->getLocation(), diag::note_using_decl_target); 11994 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 11995 BUD->setInvalidDecl(); 11996 return true; 11997 } 11998 11999 // Target is not a function. 12000 12001 if (isa<TagDecl>(Target)) { 12002 // No conflict between a tag and a non-tag. 12003 if (!Tag) return false; 12004 12005 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 12006 Diag(Target->getLocation(), diag::note_using_decl_target); 12007 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 12008 BUD->setInvalidDecl(); 12009 return true; 12010 } 12011 12012 // No conflict between a tag and a non-tag. 12013 if (!NonTag) return false; 12014 12015 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 12016 Diag(Target->getLocation(), diag::note_using_decl_target); 12017 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 12018 BUD->setInvalidDecl(); 12019 return true; 12020 } 12021 12022 /// Determine whether a direct base class is a virtual base class. 12023 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 12024 if (!Derived->getNumVBases()) 12025 return false; 12026 for (auto &B : Derived->bases()) 12027 if (B.getType()->getAsCXXRecordDecl() == Base) 12028 return B.isVirtual(); 12029 llvm_unreachable("not a direct base class"); 12030 } 12031 12032 /// Builds a shadow declaration corresponding to a 'using' declaration. 12033 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, 12034 NamedDecl *Orig, 12035 UsingShadowDecl *PrevDecl) { 12036 // If we resolved to another shadow declaration, just coalesce them. 12037 NamedDecl *Target = Orig; 12038 if (isa<UsingShadowDecl>(Target)) { 12039 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 12040 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 12041 } 12042 12043 NamedDecl *NonTemplateTarget = Target; 12044 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 12045 NonTemplateTarget = TargetTD->getTemplatedDecl(); 12046 12047 UsingShadowDecl *Shadow; 12048 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 12049 UsingDecl *Using = cast<UsingDecl>(BUD); 12050 bool IsVirtualBase = 12051 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 12052 Using->getQualifier()->getAsRecordDecl()); 12053 Shadow = ConstructorUsingShadowDecl::Create( 12054 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase); 12055 } else { 12056 Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(), 12057 Target->getDeclName(), BUD, Target); 12058 } 12059 BUD->addShadowDecl(Shadow); 12060 12061 Shadow->setAccess(BUD->getAccess()); 12062 if (Orig->isInvalidDecl() || BUD->isInvalidDecl()) 12063 Shadow->setInvalidDecl(); 12064 12065 Shadow->setPreviousDecl(PrevDecl); 12066 12067 if (S) 12068 PushOnScopeChains(Shadow, S); 12069 else 12070 CurContext->addDecl(Shadow); 12071 12072 12073 return Shadow; 12074 } 12075 12076 /// Hides a using shadow declaration. This is required by the current 12077 /// using-decl implementation when a resolvable using declaration in a 12078 /// class is followed by a declaration which would hide or override 12079 /// one or more of the using decl's targets; for example: 12080 /// 12081 /// struct Base { void foo(int); }; 12082 /// struct Derived : Base { 12083 /// using Base::foo; 12084 /// void foo(int); 12085 /// }; 12086 /// 12087 /// The governing language is C++03 [namespace.udecl]p12: 12088 /// 12089 /// When a using-declaration brings names from a base class into a 12090 /// derived class scope, member functions in the derived class 12091 /// override and/or hide member functions with the same name and 12092 /// parameter types in a base class (rather than conflicting). 12093 /// 12094 /// There are two ways to implement this: 12095 /// (1) optimistically create shadow decls when they're not hidden 12096 /// by existing declarations, or 12097 /// (2) don't create any shadow decls (or at least don't make them 12098 /// visible) until we've fully parsed/instantiated the class. 12099 /// The problem with (1) is that we might have to retroactively remove 12100 /// a shadow decl, which requires several O(n) operations because the 12101 /// decl structures are (very reasonably) not designed for removal. 12102 /// (2) avoids this but is very fiddly and phase-dependent. 12103 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 12104 if (Shadow->getDeclName().getNameKind() == 12105 DeclarationName::CXXConversionFunctionName) 12106 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 12107 12108 // Remove it from the DeclContext... 12109 Shadow->getDeclContext()->removeDecl(Shadow); 12110 12111 // ...and the scope, if applicable... 12112 if (S) { 12113 S->RemoveDecl(Shadow); 12114 IdResolver.RemoveDecl(Shadow); 12115 } 12116 12117 // ...and the using decl. 12118 Shadow->getIntroducer()->removeShadowDecl(Shadow); 12119 12120 // TODO: complain somehow if Shadow was used. It shouldn't 12121 // be possible for this to happen, because...? 12122 } 12123 12124 /// Find the base specifier for a base class with the given type. 12125 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 12126 QualType DesiredBase, 12127 bool &AnyDependentBases) { 12128 // Check whether the named type is a direct base class. 12129 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 12130 .getUnqualifiedType(); 12131 for (auto &Base : Derived->bases()) { 12132 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 12133 if (CanonicalDesiredBase == BaseType) 12134 return &Base; 12135 if (BaseType->isDependentType()) 12136 AnyDependentBases = true; 12137 } 12138 return nullptr; 12139 } 12140 12141 namespace { 12142 class UsingValidatorCCC final : public CorrectionCandidateCallback { 12143 public: 12144 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 12145 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 12146 : HasTypenameKeyword(HasTypenameKeyword), 12147 IsInstantiation(IsInstantiation), OldNNS(NNS), 12148 RequireMemberOf(RequireMemberOf) {} 12149 12150 bool ValidateCandidate(const TypoCorrection &Candidate) override { 12151 NamedDecl *ND = Candidate.getCorrectionDecl(); 12152 12153 // Keywords are not valid here. 12154 if (!ND || isa<NamespaceDecl>(ND)) 12155 return false; 12156 12157 // Completely unqualified names are invalid for a 'using' declaration. 12158 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 12159 return false; 12160 12161 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 12162 // reject. 12163 12164 if (RequireMemberOf) { 12165 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 12166 if (FoundRecord && FoundRecord->isInjectedClassName()) { 12167 // No-one ever wants a using-declaration to name an injected-class-name 12168 // of a base class, unless they're declaring an inheriting constructor. 12169 ASTContext &Ctx = ND->getASTContext(); 12170 if (!Ctx.getLangOpts().CPlusPlus11) 12171 return false; 12172 QualType FoundType = Ctx.getRecordType(FoundRecord); 12173 12174 // Check that the injected-class-name is named as a member of its own 12175 // type; we don't want to suggest 'using Derived::Base;', since that 12176 // means something else. 12177 NestedNameSpecifier *Specifier = 12178 Candidate.WillReplaceSpecifier() 12179 ? Candidate.getCorrectionSpecifier() 12180 : OldNNS; 12181 if (!Specifier->getAsType() || 12182 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 12183 return false; 12184 12185 // Check that this inheriting constructor declaration actually names a 12186 // direct base class of the current class. 12187 bool AnyDependentBases = false; 12188 if (!findDirectBaseWithType(RequireMemberOf, 12189 Ctx.getRecordType(FoundRecord), 12190 AnyDependentBases) && 12191 !AnyDependentBases) 12192 return false; 12193 } else { 12194 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 12195 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 12196 return false; 12197 12198 // FIXME: Check that the base class member is accessible? 12199 } 12200 } else { 12201 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 12202 if (FoundRecord && FoundRecord->isInjectedClassName()) 12203 return false; 12204 } 12205 12206 if (isa<TypeDecl>(ND)) 12207 return HasTypenameKeyword || !IsInstantiation; 12208 12209 return !HasTypenameKeyword; 12210 } 12211 12212 std::unique_ptr<CorrectionCandidateCallback> clone() override { 12213 return std::make_unique<UsingValidatorCCC>(*this); 12214 } 12215 12216 private: 12217 bool HasTypenameKeyword; 12218 bool IsInstantiation; 12219 NestedNameSpecifier *OldNNS; 12220 CXXRecordDecl *RequireMemberOf; 12221 }; 12222 } // end anonymous namespace 12223 12224 /// Remove decls we can't actually see from a lookup being used to declare 12225 /// shadow using decls. 12226 /// 12227 /// \param S - The scope of the potential shadow decl 12228 /// \param Previous - The lookup of a potential shadow decl's name. 12229 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) { 12230 // It is really dumb that we have to do this. 12231 LookupResult::Filter F = Previous.makeFilter(); 12232 while (F.hasNext()) { 12233 NamedDecl *D = F.next(); 12234 if (!isDeclInScope(D, CurContext, S)) 12235 F.erase(); 12236 // If we found a local extern declaration that's not ordinarily visible, 12237 // and this declaration is being added to a non-block scope, ignore it. 12238 // We're only checking for scope conflicts here, not also for violations 12239 // of the linkage rules. 12240 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 12241 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 12242 F.erase(); 12243 } 12244 F.done(); 12245 } 12246 12247 /// Builds a using declaration. 12248 /// 12249 /// \param IsInstantiation - Whether this call arises from an 12250 /// instantiation of an unresolved using declaration. We treat 12251 /// the lookup differently for these declarations. 12252 NamedDecl *Sema::BuildUsingDeclaration( 12253 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 12254 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 12255 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 12256 const ParsedAttributesView &AttrList, bool IsInstantiation, 12257 bool IsUsingIfExists) { 12258 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 12259 SourceLocation IdentLoc = NameInfo.getLoc(); 12260 assert(IdentLoc.isValid() && "Invalid TargetName location."); 12261 12262 // FIXME: We ignore attributes for now. 12263 12264 // For an inheriting constructor declaration, the name of the using 12265 // declaration is the name of a constructor in this class, not in the 12266 // base class. 12267 DeclarationNameInfo UsingName = NameInfo; 12268 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 12269 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 12270 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12271 Context.getCanonicalType(Context.getRecordType(RD)))); 12272 12273 // Do the redeclaration lookup in the current scope. 12274 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 12275 ForVisibleRedeclaration); 12276 Previous.setHideTags(false); 12277 if (S) { 12278 LookupName(Previous, S); 12279 12280 FilterUsingLookup(S, Previous); 12281 } else { 12282 assert(IsInstantiation && "no scope in non-instantiation"); 12283 if (CurContext->isRecord()) 12284 LookupQualifiedName(Previous, CurContext); 12285 else { 12286 // No redeclaration check is needed here; in non-member contexts we 12287 // diagnosed all possible conflicts with other using-declarations when 12288 // building the template: 12289 // 12290 // For a dependent non-type using declaration, the only valid case is 12291 // if we instantiate to a single enumerator. We check for conflicts 12292 // between shadow declarations we introduce, and we check in the template 12293 // definition for conflicts between a non-type using declaration and any 12294 // other declaration, which together covers all cases. 12295 // 12296 // A dependent typename using declaration will never successfully 12297 // instantiate, since it will always name a class member, so we reject 12298 // that in the template definition. 12299 } 12300 } 12301 12302 // Check for invalid redeclarations. 12303 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 12304 SS, IdentLoc, Previous)) 12305 return nullptr; 12306 12307 // 'using_if_exists' doesn't make sense on an inherited constructor. 12308 if (IsUsingIfExists && UsingName.getName().getNameKind() == 12309 DeclarationName::CXXConstructorName) { 12310 Diag(UsingLoc, diag::err_using_if_exists_on_ctor); 12311 return nullptr; 12312 } 12313 12314 DeclContext *LookupContext = computeDeclContext(SS); 12315 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12316 if (!LookupContext || EllipsisLoc.isValid()) { 12317 NamedDecl *D; 12318 // Dependent scope, or an unexpanded pack 12319 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, 12320 SS, NameInfo, IdentLoc)) 12321 return nullptr; 12322 12323 if (HasTypenameKeyword) { 12324 // FIXME: not all declaration name kinds are legal here 12325 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 12326 UsingLoc, TypenameLoc, 12327 QualifierLoc, 12328 IdentLoc, NameInfo.getName(), 12329 EllipsisLoc); 12330 } else { 12331 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 12332 QualifierLoc, NameInfo, EllipsisLoc); 12333 } 12334 D->setAccess(AS); 12335 CurContext->addDecl(D); 12336 ProcessDeclAttributeList(S, D, AttrList); 12337 return D; 12338 } 12339 12340 auto Build = [&](bool Invalid) { 12341 UsingDecl *UD = 12342 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 12343 UsingName, HasTypenameKeyword); 12344 UD->setAccess(AS); 12345 CurContext->addDecl(UD); 12346 ProcessDeclAttributeList(S, UD, AttrList); 12347 UD->setInvalidDecl(Invalid); 12348 return UD; 12349 }; 12350 auto BuildInvalid = [&]{ return Build(true); }; 12351 auto BuildValid = [&]{ return Build(false); }; 12352 12353 if (RequireCompleteDeclContext(SS, LookupContext)) 12354 return BuildInvalid(); 12355 12356 // Look up the target name. 12357 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12358 12359 // Unlike most lookups, we don't always want to hide tag 12360 // declarations: tag names are visible through the using declaration 12361 // even if hidden by ordinary names, *except* in a dependent context 12362 // where they may be used by two-phase lookup. 12363 if (!IsInstantiation) 12364 R.setHideTags(false); 12365 12366 // For the purposes of this lookup, we have a base object type 12367 // equal to that of the current context. 12368 if (CurContext->isRecord()) { 12369 R.setBaseObjectType( 12370 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 12371 } 12372 12373 LookupQualifiedName(R, LookupContext); 12374 12375 // Validate the context, now we have a lookup 12376 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 12377 IdentLoc, &R)) 12378 return nullptr; 12379 12380 if (R.empty() && IsUsingIfExists) 12381 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc, 12382 UsingName.getName()), 12383 AS_public); 12384 12385 // Try to correct typos if possible. If constructor name lookup finds no 12386 // results, that means the named class has no explicit constructors, and we 12387 // suppressed declaring implicit ones (probably because it's dependent or 12388 // invalid). 12389 if (R.empty() && 12390 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 12391 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of 12392 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where 12393 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later. 12394 auto *II = NameInfo.getName().getAsIdentifierInfo(); 12395 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 12396 CurContext->isStdNamespace() && 12397 isa<TranslationUnitDecl>(LookupContext) && 12398 getSourceManager().isInSystemHeader(UsingLoc)) 12399 return nullptr; 12400 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 12401 dyn_cast<CXXRecordDecl>(CurContext)); 12402 if (TypoCorrection Corrected = 12403 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 12404 CTK_ErrorRecovery)) { 12405 // We reject candidates where DroppedSpecifier == true, hence the 12406 // literal '0' below. 12407 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 12408 << NameInfo.getName() << LookupContext << 0 12409 << SS.getRange()); 12410 12411 // If we picked a correction with no attached Decl we can't do anything 12412 // useful with it, bail out. 12413 NamedDecl *ND = Corrected.getCorrectionDecl(); 12414 if (!ND) 12415 return BuildInvalid(); 12416 12417 // If we corrected to an inheriting constructor, handle it as one. 12418 auto *RD = dyn_cast<CXXRecordDecl>(ND); 12419 if (RD && RD->isInjectedClassName()) { 12420 // The parent of the injected class name is the class itself. 12421 RD = cast<CXXRecordDecl>(RD->getParent()); 12422 12423 // Fix up the information we'll use to build the using declaration. 12424 if (Corrected.WillReplaceSpecifier()) { 12425 NestedNameSpecifierLocBuilder Builder; 12426 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 12427 QualifierLoc.getSourceRange()); 12428 QualifierLoc = Builder.getWithLocInContext(Context); 12429 } 12430 12431 // In this case, the name we introduce is the name of a derived class 12432 // constructor. 12433 auto *CurClass = cast<CXXRecordDecl>(CurContext); 12434 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12435 Context.getCanonicalType(Context.getRecordType(CurClass)))); 12436 UsingName.setNamedTypeInfo(nullptr); 12437 for (auto *Ctor : LookupConstructors(RD)) 12438 R.addDecl(Ctor); 12439 R.resolveKind(); 12440 } else { 12441 // FIXME: Pick up all the declarations if we found an overloaded 12442 // function. 12443 UsingName.setName(ND->getDeclName()); 12444 R.addDecl(ND); 12445 } 12446 } else { 12447 Diag(IdentLoc, diag::err_no_member) 12448 << NameInfo.getName() << LookupContext << SS.getRange(); 12449 return BuildInvalid(); 12450 } 12451 } 12452 12453 if (R.isAmbiguous()) 12454 return BuildInvalid(); 12455 12456 if (HasTypenameKeyword) { 12457 // If we asked for a typename and got a non-type decl, error out. 12458 if (!R.getAsSingle<TypeDecl>() && 12459 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) { 12460 Diag(IdentLoc, diag::err_using_typename_non_type); 12461 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12462 Diag((*I)->getUnderlyingDecl()->getLocation(), 12463 diag::note_using_decl_target); 12464 return BuildInvalid(); 12465 } 12466 } else { 12467 // If we asked for a non-typename and we got a type, error out, 12468 // but only if this is an instantiation of an unresolved using 12469 // decl. Otherwise just silently find the type name. 12470 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 12471 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 12472 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 12473 return BuildInvalid(); 12474 } 12475 } 12476 12477 // C++14 [namespace.udecl]p6: 12478 // A using-declaration shall not name a namespace. 12479 if (R.getAsSingle<NamespaceDecl>()) { 12480 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 12481 << SS.getRange(); 12482 return BuildInvalid(); 12483 } 12484 12485 UsingDecl *UD = BuildValid(); 12486 12487 // Some additional rules apply to inheriting constructors. 12488 if (UsingName.getName().getNameKind() == 12489 DeclarationName::CXXConstructorName) { 12490 // Suppress access diagnostics; the access check is instead performed at the 12491 // point of use for an inheriting constructor. 12492 R.suppressDiagnostics(); 12493 if (CheckInheritingConstructorUsingDecl(UD)) 12494 return UD; 12495 } 12496 12497 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 12498 UsingShadowDecl *PrevDecl = nullptr; 12499 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 12500 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 12501 } 12502 12503 return UD; 12504 } 12505 12506 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 12507 SourceLocation UsingLoc, 12508 SourceLocation EnumLoc, 12509 SourceLocation NameLoc, 12510 EnumDecl *ED) { 12511 bool Invalid = false; 12512 12513 if (CurContext->getRedeclContext()->isRecord()) { 12514 /// In class scope, check if this is a duplicate, for better a diagnostic. 12515 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc); 12516 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName, 12517 ForVisibleRedeclaration); 12518 12519 LookupName(Previous, S); 12520 12521 for (NamedDecl *D : Previous) 12522 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D)) 12523 if (UED->getEnumDecl() == ED) { 12524 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration) 12525 << SourceRange(EnumLoc, NameLoc); 12526 Diag(D->getLocation(), diag::note_using_enum_decl) << 1; 12527 Invalid = true; 12528 break; 12529 } 12530 } 12531 12532 if (RequireCompleteEnumDecl(ED, NameLoc)) 12533 Invalid = true; 12534 12535 UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc, 12536 EnumLoc, NameLoc, ED); 12537 UD->setAccess(AS); 12538 CurContext->addDecl(UD); 12539 12540 if (Invalid) { 12541 UD->setInvalidDecl(); 12542 return UD; 12543 } 12544 12545 // Create the shadow decls for each enumerator 12546 for (EnumConstantDecl *EC : ED->enumerators()) { 12547 UsingShadowDecl *PrevDecl = nullptr; 12548 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation()); 12549 LookupResult Previous(*this, DNI, LookupOrdinaryName, 12550 ForVisibleRedeclaration); 12551 LookupName(Previous, S); 12552 FilterUsingLookup(S, Previous); 12553 12554 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl)) 12555 BuildUsingShadowDecl(S, UD, EC, PrevDecl); 12556 } 12557 12558 return UD; 12559 } 12560 12561 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 12562 ArrayRef<NamedDecl *> Expansions) { 12563 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 12564 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 12565 isa<UsingPackDecl>(InstantiatedFrom)); 12566 12567 auto *UPD = 12568 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 12569 UPD->setAccess(InstantiatedFrom->getAccess()); 12570 CurContext->addDecl(UPD); 12571 return UPD; 12572 } 12573 12574 /// Additional checks for a using declaration referring to a constructor name. 12575 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 12576 assert(!UD->hasTypename() && "expecting a constructor name"); 12577 12578 const Type *SourceType = UD->getQualifier()->getAsType(); 12579 assert(SourceType && 12580 "Using decl naming constructor doesn't have type in scope spec."); 12581 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 12582 12583 // Check whether the named type is a direct base class. 12584 bool AnyDependentBases = false; 12585 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 12586 AnyDependentBases); 12587 if (!Base && !AnyDependentBases) { 12588 Diag(UD->getUsingLoc(), 12589 diag::err_using_decl_constructor_not_in_direct_base) 12590 << UD->getNameInfo().getSourceRange() 12591 << QualType(SourceType, 0) << TargetClass; 12592 UD->setInvalidDecl(); 12593 return true; 12594 } 12595 12596 if (Base) 12597 Base->setInheritConstructors(); 12598 12599 return false; 12600 } 12601 12602 /// Checks that the given using declaration is not an invalid 12603 /// redeclaration. Note that this is checking only for the using decl 12604 /// itself, not for any ill-formedness among the UsingShadowDecls. 12605 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 12606 bool HasTypenameKeyword, 12607 const CXXScopeSpec &SS, 12608 SourceLocation NameLoc, 12609 const LookupResult &Prev) { 12610 NestedNameSpecifier *Qual = SS.getScopeRep(); 12611 12612 // C++03 [namespace.udecl]p8: 12613 // C++0x [namespace.udecl]p10: 12614 // A using-declaration is a declaration and can therefore be used 12615 // repeatedly where (and only where) multiple declarations are 12616 // allowed. 12617 // 12618 // That's in non-member contexts. 12619 if (!CurContext->getRedeclContext()->isRecord()) { 12620 // A dependent qualifier outside a class can only ever resolve to an 12621 // enumeration type. Therefore it conflicts with any other non-type 12622 // declaration in the same scope. 12623 // FIXME: How should we check for dependent type-type conflicts at block 12624 // scope? 12625 if (Qual->isDependent() && !HasTypenameKeyword) { 12626 for (auto *D : Prev) { 12627 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 12628 bool OldCouldBeEnumerator = 12629 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 12630 Diag(NameLoc, 12631 OldCouldBeEnumerator ? diag::err_redefinition 12632 : diag::err_redefinition_different_kind) 12633 << Prev.getLookupName(); 12634 Diag(D->getLocation(), diag::note_previous_definition); 12635 return true; 12636 } 12637 } 12638 } 12639 return false; 12640 } 12641 12642 const NestedNameSpecifier *CNNS = 12643 Context.getCanonicalNestedNameSpecifier(Qual); 12644 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 12645 NamedDecl *D = *I; 12646 12647 bool DTypename; 12648 NestedNameSpecifier *DQual; 12649 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 12650 DTypename = UD->hasTypename(); 12651 DQual = UD->getQualifier(); 12652 } else if (UnresolvedUsingValueDecl *UD 12653 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 12654 DTypename = false; 12655 DQual = UD->getQualifier(); 12656 } else if (UnresolvedUsingTypenameDecl *UD 12657 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 12658 DTypename = true; 12659 DQual = UD->getQualifier(); 12660 } else continue; 12661 12662 // using decls differ if one says 'typename' and the other doesn't. 12663 // FIXME: non-dependent using decls? 12664 if (HasTypenameKeyword != DTypename) continue; 12665 12666 // using decls differ if they name different scopes (but note that 12667 // template instantiation can cause this check to trigger when it 12668 // didn't before instantiation). 12669 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual)) 12670 continue; 12671 12672 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 12673 Diag(D->getLocation(), diag::note_using_decl) << 1; 12674 return true; 12675 } 12676 12677 return false; 12678 } 12679 12680 /// Checks that the given nested-name qualifier used in a using decl 12681 /// in the current context is appropriately related to the current 12682 /// scope. If an error is found, diagnoses it and returns true. 12683 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the 12684 /// result of that lookup. UD is likewise nullptr, except when we have an 12685 /// already-populated UsingDecl whose shadow decls contain the same information 12686 /// (i.e. we're instantiating a UsingDecl with non-dependent scope). 12687 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, 12688 const CXXScopeSpec &SS, 12689 const DeclarationNameInfo &NameInfo, 12690 SourceLocation NameLoc, 12691 const LookupResult *R, const UsingDecl *UD) { 12692 DeclContext *NamedContext = computeDeclContext(SS); 12693 assert(bool(NamedContext) == (R || UD) && !(R && UD) && 12694 "resolvable context must have exactly one set of decls"); 12695 12696 // C++ 20 permits using an enumerator that does not have a class-hierarchy 12697 // relationship. 12698 bool Cxx20Enumerator = false; 12699 if (NamedContext) { 12700 EnumConstantDecl *EC = nullptr; 12701 if (R) 12702 EC = R->getAsSingle<EnumConstantDecl>(); 12703 else if (UD && UD->shadow_size() == 1) 12704 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl()); 12705 if (EC) 12706 Cxx20Enumerator = getLangOpts().CPlusPlus20; 12707 12708 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) { 12709 // C++14 [namespace.udecl]p7: 12710 // A using-declaration shall not name a scoped enumerator. 12711 // C++20 p1099 permits enumerators. 12712 if (EC && R && ED->isScoped()) 12713 Diag(SS.getBeginLoc(), 12714 getLangOpts().CPlusPlus20 12715 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator 12716 : diag::ext_using_decl_scoped_enumerator) 12717 << SS.getRange(); 12718 12719 // We want to consider the scope of the enumerator 12720 NamedContext = ED->getDeclContext(); 12721 } 12722 } 12723 12724 if (!CurContext->isRecord()) { 12725 // C++03 [namespace.udecl]p3: 12726 // C++0x [namespace.udecl]p8: 12727 // A using-declaration for a class member shall be a member-declaration. 12728 // C++20 [namespace.udecl]p7 12729 // ... other than an enumerator ... 12730 12731 // If we weren't able to compute a valid scope, it might validly be a 12732 // dependent class or enumeration scope. If we have a 'typename' keyword, 12733 // the scope must resolve to a class type. 12734 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord() 12735 : !HasTypename) 12736 return false; // OK 12737 12738 Diag(NameLoc, 12739 Cxx20Enumerator 12740 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator 12741 : diag::err_using_decl_can_not_refer_to_class_member) 12742 << SS.getRange(); 12743 12744 if (Cxx20Enumerator) 12745 return false; // OK 12746 12747 auto *RD = NamedContext 12748 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 12749 : nullptr; 12750 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) { 12751 // See if there's a helpful fixit 12752 12753 if (!R) { 12754 // We will have already diagnosed the problem on the template 12755 // definition, Maybe we should do so again? 12756 } else if (R->getAsSingle<TypeDecl>()) { 12757 if (getLangOpts().CPlusPlus11) { 12758 // Convert 'using X::Y;' to 'using Y = X::Y;'. 12759 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 12760 << 0 // alias declaration 12761 << FixItHint::CreateInsertion(SS.getBeginLoc(), 12762 NameInfo.getName().getAsString() + 12763 " = "); 12764 } else { 12765 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 12766 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 12767 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 12768 << 1 // typedef declaration 12769 << FixItHint::CreateReplacement(UsingLoc, "typedef") 12770 << FixItHint::CreateInsertion( 12771 InsertLoc, " " + NameInfo.getName().getAsString()); 12772 } 12773 } else if (R->getAsSingle<VarDecl>()) { 12774 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12775 // repeating the type of the static data member here. 12776 FixItHint FixIt; 12777 if (getLangOpts().CPlusPlus11) { 12778 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12779 FixIt = FixItHint::CreateReplacement( 12780 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 12781 } 12782 12783 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12784 << 2 // reference declaration 12785 << FixIt; 12786 } else if (R->getAsSingle<EnumConstantDecl>()) { 12787 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12788 // repeating the type of the enumeration here, and we can't do so if 12789 // the type is anonymous. 12790 FixItHint FixIt; 12791 if (getLangOpts().CPlusPlus11) { 12792 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12793 FixIt = FixItHint::CreateReplacement( 12794 UsingLoc, 12795 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 12796 } 12797 12798 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12799 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 12800 << FixIt; 12801 } 12802 } 12803 12804 return true; // Fail 12805 } 12806 12807 // If the named context is dependent, we can't decide much. 12808 if (!NamedContext) { 12809 // FIXME: in C++0x, we can diagnose if we can prove that the 12810 // nested-name-specifier does not refer to a base class, which is 12811 // still possible in some cases. 12812 12813 // Otherwise we have to conservatively report that things might be 12814 // okay. 12815 return false; 12816 } 12817 12818 // The current scope is a record. 12819 if (!NamedContext->isRecord()) { 12820 // Ideally this would point at the last name in the specifier, 12821 // but we don't have that level of source info. 12822 Diag(SS.getBeginLoc(), 12823 Cxx20Enumerator 12824 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator 12825 : diag::err_using_decl_nested_name_specifier_is_not_class) 12826 << SS.getScopeRep() << SS.getRange(); 12827 12828 if (Cxx20Enumerator) 12829 return false; // OK 12830 12831 return true; 12832 } 12833 12834 if (!NamedContext->isDependentContext() && 12835 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 12836 return true; 12837 12838 if (getLangOpts().CPlusPlus11) { 12839 // C++11 [namespace.udecl]p3: 12840 // In a using-declaration used as a member-declaration, the 12841 // nested-name-specifier shall name a base class of the class 12842 // being defined. 12843 12844 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 12845 cast<CXXRecordDecl>(NamedContext))) { 12846 12847 if (Cxx20Enumerator) { 12848 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator) 12849 << SS.getRange(); 12850 return false; 12851 } 12852 12853 if (CurContext == NamedContext) { 12854 Diag(SS.getBeginLoc(), 12855 diag::err_using_decl_nested_name_specifier_is_current_class) 12856 << SS.getRange(); 12857 return !getLangOpts().CPlusPlus20; 12858 } 12859 12860 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 12861 Diag(SS.getBeginLoc(), 12862 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12863 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext) 12864 << SS.getRange(); 12865 } 12866 return true; 12867 } 12868 12869 return false; 12870 } 12871 12872 // C++03 [namespace.udecl]p4: 12873 // A using-declaration used as a member-declaration shall refer 12874 // to a member of a base class of the class being defined [etc.]. 12875 12876 // Salient point: SS doesn't have to name a base class as long as 12877 // lookup only finds members from base classes. Therefore we can 12878 // diagnose here only if we can prove that that can't happen, 12879 // i.e. if the class hierarchies provably don't intersect. 12880 12881 // TODO: it would be nice if "definitely valid" results were cached 12882 // in the UsingDecl and UsingShadowDecl so that these checks didn't 12883 // need to be repeated. 12884 12885 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 12886 auto Collect = [&Bases](const CXXRecordDecl *Base) { 12887 Bases.insert(Base); 12888 return true; 12889 }; 12890 12891 // Collect all bases. Return false if we find a dependent base. 12892 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 12893 return false; 12894 12895 // Returns true if the base is dependent or is one of the accumulated base 12896 // classes. 12897 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 12898 return !Bases.count(Base); 12899 }; 12900 12901 // Return false if the class has a dependent base or if it or one 12902 // of its bases is present in the base set of the current context. 12903 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 12904 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 12905 return false; 12906 12907 Diag(SS.getRange().getBegin(), 12908 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12909 << SS.getScopeRep() 12910 << cast<CXXRecordDecl>(CurContext) 12911 << SS.getRange(); 12912 12913 return true; 12914 } 12915 12916 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 12917 MultiTemplateParamsArg TemplateParamLists, 12918 SourceLocation UsingLoc, UnqualifiedId &Name, 12919 const ParsedAttributesView &AttrList, 12920 TypeResult Type, Decl *DeclFromDeclSpec) { 12921 // Skip up to the relevant declaration scope. 12922 while (S->isTemplateParamScope()) 12923 S = S->getParent(); 12924 assert((S->getFlags() & Scope::DeclScope) && 12925 "got alias-declaration outside of declaration scope"); 12926 12927 if (Type.isInvalid()) 12928 return nullptr; 12929 12930 bool Invalid = false; 12931 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 12932 TypeSourceInfo *TInfo = nullptr; 12933 GetTypeFromParser(Type.get(), &TInfo); 12934 12935 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 12936 return nullptr; 12937 12938 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 12939 UPPC_DeclarationType)) { 12940 Invalid = true; 12941 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12942 TInfo->getTypeLoc().getBeginLoc()); 12943 } 12944 12945 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12946 TemplateParamLists.size() 12947 ? forRedeclarationInCurContext() 12948 : ForVisibleRedeclaration); 12949 LookupName(Previous, S); 12950 12951 // Warn about shadowing the name of a template parameter. 12952 if (Previous.isSingleResult() && 12953 Previous.getFoundDecl()->isTemplateParameter()) { 12954 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 12955 Previous.clear(); 12956 } 12957 12958 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 12959 "name in alias declaration must be an identifier"); 12960 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 12961 Name.StartLocation, 12962 Name.Identifier, TInfo); 12963 12964 NewTD->setAccess(AS); 12965 12966 if (Invalid) 12967 NewTD->setInvalidDecl(); 12968 12969 ProcessDeclAttributeList(S, NewTD, AttrList); 12970 AddPragmaAttributes(S, NewTD); 12971 12972 CheckTypedefForVariablyModifiedType(S, NewTD); 12973 Invalid |= NewTD->isInvalidDecl(); 12974 12975 bool Redeclaration = false; 12976 12977 NamedDecl *NewND; 12978 if (TemplateParamLists.size()) { 12979 TypeAliasTemplateDecl *OldDecl = nullptr; 12980 TemplateParameterList *OldTemplateParams = nullptr; 12981 12982 if (TemplateParamLists.size() != 1) { 12983 Diag(UsingLoc, diag::err_alias_template_extra_headers) 12984 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 12985 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 12986 } 12987 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 12988 12989 // Check that we can declare a template here. 12990 if (CheckTemplateDeclScope(S, TemplateParams)) 12991 return nullptr; 12992 12993 // Only consider previous declarations in the same scope. 12994 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 12995 /*ExplicitInstantiationOrSpecialization*/false); 12996 if (!Previous.empty()) { 12997 Redeclaration = true; 12998 12999 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 13000 if (!OldDecl && !Invalid) { 13001 Diag(UsingLoc, diag::err_redefinition_different_kind) 13002 << Name.Identifier; 13003 13004 NamedDecl *OldD = Previous.getRepresentativeDecl(); 13005 if (OldD->getLocation().isValid()) 13006 Diag(OldD->getLocation(), diag::note_previous_definition); 13007 13008 Invalid = true; 13009 } 13010 13011 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 13012 if (TemplateParameterListsAreEqual(TemplateParams, 13013 OldDecl->getTemplateParameters(), 13014 /*Complain=*/true, 13015 TPL_TemplateMatch)) 13016 OldTemplateParams = 13017 OldDecl->getMostRecentDecl()->getTemplateParameters(); 13018 else 13019 Invalid = true; 13020 13021 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 13022 if (!Invalid && 13023 !Context.hasSameType(OldTD->getUnderlyingType(), 13024 NewTD->getUnderlyingType())) { 13025 // FIXME: The C++0x standard does not clearly say this is ill-formed, 13026 // but we can't reasonably accept it. 13027 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 13028 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 13029 if (OldTD->getLocation().isValid()) 13030 Diag(OldTD->getLocation(), diag::note_previous_definition); 13031 Invalid = true; 13032 } 13033 } 13034 } 13035 13036 // Merge any previous default template arguments into our parameters, 13037 // and check the parameter list. 13038 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 13039 TPC_TypeAliasTemplate)) 13040 return nullptr; 13041 13042 TypeAliasTemplateDecl *NewDecl = 13043 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 13044 Name.Identifier, TemplateParams, 13045 NewTD); 13046 NewTD->setDescribedAliasTemplate(NewDecl); 13047 13048 NewDecl->setAccess(AS); 13049 13050 if (Invalid) 13051 NewDecl->setInvalidDecl(); 13052 else if (OldDecl) { 13053 NewDecl->setPreviousDecl(OldDecl); 13054 CheckRedeclarationInModule(NewDecl, OldDecl); 13055 } 13056 13057 NewND = NewDecl; 13058 } else { 13059 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 13060 setTagNameForLinkagePurposes(TD, NewTD); 13061 handleTagNumbering(TD, S); 13062 } 13063 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 13064 NewND = NewTD; 13065 } 13066 13067 PushOnScopeChains(NewND, S); 13068 ActOnDocumentableDecl(NewND); 13069 return NewND; 13070 } 13071 13072 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 13073 SourceLocation AliasLoc, 13074 IdentifierInfo *Alias, CXXScopeSpec &SS, 13075 SourceLocation IdentLoc, 13076 IdentifierInfo *Ident) { 13077 13078 // Lookup the namespace name. 13079 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 13080 LookupParsedName(R, S, &SS); 13081 13082 if (R.isAmbiguous()) 13083 return nullptr; 13084 13085 if (R.empty()) { 13086 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 13087 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 13088 return nullptr; 13089 } 13090 } 13091 assert(!R.isAmbiguous() && !R.empty()); 13092 NamedDecl *ND = R.getRepresentativeDecl(); 13093 13094 // Check if we have a previous declaration with the same name. 13095 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 13096 ForVisibleRedeclaration); 13097 LookupName(PrevR, S); 13098 13099 // Check we're not shadowing a template parameter. 13100 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 13101 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 13102 PrevR.clear(); 13103 } 13104 13105 // Filter out any other lookup result from an enclosing scope. 13106 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 13107 /*AllowInlineNamespace*/false); 13108 13109 // Find the previous declaration and check that we can redeclare it. 13110 NamespaceAliasDecl *Prev = nullptr; 13111 if (PrevR.isSingleResult()) { 13112 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 13113 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 13114 // We already have an alias with the same name that points to the same 13115 // namespace; check that it matches. 13116 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 13117 Prev = AD; 13118 } else if (isVisible(PrevDecl)) { 13119 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 13120 << Alias; 13121 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 13122 << AD->getNamespace(); 13123 return nullptr; 13124 } 13125 } else if (isVisible(PrevDecl)) { 13126 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 13127 ? diag::err_redefinition 13128 : diag::err_redefinition_different_kind; 13129 Diag(AliasLoc, DiagID) << Alias; 13130 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13131 return nullptr; 13132 } 13133 } 13134 13135 // The use of a nested name specifier may trigger deprecation warnings. 13136 DiagnoseUseOfDecl(ND, IdentLoc); 13137 13138 NamespaceAliasDecl *AliasDecl = 13139 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 13140 Alias, SS.getWithLocInContext(Context), 13141 IdentLoc, ND); 13142 if (Prev) 13143 AliasDecl->setPreviousDecl(Prev); 13144 13145 PushOnScopeChains(AliasDecl, S); 13146 return AliasDecl; 13147 } 13148 13149 namespace { 13150 struct SpecialMemberExceptionSpecInfo 13151 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 13152 SourceLocation Loc; 13153 Sema::ImplicitExceptionSpecification ExceptSpec; 13154 13155 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 13156 Sema::CXXSpecialMember CSM, 13157 Sema::InheritedConstructorInfo *ICI, 13158 SourceLocation Loc) 13159 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 13160 13161 bool visitBase(CXXBaseSpecifier *Base); 13162 bool visitField(FieldDecl *FD); 13163 13164 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 13165 unsigned Quals); 13166 13167 void visitSubobjectCall(Subobject Subobj, 13168 Sema::SpecialMemberOverloadResult SMOR); 13169 }; 13170 } 13171 13172 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 13173 auto *RT = Base->getType()->getAs<RecordType>(); 13174 if (!RT) 13175 return false; 13176 13177 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 13178 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 13179 if (auto *BaseCtor = SMOR.getMethod()) { 13180 visitSubobjectCall(Base, BaseCtor); 13181 return false; 13182 } 13183 13184 visitClassSubobject(BaseClass, Base, 0); 13185 return false; 13186 } 13187 13188 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 13189 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 13190 Expr *E = FD->getInClassInitializer(); 13191 if (!E) 13192 // FIXME: It's a little wasteful to build and throw away a 13193 // CXXDefaultInitExpr here. 13194 // FIXME: We should have a single context note pointing at Loc, and 13195 // this location should be MD->getLocation() instead, since that's 13196 // the location where we actually use the default init expression. 13197 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 13198 if (E) 13199 ExceptSpec.CalledExpr(E); 13200 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 13201 ->getAs<RecordType>()) { 13202 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 13203 FD->getType().getCVRQualifiers()); 13204 } 13205 return false; 13206 } 13207 13208 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 13209 Subobject Subobj, 13210 unsigned Quals) { 13211 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 13212 bool IsMutable = Field && Field->isMutable(); 13213 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 13214 } 13215 13216 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 13217 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 13218 // Note, if lookup fails, it doesn't matter what exception specification we 13219 // choose because the special member will be deleted. 13220 if (CXXMethodDecl *MD = SMOR.getMethod()) 13221 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 13222 } 13223 13224 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 13225 llvm::APSInt Result; 13226 ExprResult Converted = CheckConvertedConstantExpression( 13227 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 13228 ExplicitSpec.setExpr(Converted.get()); 13229 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 13230 ExplicitSpec.setKind(Result.getBoolValue() 13231 ? ExplicitSpecKind::ResolvedTrue 13232 : ExplicitSpecKind::ResolvedFalse); 13233 return true; 13234 } 13235 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 13236 return false; 13237 } 13238 13239 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 13240 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 13241 if (!ExplicitExpr->isTypeDependent()) 13242 tryResolveExplicitSpecifier(ES); 13243 return ES; 13244 } 13245 13246 static Sema::ImplicitExceptionSpecification 13247 ComputeDefaultedSpecialMemberExceptionSpec( 13248 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 13249 Sema::InheritedConstructorInfo *ICI) { 13250 ComputingExceptionSpec CES(S, MD, Loc); 13251 13252 CXXRecordDecl *ClassDecl = MD->getParent(); 13253 13254 // C++ [except.spec]p14: 13255 // An implicitly declared special member function (Clause 12) shall have an 13256 // exception-specification. [...] 13257 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 13258 if (ClassDecl->isInvalidDecl()) 13259 return Info.ExceptSpec; 13260 13261 // FIXME: If this diagnostic fires, we're probably missing a check for 13262 // attempting to resolve an exception specification before it's known 13263 // at a higher level. 13264 if (S.RequireCompleteType(MD->getLocation(), 13265 S.Context.getRecordType(ClassDecl), 13266 diag::err_exception_spec_incomplete_type)) 13267 return Info.ExceptSpec; 13268 13269 // C++1z [except.spec]p7: 13270 // [Look for exceptions thrown by] a constructor selected [...] to 13271 // initialize a potentially constructed subobject, 13272 // C++1z [except.spec]p8: 13273 // The exception specification for an implicitly-declared destructor, or a 13274 // destructor without a noexcept-specifier, is potentially-throwing if and 13275 // only if any of the destructors for any of its potentially constructed 13276 // subojects is potentially throwing. 13277 // FIXME: We respect the first rule but ignore the "potentially constructed" 13278 // in the second rule to resolve a core issue (no number yet) that would have 13279 // us reject: 13280 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 13281 // struct B : A {}; 13282 // struct C : B { void f(); }; 13283 // ... due to giving B::~B() a non-throwing exception specification. 13284 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 13285 : Info.VisitAllBases); 13286 13287 return Info.ExceptSpec; 13288 } 13289 13290 namespace { 13291 /// RAII object to register a special member as being currently declared. 13292 struct DeclaringSpecialMember { 13293 Sema &S; 13294 Sema::SpecialMemberDecl D; 13295 Sema::ContextRAII SavedContext; 13296 bool WasAlreadyBeingDeclared; 13297 13298 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 13299 : S(S), D(RD, CSM), SavedContext(S, RD) { 13300 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 13301 if (WasAlreadyBeingDeclared) 13302 // This almost never happens, but if it does, ensure that our cache 13303 // doesn't contain a stale result. 13304 S.SpecialMemberCache.clear(); 13305 else { 13306 // Register a note to be produced if we encounter an error while 13307 // declaring the special member. 13308 Sema::CodeSynthesisContext Ctx; 13309 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 13310 // FIXME: We don't have a location to use here. Using the class's 13311 // location maintains the fiction that we declare all special members 13312 // with the class, but (1) it's not clear that lying about that helps our 13313 // users understand what's going on, and (2) there may be outer contexts 13314 // on the stack (some of which are relevant) and printing them exposes 13315 // our lies. 13316 Ctx.PointOfInstantiation = RD->getLocation(); 13317 Ctx.Entity = RD; 13318 Ctx.SpecialMember = CSM; 13319 S.pushCodeSynthesisContext(Ctx); 13320 } 13321 } 13322 ~DeclaringSpecialMember() { 13323 if (!WasAlreadyBeingDeclared) { 13324 S.SpecialMembersBeingDeclared.erase(D); 13325 S.popCodeSynthesisContext(); 13326 } 13327 } 13328 13329 /// Are we already trying to declare this special member? 13330 bool isAlreadyBeingDeclared() const { 13331 return WasAlreadyBeingDeclared; 13332 } 13333 }; 13334 } 13335 13336 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 13337 // Look up any existing declarations, but don't trigger declaration of all 13338 // implicit special members with this name. 13339 DeclarationName Name = FD->getDeclName(); 13340 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 13341 ForExternalRedeclaration); 13342 for (auto *D : FD->getParent()->lookup(Name)) 13343 if (auto *Acceptable = R.getAcceptableDecl(D)) 13344 R.addDecl(Acceptable); 13345 R.resolveKind(); 13346 R.suppressDiagnostics(); 13347 13348 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 13349 } 13350 13351 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 13352 QualType ResultTy, 13353 ArrayRef<QualType> Args) { 13354 // Build an exception specification pointing back at this constructor. 13355 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 13356 13357 LangAS AS = getDefaultCXXMethodAddrSpace(); 13358 if (AS != LangAS::Default) { 13359 EPI.TypeQuals.addAddressSpace(AS); 13360 } 13361 13362 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 13363 SpecialMem->setType(QT); 13364 13365 // During template instantiation of implicit special member functions we need 13366 // a reliable TypeSourceInfo for the function prototype in order to allow 13367 // functions to be substituted. 13368 if (inTemplateInstantiation() && 13369 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) { 13370 TypeSourceInfo *TSI = 13371 Context.getTrivialTypeSourceInfo(SpecialMem->getType()); 13372 SpecialMem->setTypeSourceInfo(TSI); 13373 } 13374 } 13375 13376 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 13377 CXXRecordDecl *ClassDecl) { 13378 // C++ [class.ctor]p5: 13379 // A default constructor for a class X is a constructor of class X 13380 // that can be called without an argument. If there is no 13381 // user-declared constructor for class X, a default constructor is 13382 // implicitly declared. An implicitly-declared default constructor 13383 // is an inline public member of its class. 13384 assert(ClassDecl->needsImplicitDefaultConstructor() && 13385 "Should not build implicit default constructor!"); 13386 13387 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 13388 if (DSM.isAlreadyBeingDeclared()) 13389 return nullptr; 13390 13391 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13392 CXXDefaultConstructor, 13393 false); 13394 13395 // Create the actual constructor declaration. 13396 CanQualType ClassType 13397 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13398 SourceLocation ClassLoc = ClassDecl->getLocation(); 13399 DeclarationName Name 13400 = Context.DeclarationNames.getCXXConstructorName(ClassType); 13401 DeclarationNameInfo NameInfo(Name, ClassLoc); 13402 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 13403 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 13404 /*TInfo=*/nullptr, ExplicitSpecifier(), 13405 getCurFPFeatures().isFPConstrained(), 13406 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 13407 Constexpr ? ConstexprSpecKind::Constexpr 13408 : ConstexprSpecKind::Unspecified); 13409 DefaultCon->setAccess(AS_public); 13410 DefaultCon->setDefaulted(); 13411 13412 if (getLangOpts().CUDA) { 13413 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 13414 DefaultCon, 13415 /* ConstRHS */ false, 13416 /* Diagnose */ false); 13417 } 13418 13419 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 13420 13421 // We don't need to use SpecialMemberIsTrivial here; triviality for default 13422 // constructors is easy to compute. 13423 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 13424 13425 // Note that we have declared this constructor. 13426 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 13427 13428 Scope *S = getScopeForContext(ClassDecl); 13429 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 13430 13431 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 13432 SetDeclDeleted(DefaultCon, ClassLoc); 13433 13434 if (S) 13435 PushOnScopeChains(DefaultCon, S, false); 13436 ClassDecl->addDecl(DefaultCon); 13437 13438 return DefaultCon; 13439 } 13440 13441 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 13442 CXXConstructorDecl *Constructor) { 13443 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 13444 !Constructor->doesThisDeclarationHaveABody() && 13445 !Constructor->isDeleted()) && 13446 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 13447 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13448 return; 13449 13450 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13451 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 13452 13453 SynthesizedFunctionScope Scope(*this, Constructor); 13454 13455 // The exception specification is needed because we are defining the 13456 // function. 13457 ResolveExceptionSpec(CurrentLocation, 13458 Constructor->getType()->castAs<FunctionProtoType>()); 13459 MarkVTableUsed(CurrentLocation, ClassDecl); 13460 13461 // Add a context note for diagnostics produced after this point. 13462 Scope.addContextNote(CurrentLocation); 13463 13464 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 13465 Constructor->setInvalidDecl(); 13466 return; 13467 } 13468 13469 SourceLocation Loc = Constructor->getEndLoc().isValid() 13470 ? Constructor->getEndLoc() 13471 : Constructor->getLocation(); 13472 Constructor->setBody(new (Context) CompoundStmt(Loc)); 13473 Constructor->markUsed(Context); 13474 13475 if (ASTMutationListener *L = getASTMutationListener()) { 13476 L->CompletedImplicitDefinition(Constructor); 13477 } 13478 13479 DiagnoseUninitializedFields(*this, Constructor); 13480 } 13481 13482 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 13483 // Perform any delayed checks on exception specifications. 13484 CheckDelayedMemberExceptionSpecs(); 13485 } 13486 13487 /// Find or create the fake constructor we synthesize to model constructing an 13488 /// object of a derived class via a constructor of a base class. 13489 CXXConstructorDecl * 13490 Sema::findInheritingConstructor(SourceLocation Loc, 13491 CXXConstructorDecl *BaseCtor, 13492 ConstructorUsingShadowDecl *Shadow) { 13493 CXXRecordDecl *Derived = Shadow->getParent(); 13494 SourceLocation UsingLoc = Shadow->getLocation(); 13495 13496 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 13497 // For now we use the name of the base class constructor as a member of the 13498 // derived class to indicate a (fake) inherited constructor name. 13499 DeclarationName Name = BaseCtor->getDeclName(); 13500 13501 // Check to see if we already have a fake constructor for this inherited 13502 // constructor call. 13503 for (NamedDecl *Ctor : Derived->lookup(Name)) 13504 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 13505 ->getInheritedConstructor() 13506 .getConstructor(), 13507 BaseCtor)) 13508 return cast<CXXConstructorDecl>(Ctor); 13509 13510 DeclarationNameInfo NameInfo(Name, UsingLoc); 13511 TypeSourceInfo *TInfo = 13512 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 13513 FunctionProtoTypeLoc ProtoLoc = 13514 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 13515 13516 // Check the inherited constructor is valid and find the list of base classes 13517 // from which it was inherited. 13518 InheritedConstructorInfo ICI(*this, Loc, Shadow); 13519 13520 bool Constexpr = 13521 BaseCtor->isConstexpr() && 13522 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 13523 false, BaseCtor, &ICI); 13524 13525 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 13526 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 13527 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 13528 /*isInline=*/true, 13529 /*isImplicitlyDeclared=*/true, 13530 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified, 13531 InheritedConstructor(Shadow, BaseCtor), 13532 BaseCtor->getTrailingRequiresClause()); 13533 if (Shadow->isInvalidDecl()) 13534 DerivedCtor->setInvalidDecl(); 13535 13536 // Build an unevaluated exception specification for this fake constructor. 13537 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 13538 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13539 EPI.ExceptionSpec.Type = EST_Unevaluated; 13540 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 13541 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 13542 FPT->getParamTypes(), EPI)); 13543 13544 // Build the parameter declarations. 13545 SmallVector<ParmVarDecl *, 16> ParamDecls; 13546 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 13547 TypeSourceInfo *TInfo = 13548 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 13549 ParmVarDecl *PD = ParmVarDecl::Create( 13550 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 13551 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 13552 PD->setScopeInfo(0, I); 13553 PD->setImplicit(); 13554 // Ensure attributes are propagated onto parameters (this matters for 13555 // format, pass_object_size, ...). 13556 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 13557 ParamDecls.push_back(PD); 13558 ProtoLoc.setParam(I, PD); 13559 } 13560 13561 // Set up the new constructor. 13562 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 13563 DerivedCtor->setAccess(BaseCtor->getAccess()); 13564 DerivedCtor->setParams(ParamDecls); 13565 Derived->addDecl(DerivedCtor); 13566 13567 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 13568 SetDeclDeleted(DerivedCtor, UsingLoc); 13569 13570 return DerivedCtor; 13571 } 13572 13573 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 13574 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 13575 Ctor->getInheritedConstructor().getShadowDecl()); 13576 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 13577 /*Diagnose*/true); 13578 } 13579 13580 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 13581 CXXConstructorDecl *Constructor) { 13582 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13583 assert(Constructor->getInheritedConstructor() && 13584 !Constructor->doesThisDeclarationHaveABody() && 13585 !Constructor->isDeleted()); 13586 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13587 return; 13588 13589 // Initializations are performed "as if by a defaulted default constructor", 13590 // so enter the appropriate scope. 13591 SynthesizedFunctionScope Scope(*this, Constructor); 13592 13593 // The exception specification is needed because we are defining the 13594 // function. 13595 ResolveExceptionSpec(CurrentLocation, 13596 Constructor->getType()->castAs<FunctionProtoType>()); 13597 MarkVTableUsed(CurrentLocation, ClassDecl); 13598 13599 // Add a context note for diagnostics produced after this point. 13600 Scope.addContextNote(CurrentLocation); 13601 13602 ConstructorUsingShadowDecl *Shadow = 13603 Constructor->getInheritedConstructor().getShadowDecl(); 13604 CXXConstructorDecl *InheritedCtor = 13605 Constructor->getInheritedConstructor().getConstructor(); 13606 13607 // [class.inhctor.init]p1: 13608 // initialization proceeds as if a defaulted default constructor is used to 13609 // initialize the D object and each base class subobject from which the 13610 // constructor was inherited 13611 13612 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 13613 CXXRecordDecl *RD = Shadow->getParent(); 13614 SourceLocation InitLoc = Shadow->getLocation(); 13615 13616 // Build explicit initializers for all base classes from which the 13617 // constructor was inherited. 13618 SmallVector<CXXCtorInitializer*, 8> Inits; 13619 for (bool VBase : {false, true}) { 13620 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 13621 if (B.isVirtual() != VBase) 13622 continue; 13623 13624 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 13625 if (!BaseRD) 13626 continue; 13627 13628 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 13629 if (!BaseCtor.first) 13630 continue; 13631 13632 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 13633 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 13634 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 13635 13636 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 13637 Inits.push_back(new (Context) CXXCtorInitializer( 13638 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 13639 SourceLocation())); 13640 } 13641 } 13642 13643 // We now proceed as if for a defaulted default constructor, with the relevant 13644 // initializers replaced. 13645 13646 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 13647 Constructor->setInvalidDecl(); 13648 return; 13649 } 13650 13651 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 13652 Constructor->markUsed(Context); 13653 13654 if (ASTMutationListener *L = getASTMutationListener()) { 13655 L->CompletedImplicitDefinition(Constructor); 13656 } 13657 13658 DiagnoseUninitializedFields(*this, Constructor); 13659 } 13660 13661 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 13662 // C++ [class.dtor]p2: 13663 // If a class has no user-declared destructor, a destructor is 13664 // declared implicitly. An implicitly-declared destructor is an 13665 // inline public member of its class. 13666 assert(ClassDecl->needsImplicitDestructor()); 13667 13668 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 13669 if (DSM.isAlreadyBeingDeclared()) 13670 return nullptr; 13671 13672 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13673 CXXDestructor, 13674 false); 13675 13676 // Create the actual destructor declaration. 13677 CanQualType ClassType 13678 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13679 SourceLocation ClassLoc = ClassDecl->getLocation(); 13680 DeclarationName Name 13681 = Context.DeclarationNames.getCXXDestructorName(ClassType); 13682 DeclarationNameInfo NameInfo(Name, ClassLoc); 13683 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create( 13684 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr, 13685 getCurFPFeatures().isFPConstrained(), 13686 /*isInline=*/true, 13687 /*isImplicitlyDeclared=*/true, 13688 Constexpr ? ConstexprSpecKind::Constexpr 13689 : ConstexprSpecKind::Unspecified); 13690 Destructor->setAccess(AS_public); 13691 Destructor->setDefaulted(); 13692 13693 if (getLangOpts().CUDA) { 13694 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 13695 Destructor, 13696 /* ConstRHS */ false, 13697 /* Diagnose */ false); 13698 } 13699 13700 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 13701 13702 // We don't need to use SpecialMemberIsTrivial here; triviality for 13703 // destructors is easy to compute. 13704 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 13705 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 13706 ClassDecl->hasTrivialDestructorForCall()); 13707 13708 // Note that we have declared this destructor. 13709 ++getASTContext().NumImplicitDestructorsDeclared; 13710 13711 Scope *S = getScopeForContext(ClassDecl); 13712 CheckImplicitSpecialMemberDeclaration(S, Destructor); 13713 13714 // We can't check whether an implicit destructor is deleted before we complete 13715 // the definition of the class, because its validity depends on the alignment 13716 // of the class. We'll check this from ActOnFields once the class is complete. 13717 if (ClassDecl->isCompleteDefinition() && 13718 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 13719 SetDeclDeleted(Destructor, ClassLoc); 13720 13721 // Introduce this destructor into its scope. 13722 if (S) 13723 PushOnScopeChains(Destructor, S, false); 13724 ClassDecl->addDecl(Destructor); 13725 13726 return Destructor; 13727 } 13728 13729 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 13730 CXXDestructorDecl *Destructor) { 13731 assert((Destructor->isDefaulted() && 13732 !Destructor->doesThisDeclarationHaveABody() && 13733 !Destructor->isDeleted()) && 13734 "DefineImplicitDestructor - call it for implicit default dtor"); 13735 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 13736 return; 13737 13738 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13739 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 13740 13741 SynthesizedFunctionScope Scope(*this, Destructor); 13742 13743 // The exception specification is needed because we are defining the 13744 // function. 13745 ResolveExceptionSpec(CurrentLocation, 13746 Destructor->getType()->castAs<FunctionProtoType>()); 13747 MarkVTableUsed(CurrentLocation, ClassDecl); 13748 13749 // Add a context note for diagnostics produced after this point. 13750 Scope.addContextNote(CurrentLocation); 13751 13752 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13753 Destructor->getParent()); 13754 13755 if (CheckDestructor(Destructor)) { 13756 Destructor->setInvalidDecl(); 13757 return; 13758 } 13759 13760 SourceLocation Loc = Destructor->getEndLoc().isValid() 13761 ? Destructor->getEndLoc() 13762 : Destructor->getLocation(); 13763 Destructor->setBody(new (Context) CompoundStmt(Loc)); 13764 Destructor->markUsed(Context); 13765 13766 if (ASTMutationListener *L = getASTMutationListener()) { 13767 L->CompletedImplicitDefinition(Destructor); 13768 } 13769 } 13770 13771 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 13772 CXXDestructorDecl *Destructor) { 13773 if (Destructor->isInvalidDecl()) 13774 return; 13775 13776 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13777 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() && 13778 "implicit complete dtors unneeded outside MS ABI"); 13779 assert(ClassDecl->getNumVBases() > 0 && 13780 "complete dtor only exists for classes with vbases"); 13781 13782 SynthesizedFunctionScope Scope(*this, Destructor); 13783 13784 // Add a context note for diagnostics produced after this point. 13785 Scope.addContextNote(CurrentLocation); 13786 13787 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl); 13788 } 13789 13790 /// Perform any semantic analysis which needs to be delayed until all 13791 /// pending class member declarations have been parsed. 13792 void Sema::ActOnFinishCXXMemberDecls() { 13793 // If the context is an invalid C++ class, just suppress these checks. 13794 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 13795 if (Record->isInvalidDecl()) { 13796 DelayedOverridingExceptionSpecChecks.clear(); 13797 DelayedEquivalentExceptionSpecChecks.clear(); 13798 return; 13799 } 13800 checkForMultipleExportedDefaultConstructors(*this, Record); 13801 } 13802 } 13803 13804 void Sema::ActOnFinishCXXNonNestedClass() { 13805 referenceDLLExportedClassMethods(); 13806 13807 if (!DelayedDllExportMemberFunctions.empty()) { 13808 SmallVector<CXXMethodDecl*, 4> WorkList; 13809 std::swap(DelayedDllExportMemberFunctions, WorkList); 13810 for (CXXMethodDecl *M : WorkList) { 13811 DefineDefaultedFunction(*this, M, M->getLocation()); 13812 13813 // Pass the method to the consumer to get emitted. This is not necessary 13814 // for explicit instantiation definitions, as they will get emitted 13815 // anyway. 13816 if (M->getParent()->getTemplateSpecializationKind() != 13817 TSK_ExplicitInstantiationDefinition) 13818 ActOnFinishInlineFunctionDef(M); 13819 } 13820 } 13821 } 13822 13823 void Sema::referenceDLLExportedClassMethods() { 13824 if (!DelayedDllExportClasses.empty()) { 13825 // Calling ReferenceDllExportedMembers might cause the current function to 13826 // be called again, so use a local copy of DelayedDllExportClasses. 13827 SmallVector<CXXRecordDecl *, 4> WorkList; 13828 std::swap(DelayedDllExportClasses, WorkList); 13829 for (CXXRecordDecl *Class : WorkList) 13830 ReferenceDllExportedMembers(*this, Class); 13831 } 13832 } 13833 13834 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 13835 assert(getLangOpts().CPlusPlus11 && 13836 "adjusting dtor exception specs was introduced in c++11"); 13837 13838 if (Destructor->isDependentContext()) 13839 return; 13840 13841 // C++11 [class.dtor]p3: 13842 // A declaration of a destructor that does not have an exception- 13843 // specification is implicitly considered to have the same exception- 13844 // specification as an implicit declaration. 13845 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); 13846 if (DtorType->hasExceptionSpec()) 13847 return; 13848 13849 // Replace the destructor's type, building off the existing one. Fortunately, 13850 // the only thing of interest in the destructor type is its extended info. 13851 // The return and arguments are fixed. 13852 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 13853 EPI.ExceptionSpec.Type = EST_Unevaluated; 13854 EPI.ExceptionSpec.SourceDecl = Destructor; 13855 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 13856 13857 // FIXME: If the destructor has a body that could throw, and the newly created 13858 // spec doesn't allow exceptions, we should emit a warning, because this 13859 // change in behavior can break conforming C++03 programs at runtime. 13860 // However, we don't have a body or an exception specification yet, so it 13861 // needs to be done somewhere else. 13862 } 13863 13864 namespace { 13865 /// An abstract base class for all helper classes used in building the 13866 // copy/move operators. These classes serve as factory functions and help us 13867 // avoid using the same Expr* in the AST twice. 13868 class ExprBuilder { 13869 ExprBuilder(const ExprBuilder&) = delete; 13870 ExprBuilder &operator=(const ExprBuilder&) = delete; 13871 13872 protected: 13873 static Expr *assertNotNull(Expr *E) { 13874 assert(E && "Expression construction must not fail."); 13875 return E; 13876 } 13877 13878 public: 13879 ExprBuilder() {} 13880 virtual ~ExprBuilder() {} 13881 13882 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 13883 }; 13884 13885 class RefBuilder: public ExprBuilder { 13886 VarDecl *Var; 13887 QualType VarType; 13888 13889 public: 13890 Expr *build(Sema &S, SourceLocation Loc) const override { 13891 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 13892 } 13893 13894 RefBuilder(VarDecl *Var, QualType VarType) 13895 : Var(Var), VarType(VarType) {} 13896 }; 13897 13898 class ThisBuilder: public ExprBuilder { 13899 public: 13900 Expr *build(Sema &S, SourceLocation Loc) const override { 13901 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 13902 } 13903 }; 13904 13905 class CastBuilder: public ExprBuilder { 13906 const ExprBuilder &Builder; 13907 QualType Type; 13908 ExprValueKind Kind; 13909 const CXXCastPath &Path; 13910 13911 public: 13912 Expr *build(Sema &S, SourceLocation Loc) const override { 13913 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 13914 CK_UncheckedDerivedToBase, Kind, 13915 &Path).get()); 13916 } 13917 13918 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 13919 const CXXCastPath &Path) 13920 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 13921 }; 13922 13923 class DerefBuilder: public ExprBuilder { 13924 const ExprBuilder &Builder; 13925 13926 public: 13927 Expr *build(Sema &S, SourceLocation Loc) const override { 13928 return assertNotNull( 13929 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 13930 } 13931 13932 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13933 }; 13934 13935 class MemberBuilder: public ExprBuilder { 13936 const ExprBuilder &Builder; 13937 QualType Type; 13938 CXXScopeSpec SS; 13939 bool IsArrow; 13940 LookupResult &MemberLookup; 13941 13942 public: 13943 Expr *build(Sema &S, SourceLocation Loc) const override { 13944 return assertNotNull(S.BuildMemberReferenceExpr( 13945 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 13946 nullptr, MemberLookup, nullptr, nullptr).get()); 13947 } 13948 13949 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 13950 LookupResult &MemberLookup) 13951 : Builder(Builder), Type(Type), IsArrow(IsArrow), 13952 MemberLookup(MemberLookup) {} 13953 }; 13954 13955 class MoveCastBuilder: public ExprBuilder { 13956 const ExprBuilder &Builder; 13957 13958 public: 13959 Expr *build(Sema &S, SourceLocation Loc) const override { 13960 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 13961 } 13962 13963 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13964 }; 13965 13966 class LvalueConvBuilder: public ExprBuilder { 13967 const ExprBuilder &Builder; 13968 13969 public: 13970 Expr *build(Sema &S, SourceLocation Loc) const override { 13971 return assertNotNull( 13972 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 13973 } 13974 13975 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13976 }; 13977 13978 class SubscriptBuilder: public ExprBuilder { 13979 const ExprBuilder &Base; 13980 const ExprBuilder &Index; 13981 13982 public: 13983 Expr *build(Sema &S, SourceLocation Loc) const override { 13984 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 13985 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 13986 } 13987 13988 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 13989 : Base(Base), Index(Index) {} 13990 }; 13991 13992 } // end anonymous namespace 13993 13994 /// When generating a defaulted copy or move assignment operator, if a field 13995 /// should be copied with __builtin_memcpy rather than via explicit assignments, 13996 /// do so. This optimization only applies for arrays of scalars, and for arrays 13997 /// of class type where the selected copy/move-assignment operator is trivial. 13998 static StmtResult 13999 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 14000 const ExprBuilder &ToB, const ExprBuilder &FromB) { 14001 // Compute the size of the memory buffer to be copied. 14002 QualType SizeType = S.Context.getSizeType(); 14003 llvm::APInt Size(S.Context.getTypeSize(SizeType), 14004 S.Context.getTypeSizeInChars(T).getQuantity()); 14005 14006 // Take the address of the field references for "from" and "to". We 14007 // directly construct UnaryOperators here because semantic analysis 14008 // does not permit us to take the address of an xvalue. 14009 Expr *From = FromB.build(S, Loc); 14010 From = UnaryOperator::Create( 14011 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()), 14012 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 14013 Expr *To = ToB.build(S, Loc); 14014 To = UnaryOperator::Create( 14015 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()), 14016 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 14017 14018 const Type *E = T->getBaseElementTypeUnsafe(); 14019 bool NeedsCollectableMemCpy = 14020 E->isRecordType() && 14021 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 14022 14023 // Create a reference to the __builtin_objc_memmove_collectable function 14024 StringRef MemCpyName = NeedsCollectableMemCpy ? 14025 "__builtin_objc_memmove_collectable" : 14026 "__builtin_memcpy"; 14027 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 14028 Sema::LookupOrdinaryName); 14029 S.LookupName(R, S.TUScope, true); 14030 14031 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 14032 if (!MemCpy) 14033 // Something went horribly wrong earlier, and we will have complained 14034 // about it. 14035 return StmtError(); 14036 14037 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 14038 VK_PRValue, Loc, nullptr); 14039 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 14040 14041 Expr *CallArgs[] = { 14042 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 14043 }; 14044 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 14045 Loc, CallArgs, Loc); 14046 14047 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 14048 return Call.getAs<Stmt>(); 14049 } 14050 14051 /// Builds a statement that copies/moves the given entity from \p From to 14052 /// \c To. 14053 /// 14054 /// This routine is used to copy/move the members of a class with an 14055 /// implicitly-declared copy/move assignment operator. When the entities being 14056 /// copied are arrays, this routine builds for loops to copy them. 14057 /// 14058 /// \param S The Sema object used for type-checking. 14059 /// 14060 /// \param Loc The location where the implicit copy/move is being generated. 14061 /// 14062 /// \param T The type of the expressions being copied/moved. Both expressions 14063 /// must have this type. 14064 /// 14065 /// \param To The expression we are copying/moving to. 14066 /// 14067 /// \param From The expression we are copying/moving from. 14068 /// 14069 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 14070 /// Otherwise, it's a non-static member subobject. 14071 /// 14072 /// \param Copying Whether we're copying or moving. 14073 /// 14074 /// \param Depth Internal parameter recording the depth of the recursion. 14075 /// 14076 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 14077 /// if a memcpy should be used instead. 14078 static StmtResult 14079 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 14080 const ExprBuilder &To, const ExprBuilder &From, 14081 bool CopyingBaseSubobject, bool Copying, 14082 unsigned Depth = 0) { 14083 // C++11 [class.copy]p28: 14084 // Each subobject is assigned in the manner appropriate to its type: 14085 // 14086 // - if the subobject is of class type, as if by a call to operator= with 14087 // the subobject as the object expression and the corresponding 14088 // subobject of x as a single function argument (as if by explicit 14089 // qualification; that is, ignoring any possible virtual overriding 14090 // functions in more derived classes); 14091 // 14092 // C++03 [class.copy]p13: 14093 // - if the subobject is of class type, the copy assignment operator for 14094 // the class is used (as if by explicit qualification; that is, 14095 // ignoring any possible virtual overriding functions in more derived 14096 // classes); 14097 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 14098 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 14099 14100 // Look for operator=. 14101 DeclarationName Name 14102 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14103 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 14104 S.LookupQualifiedName(OpLookup, ClassDecl, false); 14105 14106 // Prior to C++11, filter out any result that isn't a copy/move-assignment 14107 // operator. 14108 if (!S.getLangOpts().CPlusPlus11) { 14109 LookupResult::Filter F = OpLookup.makeFilter(); 14110 while (F.hasNext()) { 14111 NamedDecl *D = F.next(); 14112 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 14113 if (Method->isCopyAssignmentOperator() || 14114 (!Copying && Method->isMoveAssignmentOperator())) 14115 continue; 14116 14117 F.erase(); 14118 } 14119 F.done(); 14120 } 14121 14122 // Suppress the protected check (C++ [class.protected]) for each of the 14123 // assignment operators we found. This strange dance is required when 14124 // we're assigning via a base classes's copy-assignment operator. To 14125 // ensure that we're getting the right base class subobject (without 14126 // ambiguities), we need to cast "this" to that subobject type; to 14127 // ensure that we don't go through the virtual call mechanism, we need 14128 // to qualify the operator= name with the base class (see below). However, 14129 // this means that if the base class has a protected copy assignment 14130 // operator, the protected member access check will fail. So, we 14131 // rewrite "protected" access to "public" access in this case, since we 14132 // know by construction that we're calling from a derived class. 14133 if (CopyingBaseSubobject) { 14134 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 14135 L != LEnd; ++L) { 14136 if (L.getAccess() == AS_protected) 14137 L.setAccess(AS_public); 14138 } 14139 } 14140 14141 // Create the nested-name-specifier that will be used to qualify the 14142 // reference to operator=; this is required to suppress the virtual 14143 // call mechanism. 14144 CXXScopeSpec SS; 14145 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 14146 SS.MakeTrivial(S.Context, 14147 NestedNameSpecifier::Create(S.Context, nullptr, false, 14148 CanonicalT), 14149 Loc); 14150 14151 // Create the reference to operator=. 14152 ExprResult OpEqualRef 14153 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 14154 SS, /*TemplateKWLoc=*/SourceLocation(), 14155 /*FirstQualifierInScope=*/nullptr, 14156 OpLookup, 14157 /*TemplateArgs=*/nullptr, /*S*/nullptr, 14158 /*SuppressQualifierCheck=*/true); 14159 if (OpEqualRef.isInvalid()) 14160 return StmtError(); 14161 14162 // Build the call to the assignment operator. 14163 14164 Expr *FromInst = From.build(S, Loc); 14165 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 14166 OpEqualRef.getAs<Expr>(), 14167 Loc, FromInst, Loc); 14168 if (Call.isInvalid()) 14169 return StmtError(); 14170 14171 // If we built a call to a trivial 'operator=' while copying an array, 14172 // bail out. We'll replace the whole shebang with a memcpy. 14173 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 14174 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 14175 return StmtResult((Stmt*)nullptr); 14176 14177 // Convert to an expression-statement, and clean up any produced 14178 // temporaries. 14179 return S.ActOnExprStmt(Call); 14180 } 14181 14182 // - if the subobject is of scalar type, the built-in assignment 14183 // operator is used. 14184 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 14185 if (!ArrayTy) { 14186 ExprResult Assignment = S.CreateBuiltinBinOp( 14187 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 14188 if (Assignment.isInvalid()) 14189 return StmtError(); 14190 return S.ActOnExprStmt(Assignment); 14191 } 14192 14193 // - if the subobject is an array, each element is assigned, in the 14194 // manner appropriate to the element type; 14195 14196 // Construct a loop over the array bounds, e.g., 14197 // 14198 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 14199 // 14200 // that will copy each of the array elements. 14201 QualType SizeType = S.Context.getSizeType(); 14202 14203 // Create the iteration variable. 14204 IdentifierInfo *IterationVarName = nullptr; 14205 { 14206 SmallString<8> Str; 14207 llvm::raw_svector_ostream OS(Str); 14208 OS << "__i" << Depth; 14209 IterationVarName = &S.Context.Idents.get(OS.str()); 14210 } 14211 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 14212 IterationVarName, SizeType, 14213 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 14214 SC_None); 14215 14216 // Initialize the iteration variable to zero. 14217 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 14218 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 14219 14220 // Creates a reference to the iteration variable. 14221 RefBuilder IterationVarRef(IterationVar, SizeType); 14222 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 14223 14224 // Create the DeclStmt that holds the iteration variable. 14225 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 14226 14227 // Subscript the "from" and "to" expressions with the iteration variable. 14228 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 14229 MoveCastBuilder FromIndexMove(FromIndexCopy); 14230 const ExprBuilder *FromIndex; 14231 if (Copying) 14232 FromIndex = &FromIndexCopy; 14233 else 14234 FromIndex = &FromIndexMove; 14235 14236 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 14237 14238 // Build the copy/move for an individual element of the array. 14239 StmtResult Copy = 14240 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 14241 ToIndex, *FromIndex, CopyingBaseSubobject, 14242 Copying, Depth + 1); 14243 // Bail out if copying fails or if we determined that we should use memcpy. 14244 if (Copy.isInvalid() || !Copy.get()) 14245 return Copy; 14246 14247 // Create the comparison against the array bound. 14248 llvm::APInt Upper 14249 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 14250 Expr *Comparison = BinaryOperator::Create( 14251 S.Context, IterationVarRefRVal.build(S, Loc), 14252 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE, 14253 S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc, 14254 S.CurFPFeatureOverrides()); 14255 14256 // Create the pre-increment of the iteration variable. We can determine 14257 // whether the increment will overflow based on the value of the array 14258 // bound. 14259 Expr *Increment = UnaryOperator::Create( 14260 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue, 14261 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides()); 14262 14263 // Construct the loop that copies all elements of this array. 14264 return S.ActOnForStmt( 14265 Loc, Loc, InitStmt, 14266 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 14267 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 14268 } 14269 14270 static StmtResult 14271 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 14272 const ExprBuilder &To, const ExprBuilder &From, 14273 bool CopyingBaseSubobject, bool Copying) { 14274 // Maybe we should use a memcpy? 14275 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 14276 T.isTriviallyCopyableType(S.Context)) 14277 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 14278 14279 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 14280 CopyingBaseSubobject, 14281 Copying, 0)); 14282 14283 // If we ended up picking a trivial assignment operator for an array of a 14284 // non-trivially-copyable class type, just emit a memcpy. 14285 if (!Result.isInvalid() && !Result.get()) 14286 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 14287 14288 return Result; 14289 } 14290 14291 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 14292 // Note: The following rules are largely analoguous to the copy 14293 // constructor rules. Note that virtual bases are not taken into account 14294 // for determining the argument type of the operator. Note also that 14295 // operators taking an object instead of a reference are allowed. 14296 assert(ClassDecl->needsImplicitCopyAssignment()); 14297 14298 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 14299 if (DSM.isAlreadyBeingDeclared()) 14300 return nullptr; 14301 14302 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14303 LangAS AS = getDefaultCXXMethodAddrSpace(); 14304 if (AS != LangAS::Default) 14305 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14306 QualType RetType = Context.getLValueReferenceType(ArgType); 14307 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 14308 if (Const) 14309 ArgType = ArgType.withConst(); 14310 14311 ArgType = Context.getLValueReferenceType(ArgType); 14312 14313 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14314 CXXCopyAssignment, 14315 Const); 14316 14317 // An implicitly-declared copy assignment operator is an inline public 14318 // member of its class. 14319 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14320 SourceLocation ClassLoc = ClassDecl->getLocation(); 14321 DeclarationNameInfo NameInfo(Name, ClassLoc); 14322 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 14323 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14324 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14325 getCurFPFeatures().isFPConstrained(), 14326 /*isInline=*/true, 14327 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14328 SourceLocation()); 14329 CopyAssignment->setAccess(AS_public); 14330 CopyAssignment->setDefaulted(); 14331 CopyAssignment->setImplicit(); 14332 14333 if (getLangOpts().CUDA) { 14334 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 14335 CopyAssignment, 14336 /* ConstRHS */ Const, 14337 /* Diagnose */ false); 14338 } 14339 14340 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 14341 14342 // Add the parameter to the operator. 14343 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 14344 ClassLoc, ClassLoc, 14345 /*Id=*/nullptr, ArgType, 14346 /*TInfo=*/nullptr, SC_None, 14347 nullptr); 14348 CopyAssignment->setParams(FromParam); 14349 14350 CopyAssignment->setTrivial( 14351 ClassDecl->needsOverloadResolutionForCopyAssignment() 14352 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 14353 : ClassDecl->hasTrivialCopyAssignment()); 14354 14355 // Note that we have added this copy-assignment operator. 14356 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 14357 14358 Scope *S = getScopeForContext(ClassDecl); 14359 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 14360 14361 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) { 14362 ClassDecl->setImplicitCopyAssignmentIsDeleted(); 14363 SetDeclDeleted(CopyAssignment, ClassLoc); 14364 } 14365 14366 if (S) 14367 PushOnScopeChains(CopyAssignment, S, false); 14368 ClassDecl->addDecl(CopyAssignment); 14369 14370 return CopyAssignment; 14371 } 14372 14373 /// Diagnose an implicit copy operation for a class which is odr-used, but 14374 /// which is deprecated because the class has a user-declared copy constructor, 14375 /// copy assignment operator, or destructor. 14376 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 14377 assert(CopyOp->isImplicit()); 14378 14379 CXXRecordDecl *RD = CopyOp->getParent(); 14380 CXXMethodDecl *UserDeclaredOperation = nullptr; 14381 14382 // In Microsoft mode, assignment operations don't affect constructors and 14383 // vice versa. 14384 if (RD->hasUserDeclaredDestructor()) { 14385 UserDeclaredOperation = RD->getDestructor(); 14386 } else if (!isa<CXXConstructorDecl>(CopyOp) && 14387 RD->hasUserDeclaredCopyConstructor() && 14388 !S.getLangOpts().MSVCCompat) { 14389 // Find any user-declared copy constructor. 14390 for (auto *I : RD->ctors()) { 14391 if (I->isCopyConstructor()) { 14392 UserDeclaredOperation = I; 14393 break; 14394 } 14395 } 14396 assert(UserDeclaredOperation); 14397 } else if (isa<CXXConstructorDecl>(CopyOp) && 14398 RD->hasUserDeclaredCopyAssignment() && 14399 !S.getLangOpts().MSVCCompat) { 14400 // Find any user-declared move assignment operator. 14401 for (auto *I : RD->methods()) { 14402 if (I->isCopyAssignmentOperator()) { 14403 UserDeclaredOperation = I; 14404 break; 14405 } 14406 } 14407 assert(UserDeclaredOperation); 14408 } 14409 14410 if (UserDeclaredOperation) { 14411 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided(); 14412 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation); 14413 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp); 14414 unsigned DiagID = 14415 (UDOIsUserProvided && UDOIsDestructor) 14416 ? diag::warn_deprecated_copy_with_user_provided_dtor 14417 : (UDOIsUserProvided && !UDOIsDestructor) 14418 ? diag::warn_deprecated_copy_with_user_provided_copy 14419 : (!UDOIsUserProvided && UDOIsDestructor) 14420 ? diag::warn_deprecated_copy_with_dtor 14421 : diag::warn_deprecated_copy; 14422 S.Diag(UserDeclaredOperation->getLocation(), DiagID) 14423 << RD << IsCopyAssignment; 14424 } 14425 } 14426 14427 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 14428 CXXMethodDecl *CopyAssignOperator) { 14429 assert((CopyAssignOperator->isDefaulted() && 14430 CopyAssignOperator->isOverloadedOperator() && 14431 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 14432 !CopyAssignOperator->doesThisDeclarationHaveABody() && 14433 !CopyAssignOperator->isDeleted()) && 14434 "DefineImplicitCopyAssignment called for wrong function"); 14435 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 14436 return; 14437 14438 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 14439 if (ClassDecl->isInvalidDecl()) { 14440 CopyAssignOperator->setInvalidDecl(); 14441 return; 14442 } 14443 14444 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 14445 14446 // The exception specification is needed because we are defining the 14447 // function. 14448 ResolveExceptionSpec(CurrentLocation, 14449 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 14450 14451 // Add a context note for diagnostics produced after this point. 14452 Scope.addContextNote(CurrentLocation); 14453 14454 // C++11 [class.copy]p18: 14455 // The [definition of an implicitly declared copy assignment operator] is 14456 // deprecated if the class has a user-declared copy constructor or a 14457 // user-declared destructor. 14458 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 14459 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 14460 14461 // C++0x [class.copy]p30: 14462 // The implicitly-defined or explicitly-defaulted copy assignment operator 14463 // for a non-union class X performs memberwise copy assignment of its 14464 // subobjects. The direct base classes of X are assigned first, in the 14465 // order of their declaration in the base-specifier-list, and then the 14466 // immediate non-static data members of X are assigned, in the order in 14467 // which they were declared in the class definition. 14468 14469 // The statements that form the synthesized function body. 14470 SmallVector<Stmt*, 8> Statements; 14471 14472 // The parameter for the "other" object, which we are copying from. 14473 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 14474 Qualifiers OtherQuals = Other->getType().getQualifiers(); 14475 QualType OtherRefType = Other->getType(); 14476 if (const LValueReferenceType *OtherRef 14477 = OtherRefType->getAs<LValueReferenceType>()) { 14478 OtherRefType = OtherRef->getPointeeType(); 14479 OtherQuals = OtherRefType.getQualifiers(); 14480 } 14481 14482 // Our location for everything implicitly-generated. 14483 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 14484 ? CopyAssignOperator->getEndLoc() 14485 : CopyAssignOperator->getLocation(); 14486 14487 // Builds a DeclRefExpr for the "other" object. 14488 RefBuilder OtherRef(Other, OtherRefType); 14489 14490 // Builds the "this" pointer. 14491 ThisBuilder This; 14492 14493 // Assign base classes. 14494 bool Invalid = false; 14495 for (auto &Base : ClassDecl->bases()) { 14496 // Form the assignment: 14497 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 14498 QualType BaseType = Base.getType().getUnqualifiedType(); 14499 if (!BaseType->isRecordType()) { 14500 Invalid = true; 14501 continue; 14502 } 14503 14504 CXXCastPath BasePath; 14505 BasePath.push_back(&Base); 14506 14507 // Construct the "from" expression, which is an implicit cast to the 14508 // appropriately-qualified base type. 14509 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 14510 VK_LValue, BasePath); 14511 14512 // Dereference "this". 14513 DerefBuilder DerefThis(This); 14514 CastBuilder To(DerefThis, 14515 Context.getQualifiedType( 14516 BaseType, CopyAssignOperator->getMethodQualifiers()), 14517 VK_LValue, BasePath); 14518 14519 // Build the copy. 14520 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 14521 To, From, 14522 /*CopyingBaseSubobject=*/true, 14523 /*Copying=*/true); 14524 if (Copy.isInvalid()) { 14525 CopyAssignOperator->setInvalidDecl(); 14526 return; 14527 } 14528 14529 // Success! Record the copy. 14530 Statements.push_back(Copy.getAs<Expr>()); 14531 } 14532 14533 // Assign non-static members. 14534 for (auto *Field : ClassDecl->fields()) { 14535 // FIXME: We should form some kind of AST representation for the implied 14536 // memcpy in a union copy operation. 14537 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14538 continue; 14539 14540 if (Field->isInvalidDecl()) { 14541 Invalid = true; 14542 continue; 14543 } 14544 14545 // Check for members of reference type; we can't copy those. 14546 if (Field->getType()->isReferenceType()) { 14547 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14548 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14549 Diag(Field->getLocation(), diag::note_declared_at); 14550 Invalid = true; 14551 continue; 14552 } 14553 14554 // Check for members of const-qualified, non-class type. 14555 QualType BaseType = Context.getBaseElementType(Field->getType()); 14556 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14557 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14558 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14559 Diag(Field->getLocation(), diag::note_declared_at); 14560 Invalid = true; 14561 continue; 14562 } 14563 14564 // Suppress assigning zero-width bitfields. 14565 if (Field->isZeroLengthBitField(Context)) 14566 continue; 14567 14568 QualType FieldType = Field->getType().getNonReferenceType(); 14569 if (FieldType->isIncompleteArrayType()) { 14570 assert(ClassDecl->hasFlexibleArrayMember() && 14571 "Incomplete array type is not valid"); 14572 continue; 14573 } 14574 14575 // Build references to the field in the object we're copying from and to. 14576 CXXScopeSpec SS; // Intentionally empty 14577 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14578 LookupMemberName); 14579 MemberLookup.addDecl(Field); 14580 MemberLookup.resolveKind(); 14581 14582 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 14583 14584 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 14585 14586 // Build the copy of this field. 14587 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 14588 To, From, 14589 /*CopyingBaseSubobject=*/false, 14590 /*Copying=*/true); 14591 if (Copy.isInvalid()) { 14592 CopyAssignOperator->setInvalidDecl(); 14593 return; 14594 } 14595 14596 // Success! Record the copy. 14597 Statements.push_back(Copy.getAs<Stmt>()); 14598 } 14599 14600 if (!Invalid) { 14601 // Add a "return *this;" 14602 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14603 14604 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14605 if (Return.isInvalid()) 14606 Invalid = true; 14607 else 14608 Statements.push_back(Return.getAs<Stmt>()); 14609 } 14610 14611 if (Invalid) { 14612 CopyAssignOperator->setInvalidDecl(); 14613 return; 14614 } 14615 14616 StmtResult Body; 14617 { 14618 CompoundScopeRAII CompoundScope(*this); 14619 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14620 /*isStmtExpr=*/false); 14621 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14622 } 14623 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 14624 CopyAssignOperator->markUsed(Context); 14625 14626 if (ASTMutationListener *L = getASTMutationListener()) { 14627 L->CompletedImplicitDefinition(CopyAssignOperator); 14628 } 14629 } 14630 14631 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 14632 assert(ClassDecl->needsImplicitMoveAssignment()); 14633 14634 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 14635 if (DSM.isAlreadyBeingDeclared()) 14636 return nullptr; 14637 14638 // Note: The following rules are largely analoguous to the move 14639 // constructor rules. 14640 14641 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14642 LangAS AS = getDefaultCXXMethodAddrSpace(); 14643 if (AS != LangAS::Default) 14644 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14645 QualType RetType = Context.getLValueReferenceType(ArgType); 14646 ArgType = Context.getRValueReferenceType(ArgType); 14647 14648 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14649 CXXMoveAssignment, 14650 false); 14651 14652 // An implicitly-declared move assignment operator is an inline public 14653 // member of its class. 14654 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14655 SourceLocation ClassLoc = ClassDecl->getLocation(); 14656 DeclarationNameInfo NameInfo(Name, ClassLoc); 14657 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 14658 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14659 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14660 getCurFPFeatures().isFPConstrained(), 14661 /*isInline=*/true, 14662 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14663 SourceLocation()); 14664 MoveAssignment->setAccess(AS_public); 14665 MoveAssignment->setDefaulted(); 14666 MoveAssignment->setImplicit(); 14667 14668 if (getLangOpts().CUDA) { 14669 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 14670 MoveAssignment, 14671 /* ConstRHS */ false, 14672 /* Diagnose */ false); 14673 } 14674 14675 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType); 14676 14677 // Add the parameter to the operator. 14678 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 14679 ClassLoc, ClassLoc, 14680 /*Id=*/nullptr, ArgType, 14681 /*TInfo=*/nullptr, SC_None, 14682 nullptr); 14683 MoveAssignment->setParams(FromParam); 14684 14685 MoveAssignment->setTrivial( 14686 ClassDecl->needsOverloadResolutionForMoveAssignment() 14687 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 14688 : ClassDecl->hasTrivialMoveAssignment()); 14689 14690 // Note that we have added this copy-assignment operator. 14691 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 14692 14693 Scope *S = getScopeForContext(ClassDecl); 14694 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 14695 14696 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 14697 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 14698 SetDeclDeleted(MoveAssignment, ClassLoc); 14699 } 14700 14701 if (S) 14702 PushOnScopeChains(MoveAssignment, S, false); 14703 ClassDecl->addDecl(MoveAssignment); 14704 14705 return MoveAssignment; 14706 } 14707 14708 /// Check if we're implicitly defining a move assignment operator for a class 14709 /// with virtual bases. Such a move assignment might move-assign the virtual 14710 /// base multiple times. 14711 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 14712 SourceLocation CurrentLocation) { 14713 assert(!Class->isDependentContext() && "should not define dependent move"); 14714 14715 // Only a virtual base could get implicitly move-assigned multiple times. 14716 // Only a non-trivial move assignment can observe this. We only want to 14717 // diagnose if we implicitly define an assignment operator that assigns 14718 // two base classes, both of which move-assign the same virtual base. 14719 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 14720 Class->getNumBases() < 2) 14721 return; 14722 14723 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 14724 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 14725 VBaseMap VBases; 14726 14727 for (auto &BI : Class->bases()) { 14728 Worklist.push_back(&BI); 14729 while (!Worklist.empty()) { 14730 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 14731 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 14732 14733 // If the base has no non-trivial move assignment operators, 14734 // we don't care about moves from it. 14735 if (!Base->hasNonTrivialMoveAssignment()) 14736 continue; 14737 14738 // If there's nothing virtual here, skip it. 14739 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 14740 continue; 14741 14742 // If we're not actually going to call a move assignment for this base, 14743 // or the selected move assignment is trivial, skip it. 14744 Sema::SpecialMemberOverloadResult SMOR = 14745 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 14746 /*ConstArg*/false, /*VolatileArg*/false, 14747 /*RValueThis*/true, /*ConstThis*/false, 14748 /*VolatileThis*/false); 14749 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 14750 !SMOR.getMethod()->isMoveAssignmentOperator()) 14751 continue; 14752 14753 if (BaseSpec->isVirtual()) { 14754 // We're going to move-assign this virtual base, and its move 14755 // assignment operator is not trivial. If this can happen for 14756 // multiple distinct direct bases of Class, diagnose it. (If it 14757 // only happens in one base, we'll diagnose it when synthesizing 14758 // that base class's move assignment operator.) 14759 CXXBaseSpecifier *&Existing = 14760 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 14761 .first->second; 14762 if (Existing && Existing != &BI) { 14763 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 14764 << Class << Base; 14765 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 14766 << (Base->getCanonicalDecl() == 14767 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14768 << Base << Existing->getType() << Existing->getSourceRange(); 14769 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 14770 << (Base->getCanonicalDecl() == 14771 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14772 << Base << BI.getType() << BaseSpec->getSourceRange(); 14773 14774 // Only diagnose each vbase once. 14775 Existing = nullptr; 14776 } 14777 } else { 14778 // Only walk over bases that have defaulted move assignment operators. 14779 // We assume that any user-provided move assignment operator handles 14780 // the multiple-moves-of-vbase case itself somehow. 14781 if (!SMOR.getMethod()->isDefaulted()) 14782 continue; 14783 14784 // We're going to move the base classes of Base. Add them to the list. 14785 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases())); 14786 } 14787 } 14788 } 14789 } 14790 14791 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 14792 CXXMethodDecl *MoveAssignOperator) { 14793 assert((MoveAssignOperator->isDefaulted() && 14794 MoveAssignOperator->isOverloadedOperator() && 14795 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 14796 !MoveAssignOperator->doesThisDeclarationHaveABody() && 14797 !MoveAssignOperator->isDeleted()) && 14798 "DefineImplicitMoveAssignment called for wrong function"); 14799 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 14800 return; 14801 14802 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 14803 if (ClassDecl->isInvalidDecl()) { 14804 MoveAssignOperator->setInvalidDecl(); 14805 return; 14806 } 14807 14808 // C++0x [class.copy]p28: 14809 // The implicitly-defined or move assignment operator for a non-union class 14810 // X performs memberwise move assignment of its subobjects. The direct base 14811 // classes of X are assigned first, in the order of their declaration in the 14812 // base-specifier-list, and then the immediate non-static data members of X 14813 // are assigned, in the order in which they were declared in the class 14814 // definition. 14815 14816 // Issue a warning if our implicit move assignment operator will move 14817 // from a virtual base more than once. 14818 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 14819 14820 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 14821 14822 // The exception specification is needed because we are defining the 14823 // function. 14824 ResolveExceptionSpec(CurrentLocation, 14825 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 14826 14827 // Add a context note for diagnostics produced after this point. 14828 Scope.addContextNote(CurrentLocation); 14829 14830 // The statements that form the synthesized function body. 14831 SmallVector<Stmt*, 8> Statements; 14832 14833 // The parameter for the "other" object, which we are move from. 14834 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 14835 QualType OtherRefType = 14836 Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); 14837 14838 // Our location for everything implicitly-generated. 14839 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 14840 ? MoveAssignOperator->getEndLoc() 14841 : MoveAssignOperator->getLocation(); 14842 14843 // Builds a reference to the "other" object. 14844 RefBuilder OtherRef(Other, OtherRefType); 14845 // Cast to rvalue. 14846 MoveCastBuilder MoveOther(OtherRef); 14847 14848 // Builds the "this" pointer. 14849 ThisBuilder This; 14850 14851 // Assign base classes. 14852 bool Invalid = false; 14853 for (auto &Base : ClassDecl->bases()) { 14854 // C++11 [class.copy]p28: 14855 // It is unspecified whether subobjects representing virtual base classes 14856 // are assigned more than once by the implicitly-defined copy assignment 14857 // operator. 14858 // FIXME: Do not assign to a vbase that will be assigned by some other base 14859 // class. For a move-assignment, this can result in the vbase being moved 14860 // multiple times. 14861 14862 // Form the assignment: 14863 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 14864 QualType BaseType = Base.getType().getUnqualifiedType(); 14865 if (!BaseType->isRecordType()) { 14866 Invalid = true; 14867 continue; 14868 } 14869 14870 CXXCastPath BasePath; 14871 BasePath.push_back(&Base); 14872 14873 // Construct the "from" expression, which is an implicit cast to the 14874 // appropriately-qualified base type. 14875 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 14876 14877 // Dereference "this". 14878 DerefBuilder DerefThis(This); 14879 14880 // Implicitly cast "this" to the appropriately-qualified base type. 14881 CastBuilder To(DerefThis, 14882 Context.getQualifiedType( 14883 BaseType, MoveAssignOperator->getMethodQualifiers()), 14884 VK_LValue, BasePath); 14885 14886 // Build the move. 14887 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 14888 To, From, 14889 /*CopyingBaseSubobject=*/true, 14890 /*Copying=*/false); 14891 if (Move.isInvalid()) { 14892 MoveAssignOperator->setInvalidDecl(); 14893 return; 14894 } 14895 14896 // Success! Record the move. 14897 Statements.push_back(Move.getAs<Expr>()); 14898 } 14899 14900 // Assign non-static members. 14901 for (auto *Field : ClassDecl->fields()) { 14902 // FIXME: We should form some kind of AST representation for the implied 14903 // memcpy in a union copy operation. 14904 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14905 continue; 14906 14907 if (Field->isInvalidDecl()) { 14908 Invalid = true; 14909 continue; 14910 } 14911 14912 // Check for members of reference type; we can't move those. 14913 if (Field->getType()->isReferenceType()) { 14914 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14915 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14916 Diag(Field->getLocation(), diag::note_declared_at); 14917 Invalid = true; 14918 continue; 14919 } 14920 14921 // Check for members of const-qualified, non-class type. 14922 QualType BaseType = Context.getBaseElementType(Field->getType()); 14923 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14924 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14925 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14926 Diag(Field->getLocation(), diag::note_declared_at); 14927 Invalid = true; 14928 continue; 14929 } 14930 14931 // Suppress assigning zero-width bitfields. 14932 if (Field->isZeroLengthBitField(Context)) 14933 continue; 14934 14935 QualType FieldType = Field->getType().getNonReferenceType(); 14936 if (FieldType->isIncompleteArrayType()) { 14937 assert(ClassDecl->hasFlexibleArrayMember() && 14938 "Incomplete array type is not valid"); 14939 continue; 14940 } 14941 14942 // Build references to the field in the object we're copying from and to. 14943 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14944 LookupMemberName); 14945 MemberLookup.addDecl(Field); 14946 MemberLookup.resolveKind(); 14947 MemberBuilder From(MoveOther, OtherRefType, 14948 /*IsArrow=*/false, MemberLookup); 14949 MemberBuilder To(This, getCurrentThisType(), 14950 /*IsArrow=*/true, MemberLookup); 14951 14952 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 14953 "Member reference with rvalue base must be rvalue except for reference " 14954 "members, which aren't allowed for move assignment."); 14955 14956 // Build the move of this field. 14957 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 14958 To, From, 14959 /*CopyingBaseSubobject=*/false, 14960 /*Copying=*/false); 14961 if (Move.isInvalid()) { 14962 MoveAssignOperator->setInvalidDecl(); 14963 return; 14964 } 14965 14966 // Success! Record the copy. 14967 Statements.push_back(Move.getAs<Stmt>()); 14968 } 14969 14970 if (!Invalid) { 14971 // Add a "return *this;" 14972 ExprResult ThisObj = 14973 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14974 14975 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14976 if (Return.isInvalid()) 14977 Invalid = true; 14978 else 14979 Statements.push_back(Return.getAs<Stmt>()); 14980 } 14981 14982 if (Invalid) { 14983 MoveAssignOperator->setInvalidDecl(); 14984 return; 14985 } 14986 14987 StmtResult Body; 14988 { 14989 CompoundScopeRAII CompoundScope(*this); 14990 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14991 /*isStmtExpr=*/false); 14992 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14993 } 14994 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 14995 MoveAssignOperator->markUsed(Context); 14996 14997 if (ASTMutationListener *L = getASTMutationListener()) { 14998 L->CompletedImplicitDefinition(MoveAssignOperator); 14999 } 15000 } 15001 15002 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 15003 CXXRecordDecl *ClassDecl) { 15004 // C++ [class.copy]p4: 15005 // If the class definition does not explicitly declare a copy 15006 // constructor, one is declared implicitly. 15007 assert(ClassDecl->needsImplicitCopyConstructor()); 15008 15009 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 15010 if (DSM.isAlreadyBeingDeclared()) 15011 return nullptr; 15012 15013 QualType ClassType = Context.getTypeDeclType(ClassDecl); 15014 QualType ArgType = ClassType; 15015 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 15016 if (Const) 15017 ArgType = ArgType.withConst(); 15018 15019 LangAS AS = getDefaultCXXMethodAddrSpace(); 15020 if (AS != LangAS::Default) 15021 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 15022 15023 ArgType = Context.getLValueReferenceType(ArgType); 15024 15025 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 15026 CXXCopyConstructor, 15027 Const); 15028 15029 DeclarationName Name 15030 = Context.DeclarationNames.getCXXConstructorName( 15031 Context.getCanonicalType(ClassType)); 15032 SourceLocation ClassLoc = ClassDecl->getLocation(); 15033 DeclarationNameInfo NameInfo(Name, ClassLoc); 15034 15035 // An implicitly-declared copy constructor is an inline public 15036 // member of its class. 15037 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 15038 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 15039 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 15040 /*isInline=*/true, 15041 /*isImplicitlyDeclared=*/true, 15042 Constexpr ? ConstexprSpecKind::Constexpr 15043 : ConstexprSpecKind::Unspecified); 15044 CopyConstructor->setAccess(AS_public); 15045 CopyConstructor->setDefaulted(); 15046 15047 if (getLangOpts().CUDA) { 15048 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 15049 CopyConstructor, 15050 /* ConstRHS */ Const, 15051 /* Diagnose */ false); 15052 } 15053 15054 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 15055 15056 // During template instantiation of special member functions we need a 15057 // reliable TypeSourceInfo for the parameter types in order to allow functions 15058 // to be substituted. 15059 TypeSourceInfo *TSI = nullptr; 15060 if (inTemplateInstantiation() && ClassDecl->isLambda()) 15061 TSI = Context.getTrivialTypeSourceInfo(ArgType); 15062 15063 // Add the parameter to the constructor. 15064 ParmVarDecl *FromParam = 15065 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc, 15066 /*IdentifierInfo=*/nullptr, ArgType, 15067 /*TInfo=*/TSI, SC_None, nullptr); 15068 CopyConstructor->setParams(FromParam); 15069 15070 CopyConstructor->setTrivial( 15071 ClassDecl->needsOverloadResolutionForCopyConstructor() 15072 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 15073 : ClassDecl->hasTrivialCopyConstructor()); 15074 15075 CopyConstructor->setTrivialForCall( 15076 ClassDecl->hasAttr<TrivialABIAttr>() || 15077 (ClassDecl->needsOverloadResolutionForCopyConstructor() 15078 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 15079 TAH_ConsiderTrivialABI) 15080 : ClassDecl->hasTrivialCopyConstructorForCall())); 15081 15082 // Note that we have declared this constructor. 15083 ++getASTContext().NumImplicitCopyConstructorsDeclared; 15084 15085 Scope *S = getScopeForContext(ClassDecl); 15086 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 15087 15088 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 15089 ClassDecl->setImplicitCopyConstructorIsDeleted(); 15090 SetDeclDeleted(CopyConstructor, ClassLoc); 15091 } 15092 15093 if (S) 15094 PushOnScopeChains(CopyConstructor, S, false); 15095 ClassDecl->addDecl(CopyConstructor); 15096 15097 return CopyConstructor; 15098 } 15099 15100 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 15101 CXXConstructorDecl *CopyConstructor) { 15102 assert((CopyConstructor->isDefaulted() && 15103 CopyConstructor->isCopyConstructor() && 15104 !CopyConstructor->doesThisDeclarationHaveABody() && 15105 !CopyConstructor->isDeleted()) && 15106 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 15107 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 15108 return; 15109 15110 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 15111 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 15112 15113 SynthesizedFunctionScope Scope(*this, CopyConstructor); 15114 15115 // The exception specification is needed because we are defining the 15116 // function. 15117 ResolveExceptionSpec(CurrentLocation, 15118 CopyConstructor->getType()->castAs<FunctionProtoType>()); 15119 MarkVTableUsed(CurrentLocation, ClassDecl); 15120 15121 // Add a context note for diagnostics produced after this point. 15122 Scope.addContextNote(CurrentLocation); 15123 15124 // C++11 [class.copy]p7: 15125 // The [definition of an implicitly declared copy constructor] is 15126 // deprecated if the class has a user-declared copy assignment operator 15127 // or a user-declared destructor. 15128 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 15129 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 15130 15131 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 15132 CopyConstructor->setInvalidDecl(); 15133 } else { 15134 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 15135 ? CopyConstructor->getEndLoc() 15136 : CopyConstructor->getLocation(); 15137 Sema::CompoundScopeRAII CompoundScope(*this); 15138 CopyConstructor->setBody( 15139 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 15140 CopyConstructor->markUsed(Context); 15141 } 15142 15143 if (ASTMutationListener *L = getASTMutationListener()) { 15144 L->CompletedImplicitDefinition(CopyConstructor); 15145 } 15146 } 15147 15148 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 15149 CXXRecordDecl *ClassDecl) { 15150 assert(ClassDecl->needsImplicitMoveConstructor()); 15151 15152 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 15153 if (DSM.isAlreadyBeingDeclared()) 15154 return nullptr; 15155 15156 QualType ClassType = Context.getTypeDeclType(ClassDecl); 15157 15158 QualType ArgType = ClassType; 15159 LangAS AS = getDefaultCXXMethodAddrSpace(); 15160 if (AS != LangAS::Default) 15161 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 15162 ArgType = Context.getRValueReferenceType(ArgType); 15163 15164 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 15165 CXXMoveConstructor, 15166 false); 15167 15168 DeclarationName Name 15169 = Context.DeclarationNames.getCXXConstructorName( 15170 Context.getCanonicalType(ClassType)); 15171 SourceLocation ClassLoc = ClassDecl->getLocation(); 15172 DeclarationNameInfo NameInfo(Name, ClassLoc); 15173 15174 // C++11 [class.copy]p11: 15175 // An implicitly-declared copy/move constructor is an inline public 15176 // member of its class. 15177 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 15178 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 15179 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 15180 /*isInline=*/true, 15181 /*isImplicitlyDeclared=*/true, 15182 Constexpr ? ConstexprSpecKind::Constexpr 15183 : ConstexprSpecKind::Unspecified); 15184 MoveConstructor->setAccess(AS_public); 15185 MoveConstructor->setDefaulted(); 15186 15187 if (getLangOpts().CUDA) { 15188 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 15189 MoveConstructor, 15190 /* ConstRHS */ false, 15191 /* Diagnose */ false); 15192 } 15193 15194 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 15195 15196 // Add the parameter to the constructor. 15197 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 15198 ClassLoc, ClassLoc, 15199 /*IdentifierInfo=*/nullptr, 15200 ArgType, /*TInfo=*/nullptr, 15201 SC_None, nullptr); 15202 MoveConstructor->setParams(FromParam); 15203 15204 MoveConstructor->setTrivial( 15205 ClassDecl->needsOverloadResolutionForMoveConstructor() 15206 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 15207 : ClassDecl->hasTrivialMoveConstructor()); 15208 15209 MoveConstructor->setTrivialForCall( 15210 ClassDecl->hasAttr<TrivialABIAttr>() || 15211 (ClassDecl->needsOverloadResolutionForMoveConstructor() 15212 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 15213 TAH_ConsiderTrivialABI) 15214 : ClassDecl->hasTrivialMoveConstructorForCall())); 15215 15216 // Note that we have declared this constructor. 15217 ++getASTContext().NumImplicitMoveConstructorsDeclared; 15218 15219 Scope *S = getScopeForContext(ClassDecl); 15220 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 15221 15222 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 15223 ClassDecl->setImplicitMoveConstructorIsDeleted(); 15224 SetDeclDeleted(MoveConstructor, ClassLoc); 15225 } 15226 15227 if (S) 15228 PushOnScopeChains(MoveConstructor, S, false); 15229 ClassDecl->addDecl(MoveConstructor); 15230 15231 return MoveConstructor; 15232 } 15233 15234 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 15235 CXXConstructorDecl *MoveConstructor) { 15236 assert((MoveConstructor->isDefaulted() && 15237 MoveConstructor->isMoveConstructor() && 15238 !MoveConstructor->doesThisDeclarationHaveABody() && 15239 !MoveConstructor->isDeleted()) && 15240 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 15241 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 15242 return; 15243 15244 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 15245 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 15246 15247 SynthesizedFunctionScope Scope(*this, MoveConstructor); 15248 15249 // The exception specification is needed because we are defining the 15250 // function. 15251 ResolveExceptionSpec(CurrentLocation, 15252 MoveConstructor->getType()->castAs<FunctionProtoType>()); 15253 MarkVTableUsed(CurrentLocation, ClassDecl); 15254 15255 // Add a context note for diagnostics produced after this point. 15256 Scope.addContextNote(CurrentLocation); 15257 15258 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 15259 MoveConstructor->setInvalidDecl(); 15260 } else { 15261 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 15262 ? MoveConstructor->getEndLoc() 15263 : MoveConstructor->getLocation(); 15264 Sema::CompoundScopeRAII CompoundScope(*this); 15265 MoveConstructor->setBody(ActOnCompoundStmt( 15266 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 15267 MoveConstructor->markUsed(Context); 15268 } 15269 15270 if (ASTMutationListener *L = getASTMutationListener()) { 15271 L->CompletedImplicitDefinition(MoveConstructor); 15272 } 15273 } 15274 15275 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 15276 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 15277 } 15278 15279 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 15280 SourceLocation CurrentLocation, 15281 CXXConversionDecl *Conv) { 15282 SynthesizedFunctionScope Scope(*this, Conv); 15283 assert(!Conv->getReturnType()->isUndeducedType()); 15284 15285 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType(); 15286 CallingConv CC = 15287 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv(); 15288 15289 CXXRecordDecl *Lambda = Conv->getParent(); 15290 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 15291 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC); 15292 15293 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 15294 CallOp = InstantiateFunctionDeclaration( 15295 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 15296 if (!CallOp) 15297 return; 15298 15299 Invoker = InstantiateFunctionDeclaration( 15300 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 15301 if (!Invoker) 15302 return; 15303 } 15304 15305 if (CallOp->isInvalidDecl()) 15306 return; 15307 15308 // Mark the call operator referenced (and add to pending instantiations 15309 // if necessary). 15310 // For both the conversion and static-invoker template specializations 15311 // we construct their body's in this function, so no need to add them 15312 // to the PendingInstantiations. 15313 MarkFunctionReferenced(CurrentLocation, CallOp); 15314 15315 // Fill in the __invoke function with a dummy implementation. IR generation 15316 // will fill in the actual details. Update its type in case it contained 15317 // an 'auto'. 15318 Invoker->markUsed(Context); 15319 Invoker->setReferenced(); 15320 Invoker->setType(Conv->getReturnType()->getPointeeType()); 15321 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 15322 15323 // Construct the body of the conversion function { return __invoke; }. 15324 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 15325 VK_LValue, Conv->getLocation()); 15326 assert(FunctionRef && "Can't refer to __invoke function?"); 15327 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 15328 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 15329 Conv->getLocation())); 15330 Conv->markUsed(Context); 15331 Conv->setReferenced(); 15332 15333 if (ASTMutationListener *L = getASTMutationListener()) { 15334 L->CompletedImplicitDefinition(Conv); 15335 L->CompletedImplicitDefinition(Invoker); 15336 } 15337 } 15338 15339 15340 15341 void Sema::DefineImplicitLambdaToBlockPointerConversion( 15342 SourceLocation CurrentLocation, 15343 CXXConversionDecl *Conv) 15344 { 15345 assert(!Conv->getParent()->isGenericLambda()); 15346 15347 SynthesizedFunctionScope Scope(*this, Conv); 15348 15349 // Copy-initialize the lambda object as needed to capture it. 15350 Expr *This = ActOnCXXThis(CurrentLocation).get(); 15351 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 15352 15353 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 15354 Conv->getLocation(), 15355 Conv, DerefThis); 15356 15357 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 15358 // behavior. Note that only the general conversion function does this 15359 // (since it's unusable otherwise); in the case where we inline the 15360 // block literal, it has block literal lifetime semantics. 15361 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 15362 BuildBlock = ImplicitCastExpr::Create( 15363 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject, 15364 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride()); 15365 15366 if (BuildBlock.isInvalid()) { 15367 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15368 Conv->setInvalidDecl(); 15369 return; 15370 } 15371 15372 // Create the return statement that returns the block from the conversion 15373 // function. 15374 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 15375 if (Return.isInvalid()) { 15376 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15377 Conv->setInvalidDecl(); 15378 return; 15379 } 15380 15381 // Set the body of the conversion function. 15382 Stmt *ReturnS = Return.get(); 15383 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 15384 Conv->getLocation())); 15385 Conv->markUsed(Context); 15386 15387 // We're done; notify the mutation listener, if any. 15388 if (ASTMutationListener *L = getASTMutationListener()) { 15389 L->CompletedImplicitDefinition(Conv); 15390 } 15391 } 15392 15393 /// Determine whether the given list arguments contains exactly one 15394 /// "real" (non-default) argument. 15395 static bool hasOneRealArgument(MultiExprArg Args) { 15396 switch (Args.size()) { 15397 case 0: 15398 return false; 15399 15400 default: 15401 if (!Args[1]->isDefaultArgument()) 15402 return false; 15403 15404 LLVM_FALLTHROUGH; 15405 case 1: 15406 return !Args[0]->isDefaultArgument(); 15407 } 15408 15409 return false; 15410 } 15411 15412 ExprResult 15413 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15414 NamedDecl *FoundDecl, 15415 CXXConstructorDecl *Constructor, 15416 MultiExprArg ExprArgs, 15417 bool HadMultipleCandidates, 15418 bool IsListInitialization, 15419 bool IsStdInitListInitialization, 15420 bool RequiresZeroInit, 15421 unsigned ConstructKind, 15422 SourceRange ParenRange) { 15423 bool Elidable = false; 15424 15425 // C++0x [class.copy]p34: 15426 // When certain criteria are met, an implementation is allowed to 15427 // omit the copy/move construction of a class object, even if the 15428 // copy/move constructor and/or destructor for the object have 15429 // side effects. [...] 15430 // - when a temporary class object that has not been bound to a 15431 // reference (12.2) would be copied/moved to a class object 15432 // with the same cv-unqualified type, the copy/move operation 15433 // can be omitted by constructing the temporary object 15434 // directly into the target of the omitted copy/move 15435 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 15436 // FIXME: Converting constructors should also be accepted. 15437 // But to fix this, the logic that digs down into a CXXConstructExpr 15438 // to find the source object needs to handle it. 15439 // Right now it assumes the source object is passed directly as the 15440 // first argument. 15441 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 15442 Expr *SubExpr = ExprArgs[0]; 15443 // FIXME: Per above, this is also incorrect if we want to accept 15444 // converting constructors, as isTemporaryObject will 15445 // reject temporaries with different type from the 15446 // CXXRecord itself. 15447 Elidable = SubExpr->isTemporaryObject( 15448 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 15449 } 15450 15451 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 15452 FoundDecl, Constructor, 15453 Elidable, ExprArgs, HadMultipleCandidates, 15454 IsListInitialization, 15455 IsStdInitListInitialization, RequiresZeroInit, 15456 ConstructKind, ParenRange); 15457 } 15458 15459 ExprResult 15460 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15461 NamedDecl *FoundDecl, 15462 CXXConstructorDecl *Constructor, 15463 bool Elidable, 15464 MultiExprArg ExprArgs, 15465 bool HadMultipleCandidates, 15466 bool IsListInitialization, 15467 bool IsStdInitListInitialization, 15468 bool RequiresZeroInit, 15469 unsigned ConstructKind, 15470 SourceRange ParenRange) { 15471 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 15472 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 15473 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 15474 return ExprError(); 15475 } 15476 15477 return BuildCXXConstructExpr( 15478 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 15479 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 15480 RequiresZeroInit, ConstructKind, ParenRange); 15481 } 15482 15483 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 15484 /// including handling of its default argument expressions. 15485 ExprResult 15486 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15487 CXXConstructorDecl *Constructor, 15488 bool Elidable, 15489 MultiExprArg ExprArgs, 15490 bool HadMultipleCandidates, 15491 bool IsListInitialization, 15492 bool IsStdInitListInitialization, 15493 bool RequiresZeroInit, 15494 unsigned ConstructKind, 15495 SourceRange ParenRange) { 15496 assert(declaresSameEntity( 15497 Constructor->getParent(), 15498 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 15499 "given constructor for wrong type"); 15500 MarkFunctionReferenced(ConstructLoc, Constructor); 15501 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 15502 return ExprError(); 15503 if (getLangOpts().SYCLIsDevice && 15504 !checkSYCLDeviceFunction(ConstructLoc, Constructor)) 15505 return ExprError(); 15506 15507 return CheckForImmediateInvocation( 15508 CXXConstructExpr::Create( 15509 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 15510 HadMultipleCandidates, IsListInitialization, 15511 IsStdInitListInitialization, RequiresZeroInit, 15512 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 15513 ParenRange), 15514 Constructor); 15515 } 15516 15517 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 15518 assert(Field->hasInClassInitializer()); 15519 15520 // If we already have the in-class initializer nothing needs to be done. 15521 if (Field->getInClassInitializer()) 15522 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15523 15524 // If we might have already tried and failed to instantiate, don't try again. 15525 if (Field->isInvalidDecl()) 15526 return ExprError(); 15527 15528 // Maybe we haven't instantiated the in-class initializer. Go check the 15529 // pattern FieldDecl to see if it has one. 15530 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 15531 15532 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 15533 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 15534 DeclContext::lookup_result Lookup = 15535 ClassPattern->lookup(Field->getDeclName()); 15536 15537 FieldDecl *Pattern = nullptr; 15538 for (auto L : Lookup) { 15539 if (isa<FieldDecl>(L)) { 15540 Pattern = cast<FieldDecl>(L); 15541 break; 15542 } 15543 } 15544 assert(Pattern && "We must have set the Pattern!"); 15545 15546 if (!Pattern->hasInClassInitializer() || 15547 InstantiateInClassInitializer(Loc, Field, Pattern, 15548 getTemplateInstantiationArgs(Field))) { 15549 // Don't diagnose this again. 15550 Field->setInvalidDecl(); 15551 return ExprError(); 15552 } 15553 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15554 } 15555 15556 // DR1351: 15557 // If the brace-or-equal-initializer of a non-static data member 15558 // invokes a defaulted default constructor of its class or of an 15559 // enclosing class in a potentially evaluated subexpression, the 15560 // program is ill-formed. 15561 // 15562 // This resolution is unworkable: the exception specification of the 15563 // default constructor can be needed in an unevaluated context, in 15564 // particular, in the operand of a noexcept-expression, and we can be 15565 // unable to compute an exception specification for an enclosed class. 15566 // 15567 // Any attempt to resolve the exception specification of a defaulted default 15568 // constructor before the initializer is lexically complete will ultimately 15569 // come here at which point we can diagnose it. 15570 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 15571 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed) 15572 << OutermostClass << Field; 15573 Diag(Field->getEndLoc(), 15574 diag::note_default_member_initializer_not_yet_parsed); 15575 // Recover by marking the field invalid, unless we're in a SFINAE context. 15576 if (!isSFINAEContext()) 15577 Field->setInvalidDecl(); 15578 return ExprError(); 15579 } 15580 15581 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 15582 if (VD->isInvalidDecl()) return; 15583 // If initializing the variable failed, don't also diagnose problems with 15584 // the destructor, they're likely related. 15585 if (VD->getInit() && VD->getInit()->containsErrors()) 15586 return; 15587 15588 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 15589 if (ClassDecl->isInvalidDecl()) return; 15590 if (ClassDecl->hasIrrelevantDestructor()) return; 15591 if (ClassDecl->isDependentContext()) return; 15592 15593 if (VD->isNoDestroy(getASTContext())) 15594 return; 15595 15596 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15597 15598 // If this is an array, we'll require the destructor during initialization, so 15599 // we can skip over this. We still want to emit exit-time destructor warnings 15600 // though. 15601 if (!VD->getType()->isArrayType()) { 15602 MarkFunctionReferenced(VD->getLocation(), Destructor); 15603 CheckDestructorAccess(VD->getLocation(), Destructor, 15604 PDiag(diag::err_access_dtor_var) 15605 << VD->getDeclName() << VD->getType()); 15606 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 15607 } 15608 15609 if (Destructor->isTrivial()) return; 15610 15611 // If the destructor is constexpr, check whether the variable has constant 15612 // destruction now. 15613 if (Destructor->isConstexpr()) { 15614 bool HasConstantInit = false; 15615 if (VD->getInit() && !VD->getInit()->isValueDependent()) 15616 HasConstantInit = VD->evaluateValue(); 15617 SmallVector<PartialDiagnosticAt, 8> Notes; 15618 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && 15619 HasConstantInit) { 15620 Diag(VD->getLocation(), 15621 diag::err_constexpr_var_requires_const_destruction) << VD; 15622 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 15623 Diag(Notes[I].first, Notes[I].second); 15624 } 15625 } 15626 15627 if (!VD->hasGlobalStorage()) return; 15628 15629 // Emit warning for non-trivial dtor in global scope (a real global, 15630 // class-static, function-static). 15631 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 15632 15633 // TODO: this should be re-enabled for static locals by !CXAAtExit 15634 if (!VD->isStaticLocal()) 15635 Diag(VD->getLocation(), diag::warn_global_destructor); 15636 } 15637 15638 /// Given a constructor and the set of arguments provided for the 15639 /// constructor, convert the arguments and add any required default arguments 15640 /// to form a proper call to this constructor. 15641 /// 15642 /// \returns true if an error occurred, false otherwise. 15643 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 15644 QualType DeclInitType, MultiExprArg ArgsPtr, 15645 SourceLocation Loc, 15646 SmallVectorImpl<Expr *> &ConvertedArgs, 15647 bool AllowExplicit, 15648 bool IsListInitialization) { 15649 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 15650 unsigned NumArgs = ArgsPtr.size(); 15651 Expr **Args = ArgsPtr.data(); 15652 15653 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); 15654 unsigned NumParams = Proto->getNumParams(); 15655 15656 // If too few arguments are available, we'll fill in the rest with defaults. 15657 if (NumArgs < NumParams) 15658 ConvertedArgs.reserve(NumParams); 15659 else 15660 ConvertedArgs.reserve(NumArgs); 15661 15662 VariadicCallType CallType = 15663 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 15664 SmallVector<Expr *, 8> AllArgs; 15665 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 15666 Proto, 0, 15667 llvm::makeArrayRef(Args, NumArgs), 15668 AllArgs, 15669 CallType, AllowExplicit, 15670 IsListInitialization); 15671 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 15672 15673 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 15674 15675 CheckConstructorCall(Constructor, DeclInitType, 15676 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 15677 Proto, Loc); 15678 15679 return Invalid; 15680 } 15681 15682 static inline bool 15683 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 15684 const FunctionDecl *FnDecl) { 15685 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 15686 if (isa<NamespaceDecl>(DC)) { 15687 return SemaRef.Diag(FnDecl->getLocation(), 15688 diag::err_operator_new_delete_declared_in_namespace) 15689 << FnDecl->getDeclName(); 15690 } 15691 15692 if (isa<TranslationUnitDecl>(DC) && 15693 FnDecl->getStorageClass() == SC_Static) { 15694 return SemaRef.Diag(FnDecl->getLocation(), 15695 diag::err_operator_new_delete_declared_static) 15696 << FnDecl->getDeclName(); 15697 } 15698 15699 return false; 15700 } 15701 15702 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, 15703 const PointerType *PtrTy) { 15704 auto &Ctx = SemaRef.Context; 15705 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers(); 15706 PtrQuals.removeAddressSpace(); 15707 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType( 15708 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals))); 15709 } 15710 15711 static inline bool 15712 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 15713 CanQualType ExpectedResultType, 15714 CanQualType ExpectedFirstParamType, 15715 unsigned DependentParamTypeDiag, 15716 unsigned InvalidParamTypeDiag) { 15717 QualType ResultType = 15718 FnDecl->getType()->castAs<FunctionType>()->getReturnType(); 15719 15720 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15721 // The operator is valid on any address space for OpenCL. 15722 // Drop address space from actual and expected result types. 15723 if (const auto *PtrTy = ResultType->getAs<PointerType>()) 15724 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15725 15726 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>()) 15727 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15728 } 15729 15730 // Check that the result type is what we expect. 15731 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) { 15732 // Reject even if the type is dependent; an operator delete function is 15733 // required to have a non-dependent result type. 15734 return SemaRef.Diag( 15735 FnDecl->getLocation(), 15736 ResultType->isDependentType() 15737 ? diag::err_operator_new_delete_dependent_result_type 15738 : diag::err_operator_new_delete_invalid_result_type) 15739 << FnDecl->getDeclName() << ExpectedResultType; 15740 } 15741 15742 // A function template must have at least 2 parameters. 15743 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 15744 return SemaRef.Diag(FnDecl->getLocation(), 15745 diag::err_operator_new_delete_template_too_few_parameters) 15746 << FnDecl->getDeclName(); 15747 15748 // The function decl must have at least 1 parameter. 15749 if (FnDecl->getNumParams() == 0) 15750 return SemaRef.Diag(FnDecl->getLocation(), 15751 diag::err_operator_new_delete_too_few_parameters) 15752 << FnDecl->getDeclName(); 15753 15754 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 15755 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15756 // The operator is valid on any address space for OpenCL. 15757 // Drop address space from actual and expected first parameter types. 15758 if (const auto *PtrTy = 15759 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) 15760 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15761 15762 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>()) 15763 ExpectedFirstParamType = 15764 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15765 } 15766 15767 // Check that the first parameter type is what we expect. 15768 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 15769 ExpectedFirstParamType) { 15770 // The first parameter type is not allowed to be dependent. As a tentative 15771 // DR resolution, we allow a dependent parameter type if it is the right 15772 // type anyway, to allow destroying operator delete in class templates. 15773 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType() 15774 ? DependentParamTypeDiag 15775 : InvalidParamTypeDiag) 15776 << FnDecl->getDeclName() << ExpectedFirstParamType; 15777 } 15778 15779 return false; 15780 } 15781 15782 static bool 15783 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 15784 // C++ [basic.stc.dynamic.allocation]p1: 15785 // A program is ill-formed if an allocation function is declared in a 15786 // namespace scope other than global scope or declared static in global 15787 // scope. 15788 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15789 return true; 15790 15791 CanQualType SizeTy = 15792 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 15793 15794 // C++ [basic.stc.dynamic.allocation]p1: 15795 // The return type shall be void*. The first parameter shall have type 15796 // std::size_t. 15797 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 15798 SizeTy, 15799 diag::err_operator_new_dependent_param_type, 15800 diag::err_operator_new_param_type)) 15801 return true; 15802 15803 // C++ [basic.stc.dynamic.allocation]p1: 15804 // The first parameter shall not have an associated default argument. 15805 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 15806 return SemaRef.Diag(FnDecl->getLocation(), 15807 diag::err_operator_new_default_arg) 15808 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 15809 15810 return false; 15811 } 15812 15813 static bool 15814 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 15815 // C++ [basic.stc.dynamic.deallocation]p1: 15816 // A program is ill-formed if deallocation functions are declared in a 15817 // namespace scope other than global scope or declared static in global 15818 // scope. 15819 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15820 return true; 15821 15822 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 15823 15824 // C++ P0722: 15825 // Within a class C, the first parameter of a destroying operator delete 15826 // shall be of type C *. The first parameter of any other deallocation 15827 // function shall be of type void *. 15828 CanQualType ExpectedFirstParamType = 15829 MD && MD->isDestroyingOperatorDelete() 15830 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 15831 SemaRef.Context.getRecordType(MD->getParent()))) 15832 : SemaRef.Context.VoidPtrTy; 15833 15834 // C++ [basic.stc.dynamic.deallocation]p2: 15835 // Each deallocation function shall return void 15836 if (CheckOperatorNewDeleteTypes( 15837 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 15838 diag::err_operator_delete_dependent_param_type, 15839 diag::err_operator_delete_param_type)) 15840 return true; 15841 15842 // C++ P0722: 15843 // A destroying operator delete shall be a usual deallocation function. 15844 if (MD && !MD->getParent()->isDependentContext() && 15845 MD->isDestroyingOperatorDelete() && 15846 !SemaRef.isUsualDeallocationFunction(MD)) { 15847 SemaRef.Diag(MD->getLocation(), 15848 diag::err_destroying_operator_delete_not_usual); 15849 return true; 15850 } 15851 15852 return false; 15853 } 15854 15855 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 15856 /// of this overloaded operator is well-formed. If so, returns false; 15857 /// otherwise, emits appropriate diagnostics and returns true. 15858 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 15859 assert(FnDecl && FnDecl->isOverloadedOperator() && 15860 "Expected an overloaded operator declaration"); 15861 15862 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 15863 15864 // C++ [over.oper]p5: 15865 // The allocation and deallocation functions, operator new, 15866 // operator new[], operator delete and operator delete[], are 15867 // described completely in 3.7.3. The attributes and restrictions 15868 // found in the rest of this subclause do not apply to them unless 15869 // explicitly stated in 3.7.3. 15870 if (Op == OO_Delete || Op == OO_Array_Delete) 15871 return CheckOperatorDeleteDeclaration(*this, FnDecl); 15872 15873 if (Op == OO_New || Op == OO_Array_New) 15874 return CheckOperatorNewDeclaration(*this, FnDecl); 15875 15876 // C++ [over.oper]p6: 15877 // An operator function shall either be a non-static member 15878 // function or be a non-member function and have at least one 15879 // parameter whose type is a class, a reference to a class, an 15880 // enumeration, or a reference to an enumeration. 15881 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 15882 if (MethodDecl->isStatic()) 15883 return Diag(FnDecl->getLocation(), 15884 diag::err_operator_overload_static) << FnDecl->getDeclName(); 15885 } else { 15886 bool ClassOrEnumParam = false; 15887 for (auto Param : FnDecl->parameters()) { 15888 QualType ParamType = Param->getType().getNonReferenceType(); 15889 if (ParamType->isDependentType() || ParamType->isRecordType() || 15890 ParamType->isEnumeralType()) { 15891 ClassOrEnumParam = true; 15892 break; 15893 } 15894 } 15895 15896 if (!ClassOrEnumParam) 15897 return Diag(FnDecl->getLocation(), 15898 diag::err_operator_overload_needs_class_or_enum) 15899 << FnDecl->getDeclName(); 15900 } 15901 15902 // C++ [over.oper]p8: 15903 // An operator function cannot have default arguments (8.3.6), 15904 // except where explicitly stated below. 15905 // 15906 // Only the function-call operator (C++ [over.call]p1) and the subscript 15907 // operator (CWG2507) allow default arguments. 15908 if (Op != OO_Call) { 15909 ParmVarDecl *FirstDefaultedParam = nullptr; 15910 for (auto Param : FnDecl->parameters()) { 15911 if (Param->hasDefaultArg()) { 15912 FirstDefaultedParam = Param; 15913 break; 15914 } 15915 } 15916 if (FirstDefaultedParam) { 15917 if (Op == OO_Subscript) { 15918 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b 15919 ? diag::ext_subscript_overload 15920 : diag::error_subscript_overload) 15921 << FnDecl->getDeclName() << 1 15922 << FirstDefaultedParam->getDefaultArgRange(); 15923 } else { 15924 return Diag(FirstDefaultedParam->getLocation(), 15925 diag::err_operator_overload_default_arg) 15926 << FnDecl->getDeclName() 15927 << FirstDefaultedParam->getDefaultArgRange(); 15928 } 15929 } 15930 } 15931 15932 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 15933 { false, false, false } 15934 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 15935 , { Unary, Binary, MemberOnly } 15936 #include "clang/Basic/OperatorKinds.def" 15937 }; 15938 15939 bool CanBeUnaryOperator = OperatorUses[Op][0]; 15940 bool CanBeBinaryOperator = OperatorUses[Op][1]; 15941 bool MustBeMemberOperator = OperatorUses[Op][2]; 15942 15943 // C++ [over.oper]p8: 15944 // [...] Operator functions cannot have more or fewer parameters 15945 // than the number required for the corresponding operator, as 15946 // described in the rest of this subclause. 15947 unsigned NumParams = FnDecl->getNumParams() 15948 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 15949 if (Op != OO_Call && Op != OO_Subscript && 15950 ((NumParams == 1 && !CanBeUnaryOperator) || 15951 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) || 15952 (NumParams > 2))) { 15953 // We have the wrong number of parameters. 15954 unsigned ErrorKind; 15955 if (CanBeUnaryOperator && CanBeBinaryOperator) { 15956 ErrorKind = 2; // 2 -> unary or binary. 15957 } else if (CanBeUnaryOperator) { 15958 ErrorKind = 0; // 0 -> unary 15959 } else { 15960 assert(CanBeBinaryOperator && 15961 "All non-call overloaded operators are unary or binary!"); 15962 ErrorKind = 1; // 1 -> binary 15963 } 15964 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 15965 << FnDecl->getDeclName() << NumParams << ErrorKind; 15966 } 15967 15968 if (Op == OO_Subscript && NumParams != 2) { 15969 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b 15970 ? diag::ext_subscript_overload 15971 : diag::error_subscript_overload) 15972 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2); 15973 } 15974 15975 // Overloaded operators other than operator() and operator[] cannot be 15976 // variadic. 15977 if (Op != OO_Call && 15978 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { 15979 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 15980 << FnDecl->getDeclName(); 15981 } 15982 15983 // Some operators must be non-static member functions. 15984 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 15985 return Diag(FnDecl->getLocation(), 15986 diag::err_operator_overload_must_be_member) 15987 << FnDecl->getDeclName(); 15988 } 15989 15990 // C++ [over.inc]p1: 15991 // The user-defined function called operator++ implements the 15992 // prefix and postfix ++ operator. If this function is a member 15993 // function with no parameters, or a non-member function with one 15994 // parameter of class or enumeration type, it defines the prefix 15995 // increment operator ++ for objects of that type. If the function 15996 // is a member function with one parameter (which shall be of type 15997 // int) or a non-member function with two parameters (the second 15998 // of which shall be of type int), it defines the postfix 15999 // increment operator ++ for objects of that type. 16000 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 16001 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 16002 QualType ParamType = LastParam->getType(); 16003 16004 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 16005 !ParamType->isDependentType()) 16006 return Diag(LastParam->getLocation(), 16007 diag::err_operator_overload_post_incdec_must_be_int) 16008 << LastParam->getType() << (Op == OO_MinusMinus); 16009 } 16010 16011 return false; 16012 } 16013 16014 static bool 16015 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 16016 FunctionTemplateDecl *TpDecl) { 16017 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 16018 16019 // Must have one or two template parameters. 16020 if (TemplateParams->size() == 1) { 16021 NonTypeTemplateParmDecl *PmDecl = 16022 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 16023 16024 // The template parameter must be a char parameter pack. 16025 if (PmDecl && PmDecl->isTemplateParameterPack() && 16026 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 16027 return false; 16028 16029 // C++20 [over.literal]p5: 16030 // A string literal operator template is a literal operator template 16031 // whose template-parameter-list comprises a single non-type 16032 // template-parameter of class type. 16033 // 16034 // As a DR resolution, we also allow placeholders for deduced class 16035 // template specializations. 16036 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl && 16037 !PmDecl->isTemplateParameterPack() && 16038 (PmDecl->getType()->isRecordType() || 16039 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>())) 16040 return false; 16041 } else if (TemplateParams->size() == 2) { 16042 TemplateTypeParmDecl *PmType = 16043 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 16044 NonTypeTemplateParmDecl *PmArgs = 16045 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 16046 16047 // The second template parameter must be a parameter pack with the 16048 // first template parameter as its type. 16049 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 16050 PmArgs->isTemplateParameterPack()) { 16051 const TemplateTypeParmType *TArgs = 16052 PmArgs->getType()->getAs<TemplateTypeParmType>(); 16053 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 16054 TArgs->getIndex() == PmType->getIndex()) { 16055 if (!SemaRef.inTemplateInstantiation()) 16056 SemaRef.Diag(TpDecl->getLocation(), 16057 diag::ext_string_literal_operator_template); 16058 return false; 16059 } 16060 } 16061 } 16062 16063 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 16064 diag::err_literal_operator_template) 16065 << TpDecl->getTemplateParameters()->getSourceRange(); 16066 return true; 16067 } 16068 16069 /// CheckLiteralOperatorDeclaration - Check whether the declaration 16070 /// of this literal operator function is well-formed. If so, returns 16071 /// false; otherwise, emits appropriate diagnostics and returns true. 16072 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 16073 if (isa<CXXMethodDecl>(FnDecl)) { 16074 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 16075 << FnDecl->getDeclName(); 16076 return true; 16077 } 16078 16079 if (FnDecl->isExternC()) { 16080 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 16081 if (const LinkageSpecDecl *LSD = 16082 FnDecl->getDeclContext()->getExternCContext()) 16083 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 16084 return true; 16085 } 16086 16087 // This might be the definition of a literal operator template. 16088 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 16089 16090 // This might be a specialization of a literal operator template. 16091 if (!TpDecl) 16092 TpDecl = FnDecl->getPrimaryTemplate(); 16093 16094 // template <char...> type operator "" name() and 16095 // template <class T, T...> type operator "" name() are the only valid 16096 // template signatures, and the only valid signatures with no parameters. 16097 // 16098 // C++20 also allows template <SomeClass T> type operator "" name(). 16099 if (TpDecl) { 16100 if (FnDecl->param_size() != 0) { 16101 Diag(FnDecl->getLocation(), 16102 diag::err_literal_operator_template_with_params); 16103 return true; 16104 } 16105 16106 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 16107 return true; 16108 16109 } else if (FnDecl->param_size() == 1) { 16110 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 16111 16112 QualType ParamType = Param->getType().getUnqualifiedType(); 16113 16114 // Only unsigned long long int, long double, any character type, and const 16115 // char * are allowed as the only parameters. 16116 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 16117 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 16118 Context.hasSameType(ParamType, Context.CharTy) || 16119 Context.hasSameType(ParamType, Context.WideCharTy) || 16120 Context.hasSameType(ParamType, Context.Char8Ty) || 16121 Context.hasSameType(ParamType, Context.Char16Ty) || 16122 Context.hasSameType(ParamType, Context.Char32Ty)) { 16123 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 16124 QualType InnerType = Ptr->getPointeeType(); 16125 16126 // Pointer parameter must be a const char *. 16127 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 16128 Context.CharTy) && 16129 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 16130 Diag(Param->getSourceRange().getBegin(), 16131 diag::err_literal_operator_param) 16132 << ParamType << "'const char *'" << Param->getSourceRange(); 16133 return true; 16134 } 16135 16136 } else if (ParamType->isRealFloatingType()) { 16137 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 16138 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 16139 return true; 16140 16141 } else if (ParamType->isIntegerType()) { 16142 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 16143 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 16144 return true; 16145 16146 } else { 16147 Diag(Param->getSourceRange().getBegin(), 16148 diag::err_literal_operator_invalid_param) 16149 << ParamType << Param->getSourceRange(); 16150 return true; 16151 } 16152 16153 } else if (FnDecl->param_size() == 2) { 16154 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 16155 16156 // First, verify that the first parameter is correct. 16157 16158 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 16159 16160 // Two parameter function must have a pointer to const as a 16161 // first parameter; let's strip those qualifiers. 16162 const PointerType *PT = FirstParamType->getAs<PointerType>(); 16163 16164 if (!PT) { 16165 Diag((*Param)->getSourceRange().getBegin(), 16166 diag::err_literal_operator_param) 16167 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16168 return true; 16169 } 16170 16171 QualType PointeeType = PT->getPointeeType(); 16172 // First parameter must be const 16173 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 16174 Diag((*Param)->getSourceRange().getBegin(), 16175 diag::err_literal_operator_param) 16176 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16177 return true; 16178 } 16179 16180 QualType InnerType = PointeeType.getUnqualifiedType(); 16181 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 16182 // const char32_t* are allowed as the first parameter to a two-parameter 16183 // function 16184 if (!(Context.hasSameType(InnerType, Context.CharTy) || 16185 Context.hasSameType(InnerType, Context.WideCharTy) || 16186 Context.hasSameType(InnerType, Context.Char8Ty) || 16187 Context.hasSameType(InnerType, Context.Char16Ty) || 16188 Context.hasSameType(InnerType, Context.Char32Ty))) { 16189 Diag((*Param)->getSourceRange().getBegin(), 16190 diag::err_literal_operator_param) 16191 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16192 return true; 16193 } 16194 16195 // Move on to the second and final parameter. 16196 ++Param; 16197 16198 // The second parameter must be a std::size_t. 16199 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 16200 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 16201 Diag((*Param)->getSourceRange().getBegin(), 16202 diag::err_literal_operator_param) 16203 << SecondParamType << Context.getSizeType() 16204 << (*Param)->getSourceRange(); 16205 return true; 16206 } 16207 } else { 16208 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 16209 return true; 16210 } 16211 16212 // Parameters are good. 16213 16214 // A parameter-declaration-clause containing a default argument is not 16215 // equivalent to any of the permitted forms. 16216 for (auto Param : FnDecl->parameters()) { 16217 if (Param->hasDefaultArg()) { 16218 Diag(Param->getDefaultArgRange().getBegin(), 16219 diag::err_literal_operator_default_argument) 16220 << Param->getDefaultArgRange(); 16221 break; 16222 } 16223 } 16224 16225 StringRef LiteralName 16226 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 16227 if (LiteralName[0] != '_' && 16228 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 16229 // C++11 [usrlit.suffix]p1: 16230 // Literal suffix identifiers that do not start with an underscore 16231 // are reserved for future standardization. 16232 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 16233 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 16234 } 16235 16236 return false; 16237 } 16238 16239 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 16240 /// linkage specification, including the language and (if present) 16241 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 16242 /// language string literal. LBraceLoc, if valid, provides the location of 16243 /// the '{' brace. Otherwise, this linkage specification does not 16244 /// have any braces. 16245 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 16246 Expr *LangStr, 16247 SourceLocation LBraceLoc) { 16248 StringLiteral *Lit = cast<StringLiteral>(LangStr); 16249 if (!Lit->isAscii()) { 16250 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 16251 << LangStr->getSourceRange(); 16252 return nullptr; 16253 } 16254 16255 StringRef Lang = Lit->getString(); 16256 LinkageSpecDecl::LanguageIDs Language; 16257 if (Lang == "C") 16258 Language = LinkageSpecDecl::lang_c; 16259 else if (Lang == "C++") 16260 Language = LinkageSpecDecl::lang_cxx; 16261 else { 16262 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 16263 << LangStr->getSourceRange(); 16264 return nullptr; 16265 } 16266 16267 // FIXME: Add all the various semantics of linkage specifications 16268 16269 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 16270 LangStr->getExprLoc(), Language, 16271 LBraceLoc.isValid()); 16272 16273 /// C++ [module.unit]p7.2.3 16274 /// - Otherwise, if the declaration 16275 /// - ... 16276 /// - ... 16277 /// - appears within a linkage-specification, 16278 /// it is attached to the global module. 16279 /// 16280 /// If the declaration is already in global module fragment, we don't 16281 /// need to attach it again. 16282 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) { 16283 Module *GlobalModule = 16284 PushGlobalModuleFragment(ExternLoc, /*IsImplicit=*/true); 16285 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate); 16286 D->setLocalOwningModule(GlobalModule); 16287 } 16288 16289 CurContext->addDecl(D); 16290 PushDeclContext(S, D); 16291 return D; 16292 } 16293 16294 /// ActOnFinishLinkageSpecification - Complete the definition of 16295 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 16296 /// valid, it's the position of the closing '}' brace in a linkage 16297 /// specification that uses braces. 16298 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 16299 Decl *LinkageSpec, 16300 SourceLocation RBraceLoc) { 16301 if (RBraceLoc.isValid()) { 16302 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 16303 LSDecl->setRBraceLoc(RBraceLoc); 16304 } 16305 16306 // If the current module doesn't has Parent, it implies that the 16307 // LinkageSpec isn't in the module created by itself. So we don't 16308 // need to pop it. 16309 if (getLangOpts().CPlusPlusModules && getCurrentModule() && 16310 getCurrentModule()->isGlobalModule() && getCurrentModule()->Parent) 16311 PopGlobalModuleFragment(); 16312 16313 PopDeclContext(); 16314 return LinkageSpec; 16315 } 16316 16317 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 16318 const ParsedAttributesView &AttrList, 16319 SourceLocation SemiLoc) { 16320 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 16321 // Attribute declarations appertain to empty declaration so we handle 16322 // them here. 16323 ProcessDeclAttributeList(S, ED, AttrList); 16324 16325 CurContext->addDecl(ED); 16326 return ED; 16327 } 16328 16329 /// Perform semantic analysis for the variable declaration that 16330 /// occurs within a C++ catch clause, returning the newly-created 16331 /// variable. 16332 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 16333 TypeSourceInfo *TInfo, 16334 SourceLocation StartLoc, 16335 SourceLocation Loc, 16336 IdentifierInfo *Name) { 16337 bool Invalid = false; 16338 QualType ExDeclType = TInfo->getType(); 16339 16340 // Arrays and functions decay. 16341 if (ExDeclType->isArrayType()) 16342 ExDeclType = Context.getArrayDecayedType(ExDeclType); 16343 else if (ExDeclType->isFunctionType()) 16344 ExDeclType = Context.getPointerType(ExDeclType); 16345 16346 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 16347 // The exception-declaration shall not denote a pointer or reference to an 16348 // incomplete type, other than [cv] void*. 16349 // N2844 forbids rvalue references. 16350 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 16351 Diag(Loc, diag::err_catch_rvalue_ref); 16352 Invalid = true; 16353 } 16354 16355 if (ExDeclType->isVariablyModifiedType()) { 16356 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 16357 Invalid = true; 16358 } 16359 16360 QualType BaseType = ExDeclType; 16361 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 16362 unsigned DK = diag::err_catch_incomplete; 16363 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 16364 BaseType = Ptr->getPointeeType(); 16365 Mode = 1; 16366 DK = diag::err_catch_incomplete_ptr; 16367 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 16368 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 16369 BaseType = Ref->getPointeeType(); 16370 Mode = 2; 16371 DK = diag::err_catch_incomplete_ref; 16372 } 16373 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 16374 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 16375 Invalid = true; 16376 16377 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) { 16378 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType; 16379 Invalid = true; 16380 } 16381 16382 if (!Invalid && !ExDeclType->isDependentType() && 16383 RequireNonAbstractType(Loc, ExDeclType, 16384 diag::err_abstract_type_in_decl, 16385 AbstractVariableType)) 16386 Invalid = true; 16387 16388 // Only the non-fragile NeXT runtime currently supports C++ catches 16389 // of ObjC types, and no runtime supports catching ObjC types by value. 16390 if (!Invalid && getLangOpts().ObjC) { 16391 QualType T = ExDeclType; 16392 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 16393 T = RT->getPointeeType(); 16394 16395 if (T->isObjCObjectType()) { 16396 Diag(Loc, diag::err_objc_object_catch); 16397 Invalid = true; 16398 } else if (T->isObjCObjectPointerType()) { 16399 // FIXME: should this be a test for macosx-fragile specifically? 16400 if (getLangOpts().ObjCRuntime.isFragile()) 16401 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 16402 } 16403 } 16404 16405 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 16406 ExDeclType, TInfo, SC_None); 16407 ExDecl->setExceptionVariable(true); 16408 16409 // In ARC, infer 'retaining' for variables of retainable type. 16410 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 16411 Invalid = true; 16412 16413 if (!Invalid && !ExDeclType->isDependentType()) { 16414 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 16415 // Insulate this from anything else we might currently be parsing. 16416 EnterExpressionEvaluationContext scope( 16417 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 16418 16419 // C++ [except.handle]p16: 16420 // The object declared in an exception-declaration or, if the 16421 // exception-declaration does not specify a name, a temporary (12.2) is 16422 // copy-initialized (8.5) from the exception object. [...] 16423 // The object is destroyed when the handler exits, after the destruction 16424 // of any automatic objects initialized within the handler. 16425 // 16426 // We just pretend to initialize the object with itself, then make sure 16427 // it can be destroyed later. 16428 QualType initType = Context.getExceptionObjectType(ExDeclType); 16429 16430 InitializedEntity entity = 16431 InitializedEntity::InitializeVariable(ExDecl); 16432 InitializationKind initKind = 16433 InitializationKind::CreateCopy(Loc, SourceLocation()); 16434 16435 Expr *opaqueValue = 16436 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 16437 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 16438 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 16439 if (result.isInvalid()) 16440 Invalid = true; 16441 else { 16442 // If the constructor used was non-trivial, set this as the 16443 // "initializer". 16444 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 16445 if (!construct->getConstructor()->isTrivial()) { 16446 Expr *init = MaybeCreateExprWithCleanups(construct); 16447 ExDecl->setInit(init); 16448 } 16449 16450 // And make sure it's destructable. 16451 FinalizeVarWithDestructor(ExDecl, recordType); 16452 } 16453 } 16454 } 16455 16456 if (Invalid) 16457 ExDecl->setInvalidDecl(); 16458 16459 return ExDecl; 16460 } 16461 16462 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 16463 /// handler. 16464 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 16465 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16466 bool Invalid = D.isInvalidType(); 16467 16468 // Check for unexpanded parameter packs. 16469 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16470 UPPC_ExceptionType)) { 16471 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 16472 D.getIdentifierLoc()); 16473 Invalid = true; 16474 } 16475 16476 IdentifierInfo *II = D.getIdentifier(); 16477 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 16478 LookupOrdinaryName, 16479 ForVisibleRedeclaration)) { 16480 // The scope should be freshly made just for us. There is just no way 16481 // it contains any previous declaration, except for function parameters in 16482 // a function-try-block's catch statement. 16483 assert(!S->isDeclScope(PrevDecl)); 16484 if (isDeclInScope(PrevDecl, CurContext, S)) { 16485 Diag(D.getIdentifierLoc(), diag::err_redefinition) 16486 << D.getIdentifier(); 16487 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 16488 Invalid = true; 16489 } else if (PrevDecl->isTemplateParameter()) 16490 // Maybe we will complain about the shadowed template parameter. 16491 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16492 } 16493 16494 if (D.getCXXScopeSpec().isSet() && !Invalid) { 16495 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 16496 << D.getCXXScopeSpec().getRange(); 16497 Invalid = true; 16498 } 16499 16500 VarDecl *ExDecl = BuildExceptionDeclaration( 16501 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 16502 if (Invalid) 16503 ExDecl->setInvalidDecl(); 16504 16505 // Add the exception declaration into this scope. 16506 if (II) 16507 PushOnScopeChains(ExDecl, S); 16508 else 16509 CurContext->addDecl(ExDecl); 16510 16511 ProcessDeclAttributes(S, ExDecl, D); 16512 return ExDecl; 16513 } 16514 16515 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16516 Expr *AssertExpr, 16517 Expr *AssertMessageExpr, 16518 SourceLocation RParenLoc) { 16519 StringLiteral *AssertMessage = 16520 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 16521 16522 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 16523 return nullptr; 16524 16525 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 16526 AssertMessage, RParenLoc, false); 16527 } 16528 16529 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16530 Expr *AssertExpr, 16531 StringLiteral *AssertMessage, 16532 SourceLocation RParenLoc, 16533 bool Failed) { 16534 assert(AssertExpr != nullptr && "Expected non-null condition"); 16535 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 16536 !Failed) { 16537 // In a static_assert-declaration, the constant-expression shall be a 16538 // constant expression that can be contextually converted to bool. 16539 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 16540 if (Converted.isInvalid()) 16541 Failed = true; 16542 16543 ExprResult FullAssertExpr = 16544 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 16545 /*DiscardedValue*/ false, 16546 /*IsConstexpr*/ true); 16547 if (FullAssertExpr.isInvalid()) 16548 Failed = true; 16549 else 16550 AssertExpr = FullAssertExpr.get(); 16551 16552 llvm::APSInt Cond; 16553 if (!Failed && VerifyIntegerConstantExpression( 16554 AssertExpr, &Cond, 16555 diag::err_static_assert_expression_is_not_constant) 16556 .isInvalid()) 16557 Failed = true; 16558 16559 if (!Failed && !Cond) { 16560 SmallString<256> MsgBuffer; 16561 llvm::raw_svector_ostream Msg(MsgBuffer); 16562 if (AssertMessage) 16563 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 16564 16565 Expr *InnerCond = nullptr; 16566 std::string InnerCondDescription; 16567 std::tie(InnerCond, InnerCondDescription) = 16568 findFailedBooleanCondition(Converted.get()); 16569 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 16570 // Drill down into concept specialization expressions to see why they 16571 // weren't satisfied. 16572 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16573 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16574 ConstraintSatisfaction Satisfaction; 16575 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 16576 DiagnoseUnsatisfiedConstraint(Satisfaction); 16577 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 16578 && !isa<IntegerLiteral>(InnerCond)) { 16579 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 16580 << InnerCondDescription << !AssertMessage 16581 << Msg.str() << InnerCond->getSourceRange(); 16582 } else { 16583 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16584 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16585 } 16586 Failed = true; 16587 } 16588 } else { 16589 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 16590 /*DiscardedValue*/false, 16591 /*IsConstexpr*/true); 16592 if (FullAssertExpr.isInvalid()) 16593 Failed = true; 16594 else 16595 AssertExpr = FullAssertExpr.get(); 16596 } 16597 16598 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 16599 AssertExpr, AssertMessage, RParenLoc, 16600 Failed); 16601 16602 CurContext->addDecl(Decl); 16603 return Decl; 16604 } 16605 16606 /// Perform semantic analysis of the given friend type declaration. 16607 /// 16608 /// \returns A friend declaration that. 16609 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 16610 SourceLocation FriendLoc, 16611 TypeSourceInfo *TSInfo) { 16612 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 16613 16614 QualType T = TSInfo->getType(); 16615 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 16616 16617 // C++03 [class.friend]p2: 16618 // An elaborated-type-specifier shall be used in a friend declaration 16619 // for a class.* 16620 // 16621 // * The class-key of the elaborated-type-specifier is required. 16622 if (!CodeSynthesisContexts.empty()) { 16623 // Do not complain about the form of friend template types during any kind 16624 // of code synthesis. For template instantiation, we will have complained 16625 // when the template was defined. 16626 } else { 16627 if (!T->isElaboratedTypeSpecifier()) { 16628 // If we evaluated the type to a record type, suggest putting 16629 // a tag in front. 16630 if (const RecordType *RT = T->getAs<RecordType>()) { 16631 RecordDecl *RD = RT->getDecl(); 16632 16633 SmallString<16> InsertionText(" "); 16634 InsertionText += RD->getKindName(); 16635 16636 Diag(TypeRange.getBegin(), 16637 getLangOpts().CPlusPlus11 ? 16638 diag::warn_cxx98_compat_unelaborated_friend_type : 16639 diag::ext_unelaborated_friend_type) 16640 << (unsigned) RD->getTagKind() 16641 << T 16642 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 16643 InsertionText); 16644 } else { 16645 Diag(FriendLoc, 16646 getLangOpts().CPlusPlus11 ? 16647 diag::warn_cxx98_compat_nonclass_type_friend : 16648 diag::ext_nonclass_type_friend) 16649 << T 16650 << TypeRange; 16651 } 16652 } else if (T->getAs<EnumType>()) { 16653 Diag(FriendLoc, 16654 getLangOpts().CPlusPlus11 ? 16655 diag::warn_cxx98_compat_enum_friend : 16656 diag::ext_enum_friend) 16657 << T 16658 << TypeRange; 16659 } 16660 16661 // C++11 [class.friend]p3: 16662 // A friend declaration that does not declare a function shall have one 16663 // of the following forms: 16664 // friend elaborated-type-specifier ; 16665 // friend simple-type-specifier ; 16666 // friend typename-specifier ; 16667 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 16668 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 16669 } 16670 16671 // If the type specifier in a friend declaration designates a (possibly 16672 // cv-qualified) class type, that class is declared as a friend; otherwise, 16673 // the friend declaration is ignored. 16674 return FriendDecl::Create(Context, CurContext, 16675 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 16676 FriendLoc); 16677 } 16678 16679 /// Handle a friend tag declaration where the scope specifier was 16680 /// templated. 16681 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 16682 unsigned TagSpec, SourceLocation TagLoc, 16683 CXXScopeSpec &SS, IdentifierInfo *Name, 16684 SourceLocation NameLoc, 16685 const ParsedAttributesView &Attr, 16686 MultiTemplateParamsArg TempParamLists) { 16687 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16688 16689 bool IsMemberSpecialization = false; 16690 bool Invalid = false; 16691 16692 if (TemplateParameterList *TemplateParams = 16693 MatchTemplateParametersToScopeSpecifier( 16694 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 16695 IsMemberSpecialization, Invalid)) { 16696 if (TemplateParams->size() > 0) { 16697 // This is a declaration of a class template. 16698 if (Invalid) 16699 return nullptr; 16700 16701 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 16702 NameLoc, Attr, TemplateParams, AS_public, 16703 /*ModulePrivateLoc=*/SourceLocation(), 16704 FriendLoc, TempParamLists.size() - 1, 16705 TempParamLists.data()).get(); 16706 } else { 16707 // The "template<>" header is extraneous. 16708 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16709 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16710 IsMemberSpecialization = true; 16711 } 16712 } 16713 16714 if (Invalid) return nullptr; 16715 16716 bool isAllExplicitSpecializations = true; 16717 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 16718 if (TempParamLists[I]->size()) { 16719 isAllExplicitSpecializations = false; 16720 break; 16721 } 16722 } 16723 16724 // FIXME: don't ignore attributes. 16725 16726 // If it's explicit specializations all the way down, just forget 16727 // about the template header and build an appropriate non-templated 16728 // friend. TODO: for source fidelity, remember the headers. 16729 if (isAllExplicitSpecializations) { 16730 if (SS.isEmpty()) { 16731 bool Owned = false; 16732 bool IsDependent = false; 16733 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 16734 Attr, AS_public, 16735 /*ModulePrivateLoc=*/SourceLocation(), 16736 MultiTemplateParamsArg(), Owned, IsDependent, 16737 /*ScopedEnumKWLoc=*/SourceLocation(), 16738 /*ScopedEnumUsesClassTag=*/false, 16739 /*UnderlyingType=*/TypeResult(), 16740 /*IsTypeSpecifier=*/false, 16741 /*IsTemplateParamOrArg=*/false); 16742 } 16743 16744 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 16745 ElaboratedTypeKeyword Keyword 16746 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16747 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 16748 *Name, NameLoc); 16749 if (T.isNull()) 16750 return nullptr; 16751 16752 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16753 if (isa<DependentNameType>(T)) { 16754 DependentNameTypeLoc TL = 16755 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16756 TL.setElaboratedKeywordLoc(TagLoc); 16757 TL.setQualifierLoc(QualifierLoc); 16758 TL.setNameLoc(NameLoc); 16759 } else { 16760 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 16761 TL.setElaboratedKeywordLoc(TagLoc); 16762 TL.setQualifierLoc(QualifierLoc); 16763 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 16764 } 16765 16766 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16767 TSI, FriendLoc, TempParamLists); 16768 Friend->setAccess(AS_public); 16769 CurContext->addDecl(Friend); 16770 return Friend; 16771 } 16772 16773 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 16774 16775 16776 16777 // Handle the case of a templated-scope friend class. e.g. 16778 // template <class T> class A<T>::B; 16779 // FIXME: we don't support these right now. 16780 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 16781 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 16782 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16783 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 16784 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16785 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16786 TL.setElaboratedKeywordLoc(TagLoc); 16787 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 16788 TL.setNameLoc(NameLoc); 16789 16790 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16791 TSI, FriendLoc, TempParamLists); 16792 Friend->setAccess(AS_public); 16793 Friend->setUnsupportedFriend(true); 16794 CurContext->addDecl(Friend); 16795 return Friend; 16796 } 16797 16798 /// Handle a friend type declaration. This works in tandem with 16799 /// ActOnTag. 16800 /// 16801 /// Notes on friend class templates: 16802 /// 16803 /// We generally treat friend class declarations as if they were 16804 /// declaring a class. So, for example, the elaborated type specifier 16805 /// in a friend declaration is required to obey the restrictions of a 16806 /// class-head (i.e. no typedefs in the scope chain), template 16807 /// parameters are required to match up with simple template-ids, &c. 16808 /// However, unlike when declaring a template specialization, it's 16809 /// okay to refer to a template specialization without an empty 16810 /// template parameter declaration, e.g. 16811 /// friend class A<T>::B<unsigned>; 16812 /// We permit this as a special case; if there are any template 16813 /// parameters present at all, require proper matching, i.e. 16814 /// template <> template \<class T> friend class A<int>::B; 16815 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 16816 MultiTemplateParamsArg TempParams) { 16817 SourceLocation Loc = DS.getBeginLoc(); 16818 16819 assert(DS.isFriendSpecified()); 16820 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16821 16822 // C++ [class.friend]p3: 16823 // A friend declaration that does not declare a function shall have one of 16824 // the following forms: 16825 // friend elaborated-type-specifier ; 16826 // friend simple-type-specifier ; 16827 // friend typename-specifier ; 16828 // 16829 // Any declaration with a type qualifier does not have that form. (It's 16830 // legal to specify a qualified type as a friend, you just can't write the 16831 // keywords.) 16832 if (DS.getTypeQualifiers()) { 16833 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 16834 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 16835 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 16836 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 16837 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 16838 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 16839 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 16840 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 16841 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 16842 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 16843 } 16844 16845 // Try to convert the decl specifier to a type. This works for 16846 // friend templates because ActOnTag never produces a ClassTemplateDecl 16847 // for a TUK_Friend. 16848 Declarator TheDeclarator(DS, DeclaratorContext::Member); 16849 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 16850 QualType T = TSI->getType(); 16851 if (TheDeclarator.isInvalidType()) 16852 return nullptr; 16853 16854 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 16855 return nullptr; 16856 16857 // This is definitely an error in C++98. It's probably meant to 16858 // be forbidden in C++0x, too, but the specification is just 16859 // poorly written. 16860 // 16861 // The problem is with declarations like the following: 16862 // template <T> friend A<T>::foo; 16863 // where deciding whether a class C is a friend or not now hinges 16864 // on whether there exists an instantiation of A that causes 16865 // 'foo' to equal C. There are restrictions on class-heads 16866 // (which we declare (by fiat) elaborated friend declarations to 16867 // be) that makes this tractable. 16868 // 16869 // FIXME: handle "template <> friend class A<T>;", which 16870 // is possibly well-formed? Who even knows? 16871 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 16872 Diag(Loc, diag::err_tagless_friend_type_template) 16873 << DS.getSourceRange(); 16874 return nullptr; 16875 } 16876 16877 // C++98 [class.friend]p1: A friend of a class is a function 16878 // or class that is not a member of the class . . . 16879 // This is fixed in DR77, which just barely didn't make the C++03 16880 // deadline. It's also a very silly restriction that seriously 16881 // affects inner classes and which nobody else seems to implement; 16882 // thus we never diagnose it, not even in -pedantic. 16883 // 16884 // But note that we could warn about it: it's always useless to 16885 // friend one of your own members (it's not, however, worthless to 16886 // friend a member of an arbitrary specialization of your template). 16887 16888 Decl *D; 16889 if (!TempParams.empty()) 16890 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 16891 TempParams, 16892 TSI, 16893 DS.getFriendSpecLoc()); 16894 else 16895 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 16896 16897 if (!D) 16898 return nullptr; 16899 16900 D->setAccess(AS_public); 16901 CurContext->addDecl(D); 16902 16903 return D; 16904 } 16905 16906 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 16907 MultiTemplateParamsArg TemplateParams) { 16908 const DeclSpec &DS = D.getDeclSpec(); 16909 16910 assert(DS.isFriendSpecified()); 16911 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16912 16913 SourceLocation Loc = D.getIdentifierLoc(); 16914 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16915 16916 // C++ [class.friend]p1 16917 // A friend of a class is a function or class.... 16918 // Note that this sees through typedefs, which is intended. 16919 // It *doesn't* see through dependent types, which is correct 16920 // according to [temp.arg.type]p3: 16921 // If a declaration acquires a function type through a 16922 // type dependent on a template-parameter and this causes 16923 // a declaration that does not use the syntactic form of a 16924 // function declarator to have a function type, the program 16925 // is ill-formed. 16926 if (!TInfo->getType()->isFunctionType()) { 16927 Diag(Loc, diag::err_unexpected_friend); 16928 16929 // It might be worthwhile to try to recover by creating an 16930 // appropriate declaration. 16931 return nullptr; 16932 } 16933 16934 // C++ [namespace.memdef]p3 16935 // - If a friend declaration in a non-local class first declares a 16936 // class or function, the friend class or function is a member 16937 // of the innermost enclosing namespace. 16938 // - The name of the friend is not found by simple name lookup 16939 // until a matching declaration is provided in that namespace 16940 // scope (either before or after the class declaration granting 16941 // friendship). 16942 // - If a friend function is called, its name may be found by the 16943 // name lookup that considers functions from namespaces and 16944 // classes associated with the types of the function arguments. 16945 // - When looking for a prior declaration of a class or a function 16946 // declared as a friend, scopes outside the innermost enclosing 16947 // namespace scope are not considered. 16948 16949 CXXScopeSpec &SS = D.getCXXScopeSpec(); 16950 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 16951 assert(NameInfo.getName()); 16952 16953 // Check for unexpanded parameter packs. 16954 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 16955 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 16956 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 16957 return nullptr; 16958 16959 // The context we found the declaration in, or in which we should 16960 // create the declaration. 16961 DeclContext *DC; 16962 Scope *DCScope = S; 16963 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 16964 ForExternalRedeclaration); 16965 16966 // There are five cases here. 16967 // - There's no scope specifier and we're in a local class. Only look 16968 // for functions declared in the immediately-enclosing block scope. 16969 // We recover from invalid scope qualifiers as if they just weren't there. 16970 FunctionDecl *FunctionContainingLocalClass = nullptr; 16971 if ((SS.isInvalid() || !SS.isSet()) && 16972 (FunctionContainingLocalClass = 16973 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 16974 // C++11 [class.friend]p11: 16975 // If a friend declaration appears in a local class and the name 16976 // specified is an unqualified name, a prior declaration is 16977 // looked up without considering scopes that are outside the 16978 // innermost enclosing non-class scope. For a friend function 16979 // declaration, if there is no prior declaration, the program is 16980 // ill-formed. 16981 16982 // Find the innermost enclosing non-class scope. This is the block 16983 // scope containing the local class definition (or for a nested class, 16984 // the outer local class). 16985 DCScope = S->getFnParent(); 16986 16987 // Look up the function name in the scope. 16988 Previous.clear(LookupLocalFriendName); 16989 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 16990 16991 if (!Previous.empty()) { 16992 // All possible previous declarations must have the same context: 16993 // either they were declared at block scope or they are members of 16994 // one of the enclosing local classes. 16995 DC = Previous.getRepresentativeDecl()->getDeclContext(); 16996 } else { 16997 // This is ill-formed, but provide the context that we would have 16998 // declared the function in, if we were permitted to, for error recovery. 16999 DC = FunctionContainingLocalClass; 17000 } 17001 adjustContextForLocalExternDecl(DC); 17002 17003 // C++ [class.friend]p6: 17004 // A function can be defined in a friend declaration of a class if and 17005 // only if the class is a non-local class (9.8), the function name is 17006 // unqualified, and the function has namespace scope. 17007 if (D.isFunctionDefinition()) { 17008 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 17009 } 17010 17011 // - There's no scope specifier, in which case we just go to the 17012 // appropriate scope and look for a function or function template 17013 // there as appropriate. 17014 } else if (SS.isInvalid() || !SS.isSet()) { 17015 // C++11 [namespace.memdef]p3: 17016 // If the name in a friend declaration is neither qualified nor 17017 // a template-id and the declaration is a function or an 17018 // elaborated-type-specifier, the lookup to determine whether 17019 // the entity has been previously declared shall not consider 17020 // any scopes outside the innermost enclosing namespace. 17021 bool isTemplateId = 17022 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 17023 17024 // Find the appropriate context according to the above. 17025 DC = CurContext; 17026 17027 // Skip class contexts. If someone can cite chapter and verse 17028 // for this behavior, that would be nice --- it's what GCC and 17029 // EDG do, and it seems like a reasonable intent, but the spec 17030 // really only says that checks for unqualified existing 17031 // declarations should stop at the nearest enclosing namespace, 17032 // not that they should only consider the nearest enclosing 17033 // namespace. 17034 while (DC->isRecord()) 17035 DC = DC->getParent(); 17036 17037 DeclContext *LookupDC = DC->getNonTransparentContext(); 17038 while (true) { 17039 LookupQualifiedName(Previous, LookupDC); 17040 17041 if (!Previous.empty()) { 17042 DC = LookupDC; 17043 break; 17044 } 17045 17046 if (isTemplateId) { 17047 if (isa<TranslationUnitDecl>(LookupDC)) break; 17048 } else { 17049 if (LookupDC->isFileContext()) break; 17050 } 17051 LookupDC = LookupDC->getParent(); 17052 } 17053 17054 DCScope = getScopeForDeclContext(S, DC); 17055 17056 // - There's a non-dependent scope specifier, in which case we 17057 // compute it and do a previous lookup there for a function 17058 // or function template. 17059 } else if (!SS.getScopeRep()->isDependent()) { 17060 DC = computeDeclContext(SS); 17061 if (!DC) return nullptr; 17062 17063 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 17064 17065 LookupQualifiedName(Previous, DC); 17066 17067 // C++ [class.friend]p1: A friend of a class is a function or 17068 // class that is not a member of the class . . . 17069 if (DC->Equals(CurContext)) 17070 Diag(DS.getFriendSpecLoc(), 17071 getLangOpts().CPlusPlus11 ? 17072 diag::warn_cxx98_compat_friend_is_member : 17073 diag::err_friend_is_member); 17074 17075 if (D.isFunctionDefinition()) { 17076 // C++ [class.friend]p6: 17077 // A function can be defined in a friend declaration of a class if and 17078 // only if the class is a non-local class (9.8), the function name is 17079 // unqualified, and the function has namespace scope. 17080 // 17081 // FIXME: We should only do this if the scope specifier names the 17082 // innermost enclosing namespace; otherwise the fixit changes the 17083 // meaning of the code. 17084 SemaDiagnosticBuilder DB 17085 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 17086 17087 DB << SS.getScopeRep(); 17088 if (DC->isFileContext()) 17089 DB << FixItHint::CreateRemoval(SS.getRange()); 17090 SS.clear(); 17091 } 17092 17093 // - There's a scope specifier that does not match any template 17094 // parameter lists, in which case we use some arbitrary context, 17095 // create a method or method template, and wait for instantiation. 17096 // - There's a scope specifier that does match some template 17097 // parameter lists, which we don't handle right now. 17098 } else { 17099 if (D.isFunctionDefinition()) { 17100 // C++ [class.friend]p6: 17101 // A function can be defined in a friend declaration of a class if and 17102 // only if the class is a non-local class (9.8), the function name is 17103 // unqualified, and the function has namespace scope. 17104 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 17105 << SS.getScopeRep(); 17106 } 17107 17108 DC = CurContext; 17109 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 17110 } 17111 17112 if (!DC->isRecord()) { 17113 int DiagArg = -1; 17114 switch (D.getName().getKind()) { 17115 case UnqualifiedIdKind::IK_ConstructorTemplateId: 17116 case UnqualifiedIdKind::IK_ConstructorName: 17117 DiagArg = 0; 17118 break; 17119 case UnqualifiedIdKind::IK_DestructorName: 17120 DiagArg = 1; 17121 break; 17122 case UnqualifiedIdKind::IK_ConversionFunctionId: 17123 DiagArg = 2; 17124 break; 17125 case UnqualifiedIdKind::IK_DeductionGuideName: 17126 DiagArg = 3; 17127 break; 17128 case UnqualifiedIdKind::IK_Identifier: 17129 case UnqualifiedIdKind::IK_ImplicitSelfParam: 17130 case UnqualifiedIdKind::IK_LiteralOperatorId: 17131 case UnqualifiedIdKind::IK_OperatorFunctionId: 17132 case UnqualifiedIdKind::IK_TemplateId: 17133 break; 17134 } 17135 // This implies that it has to be an operator or function. 17136 if (DiagArg >= 0) { 17137 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 17138 return nullptr; 17139 } 17140 } 17141 17142 // FIXME: This is an egregious hack to cope with cases where the scope stack 17143 // does not contain the declaration context, i.e., in an out-of-line 17144 // definition of a class. 17145 Scope FakeDCScope(S, Scope::DeclScope, Diags); 17146 if (!DCScope) { 17147 FakeDCScope.setEntity(DC); 17148 DCScope = &FakeDCScope; 17149 } 17150 17151 bool AddToScope = true; 17152 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 17153 TemplateParams, AddToScope); 17154 if (!ND) return nullptr; 17155 17156 assert(ND->getLexicalDeclContext() == CurContext); 17157 17158 // If we performed typo correction, we might have added a scope specifier 17159 // and changed the decl context. 17160 DC = ND->getDeclContext(); 17161 17162 // Add the function declaration to the appropriate lookup tables, 17163 // adjusting the redeclarations list as necessary. We don't 17164 // want to do this yet if the friending class is dependent. 17165 // 17166 // Also update the scope-based lookup if the target context's 17167 // lookup context is in lexical scope. 17168 if (!CurContext->isDependentContext()) { 17169 DC = DC->getRedeclContext(); 17170 DC->makeDeclVisibleInContext(ND); 17171 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 17172 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 17173 } 17174 17175 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 17176 D.getIdentifierLoc(), ND, 17177 DS.getFriendSpecLoc()); 17178 FrD->setAccess(AS_public); 17179 CurContext->addDecl(FrD); 17180 17181 if (ND->isInvalidDecl()) { 17182 FrD->setInvalidDecl(); 17183 } else { 17184 if (DC->isRecord()) CheckFriendAccess(ND); 17185 17186 FunctionDecl *FD; 17187 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 17188 FD = FTD->getTemplatedDecl(); 17189 else 17190 FD = cast<FunctionDecl>(ND); 17191 17192 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 17193 // default argument expression, that declaration shall be a definition 17194 // and shall be the only declaration of the function or function 17195 // template in the translation unit. 17196 if (functionDeclHasDefaultArgument(FD)) { 17197 // We can't look at FD->getPreviousDecl() because it may not have been set 17198 // if we're in a dependent context. If the function is known to be a 17199 // redeclaration, we will have narrowed Previous down to the right decl. 17200 if (D.isRedeclaration()) { 17201 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 17202 Diag(Previous.getRepresentativeDecl()->getLocation(), 17203 diag::note_previous_declaration); 17204 } else if (!D.isFunctionDefinition()) 17205 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 17206 } 17207 17208 // Mark templated-scope function declarations as unsupported. 17209 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 17210 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 17211 << SS.getScopeRep() << SS.getRange() 17212 << cast<CXXRecordDecl>(CurContext); 17213 FrD->setUnsupportedFriend(true); 17214 } 17215 } 17216 17217 warnOnReservedIdentifier(ND); 17218 17219 return ND; 17220 } 17221 17222 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 17223 AdjustDeclIfTemplate(Dcl); 17224 17225 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 17226 if (!Fn) { 17227 Diag(DelLoc, diag::err_deleted_non_function); 17228 return; 17229 } 17230 17231 // Deleted function does not have a body. 17232 Fn->setWillHaveBody(false); 17233 17234 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 17235 // Don't consider the implicit declaration we generate for explicit 17236 // specializations. FIXME: Do not generate these implicit declarations. 17237 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 17238 Prev->getPreviousDecl()) && 17239 !Prev->isDefined()) { 17240 Diag(DelLoc, diag::err_deleted_decl_not_first); 17241 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 17242 Prev->isImplicit() ? diag::note_previous_implicit_declaration 17243 : diag::note_previous_declaration); 17244 // We can't recover from this; the declaration might have already 17245 // been used. 17246 Fn->setInvalidDecl(); 17247 return; 17248 } 17249 17250 // To maintain the invariant that functions are only deleted on their first 17251 // declaration, mark the implicitly-instantiated declaration of the 17252 // explicitly-specialized function as deleted instead of marking the 17253 // instantiated redeclaration. 17254 Fn = Fn->getCanonicalDecl(); 17255 } 17256 17257 // dllimport/dllexport cannot be deleted. 17258 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 17259 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 17260 Fn->setInvalidDecl(); 17261 } 17262 17263 // C++11 [basic.start.main]p3: 17264 // A program that defines main as deleted [...] is ill-formed. 17265 if (Fn->isMain()) 17266 Diag(DelLoc, diag::err_deleted_main); 17267 17268 // C++11 [dcl.fct.def.delete]p4: 17269 // A deleted function is implicitly inline. 17270 Fn->setImplicitlyInline(); 17271 Fn->setDeletedAsWritten(); 17272 } 17273 17274 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 17275 if (!Dcl || Dcl->isInvalidDecl()) 17276 return; 17277 17278 auto *FD = dyn_cast<FunctionDecl>(Dcl); 17279 if (!FD) { 17280 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 17281 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 17282 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 17283 return; 17284 } 17285 } 17286 17287 Diag(DefaultLoc, diag::err_default_special_members) 17288 << getLangOpts().CPlusPlus20; 17289 return; 17290 } 17291 17292 // Reject if this can't possibly be a defaultable function. 17293 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 17294 if (!DefKind && 17295 // A dependent function that doesn't locally look defaultable can 17296 // still instantiate to a defaultable function if it's a constructor 17297 // or assignment operator. 17298 (!FD->isDependentContext() || 17299 (!isa<CXXConstructorDecl>(FD) && 17300 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 17301 Diag(DefaultLoc, diag::err_default_special_members) 17302 << getLangOpts().CPlusPlus20; 17303 return; 17304 } 17305 17306 // Issue compatibility warning. We already warned if the operator is 17307 // 'operator<=>' when parsing the '<=>' token. 17308 if (DefKind.isComparison() && 17309 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 17310 Diag(DefaultLoc, getLangOpts().CPlusPlus20 17311 ? diag::warn_cxx17_compat_defaulted_comparison 17312 : diag::ext_defaulted_comparison); 17313 } 17314 17315 FD->setDefaulted(); 17316 FD->setExplicitlyDefaulted(); 17317 17318 // Defer checking functions that are defaulted in a dependent context. 17319 if (FD->isDependentContext()) 17320 return; 17321 17322 // Unset that we will have a body for this function. We might not, 17323 // if it turns out to be trivial, and we don't need this marking now 17324 // that we've marked it as defaulted. 17325 FD->setWillHaveBody(false); 17326 17327 if (DefKind.isComparison()) { 17328 // If this comparison's defaulting occurs within the definition of its 17329 // lexical class context, we have to do the checking when complete. 17330 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext())) 17331 if (!RD->isCompleteDefinition()) 17332 return; 17333 } 17334 17335 // If this member fn was defaulted on its first declaration, we will have 17336 // already performed the checking in CheckCompletedCXXClass. Such a 17337 // declaration doesn't trigger an implicit definition. 17338 if (isa<CXXMethodDecl>(FD)) { 17339 const FunctionDecl *Primary = FD; 17340 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 17341 // Ask the template instantiation pattern that actually had the 17342 // '= default' on it. 17343 Primary = Pattern; 17344 if (Primary->getCanonicalDecl()->isDefaulted()) 17345 return; 17346 } 17347 17348 if (DefKind.isComparison()) { 17349 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison())) 17350 FD->setInvalidDecl(); 17351 else 17352 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison()); 17353 } else { 17354 auto *MD = cast<CXXMethodDecl>(FD); 17355 17356 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 17357 MD->setInvalidDecl(); 17358 else 17359 DefineDefaultedFunction(*this, MD, DefaultLoc); 17360 } 17361 } 17362 17363 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 17364 for (Stmt *SubStmt : S->children()) { 17365 if (!SubStmt) 17366 continue; 17367 if (isa<ReturnStmt>(SubStmt)) 17368 Self.Diag(SubStmt->getBeginLoc(), 17369 diag::err_return_in_constructor_handler); 17370 if (!isa<Expr>(SubStmt)) 17371 SearchForReturnInStmt(Self, SubStmt); 17372 } 17373 } 17374 17375 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 17376 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 17377 CXXCatchStmt *Handler = TryBlock->getHandler(I); 17378 SearchForReturnInStmt(*this, Handler); 17379 } 17380 } 17381 17382 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 17383 const CXXMethodDecl *Old) { 17384 const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); 17385 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); 17386 17387 if (OldFT->hasExtParameterInfos()) { 17388 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 17389 // A parameter of the overriding method should be annotated with noescape 17390 // if the corresponding parameter of the overridden method is annotated. 17391 if (OldFT->getExtParameterInfo(I).isNoEscape() && 17392 !NewFT->getExtParameterInfo(I).isNoEscape()) { 17393 Diag(New->getParamDecl(I)->getLocation(), 17394 diag::warn_overriding_method_missing_noescape); 17395 Diag(Old->getParamDecl(I)->getLocation(), 17396 diag::note_overridden_marked_noescape); 17397 } 17398 } 17399 17400 // Virtual overrides must have the same code_seg. 17401 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 17402 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 17403 if ((NewCSA || OldCSA) && 17404 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 17405 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 17406 Diag(Old->getLocation(), diag::note_previous_declaration); 17407 return true; 17408 } 17409 17410 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 17411 17412 // If the calling conventions match, everything is fine 17413 if (NewCC == OldCC) 17414 return false; 17415 17416 // If the calling conventions mismatch because the new function is static, 17417 // suppress the calling convention mismatch error; the error about static 17418 // function override (err_static_overrides_virtual from 17419 // Sema::CheckFunctionDeclaration) is more clear. 17420 if (New->getStorageClass() == SC_Static) 17421 return false; 17422 17423 Diag(New->getLocation(), 17424 diag::err_conflicting_overriding_cc_attributes) 17425 << New->getDeclName() << New->getType() << Old->getType(); 17426 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 17427 return true; 17428 } 17429 17430 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 17431 const CXXMethodDecl *Old) { 17432 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); 17433 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); 17434 17435 if (Context.hasSameType(NewTy, OldTy) || 17436 NewTy->isDependentType() || OldTy->isDependentType()) 17437 return false; 17438 17439 // Check if the return types are covariant 17440 QualType NewClassTy, OldClassTy; 17441 17442 /// Both types must be pointers or references to classes. 17443 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 17444 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 17445 NewClassTy = NewPT->getPointeeType(); 17446 OldClassTy = OldPT->getPointeeType(); 17447 } 17448 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 17449 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 17450 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 17451 NewClassTy = NewRT->getPointeeType(); 17452 OldClassTy = OldRT->getPointeeType(); 17453 } 17454 } 17455 } 17456 17457 // The return types aren't either both pointers or references to a class type. 17458 if (NewClassTy.isNull()) { 17459 Diag(New->getLocation(), 17460 diag::err_different_return_type_for_overriding_virtual_function) 17461 << New->getDeclName() << NewTy << OldTy 17462 << New->getReturnTypeSourceRange(); 17463 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17464 << Old->getReturnTypeSourceRange(); 17465 17466 return true; 17467 } 17468 17469 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 17470 // C++14 [class.virtual]p8: 17471 // If the class type in the covariant return type of D::f differs from 17472 // that of B::f, the class type in the return type of D::f shall be 17473 // complete at the point of declaration of D::f or shall be the class 17474 // type D. 17475 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 17476 if (!RT->isBeingDefined() && 17477 RequireCompleteType(New->getLocation(), NewClassTy, 17478 diag::err_covariant_return_incomplete, 17479 New->getDeclName())) 17480 return true; 17481 } 17482 17483 // Check if the new class derives from the old class. 17484 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 17485 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 17486 << New->getDeclName() << NewTy << OldTy 17487 << New->getReturnTypeSourceRange(); 17488 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17489 << Old->getReturnTypeSourceRange(); 17490 return true; 17491 } 17492 17493 // Check if we the conversion from derived to base is valid. 17494 if (CheckDerivedToBaseConversion( 17495 NewClassTy, OldClassTy, 17496 diag::err_covariant_return_inaccessible_base, 17497 diag::err_covariant_return_ambiguous_derived_to_base_conv, 17498 New->getLocation(), New->getReturnTypeSourceRange(), 17499 New->getDeclName(), nullptr)) { 17500 // FIXME: this note won't trigger for delayed access control 17501 // diagnostics, and it's impossible to get an undelayed error 17502 // here from access control during the original parse because 17503 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 17504 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17505 << Old->getReturnTypeSourceRange(); 17506 return true; 17507 } 17508 } 17509 17510 // The qualifiers of the return types must be the same. 17511 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 17512 Diag(New->getLocation(), 17513 diag::err_covariant_return_type_different_qualifications) 17514 << New->getDeclName() << NewTy << OldTy 17515 << New->getReturnTypeSourceRange(); 17516 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17517 << Old->getReturnTypeSourceRange(); 17518 return true; 17519 } 17520 17521 17522 // The new class type must have the same or less qualifiers as the old type. 17523 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 17524 Diag(New->getLocation(), 17525 diag::err_covariant_return_type_class_type_more_qualified) 17526 << New->getDeclName() << NewTy << OldTy 17527 << New->getReturnTypeSourceRange(); 17528 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17529 << Old->getReturnTypeSourceRange(); 17530 return true; 17531 } 17532 17533 return false; 17534 } 17535 17536 /// Mark the given method pure. 17537 /// 17538 /// \param Method the method to be marked pure. 17539 /// 17540 /// \param InitRange the source range that covers the "0" initializer. 17541 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 17542 SourceLocation EndLoc = InitRange.getEnd(); 17543 if (EndLoc.isValid()) 17544 Method->setRangeEnd(EndLoc); 17545 17546 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 17547 Method->setPure(); 17548 return false; 17549 } 17550 17551 if (!Method->isInvalidDecl()) 17552 Diag(Method->getLocation(), diag::err_non_virtual_pure) 17553 << Method->getDeclName() << InitRange; 17554 return true; 17555 } 17556 17557 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 17558 if (D->getFriendObjectKind()) 17559 Diag(D->getLocation(), diag::err_pure_friend); 17560 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 17561 CheckPureMethod(M, ZeroLoc); 17562 else 17563 Diag(D->getLocation(), diag::err_illegal_initializer); 17564 } 17565 17566 /// Determine whether the given declaration is a global variable or 17567 /// static data member. 17568 static bool isNonlocalVariable(const Decl *D) { 17569 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 17570 return Var->hasGlobalStorage(); 17571 17572 return false; 17573 } 17574 17575 /// Invoked when we are about to parse an initializer for the declaration 17576 /// 'Dcl'. 17577 /// 17578 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 17579 /// static data member of class X, names should be looked up in the scope of 17580 /// class X. If the declaration had a scope specifier, a scope will have 17581 /// been created and passed in for this purpose. Otherwise, S will be null. 17582 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 17583 // If there is no declaration, there was an error parsing it. 17584 if (!D || D->isInvalidDecl()) 17585 return; 17586 17587 // We will always have a nested name specifier here, but this declaration 17588 // might not be out of line if the specifier names the current namespace: 17589 // extern int n; 17590 // int ::n = 0; 17591 if (S && D->isOutOfLine()) 17592 EnterDeclaratorContext(S, D->getDeclContext()); 17593 17594 // If we are parsing the initializer for a static data member, push a 17595 // new expression evaluation context that is associated with this static 17596 // data member. 17597 if (isNonlocalVariable(D)) 17598 PushExpressionEvaluationContext( 17599 ExpressionEvaluationContext::PotentiallyEvaluated, D); 17600 } 17601 17602 /// Invoked after we are finished parsing an initializer for the declaration D. 17603 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 17604 // If there is no declaration, there was an error parsing it. 17605 if (!D || D->isInvalidDecl()) 17606 return; 17607 17608 if (isNonlocalVariable(D)) 17609 PopExpressionEvaluationContext(); 17610 17611 if (S && D->isOutOfLine()) 17612 ExitDeclaratorContext(S); 17613 } 17614 17615 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 17616 /// C++ if/switch/while/for statement. 17617 /// e.g: "if (int x = f()) {...}" 17618 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 17619 // C++ 6.4p2: 17620 // The declarator shall not specify a function or an array. 17621 // The type-specifier-seq shall not contain typedef and shall not declare a 17622 // new class or enumeration. 17623 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 17624 "Parser allowed 'typedef' as storage class of condition decl."); 17625 17626 Decl *Dcl = ActOnDeclarator(S, D); 17627 if (!Dcl) 17628 return true; 17629 17630 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 17631 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 17632 << D.getSourceRange(); 17633 return true; 17634 } 17635 17636 return Dcl; 17637 } 17638 17639 void Sema::LoadExternalVTableUses() { 17640 if (!ExternalSource) 17641 return; 17642 17643 SmallVector<ExternalVTableUse, 4> VTables; 17644 ExternalSource->ReadUsedVTables(VTables); 17645 SmallVector<VTableUse, 4> NewUses; 17646 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 17647 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 17648 = VTablesUsed.find(VTables[I].Record); 17649 // Even if a definition wasn't required before, it may be required now. 17650 if (Pos != VTablesUsed.end()) { 17651 if (!Pos->second && VTables[I].DefinitionRequired) 17652 Pos->second = true; 17653 continue; 17654 } 17655 17656 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 17657 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 17658 } 17659 17660 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 17661 } 17662 17663 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 17664 bool DefinitionRequired) { 17665 // Ignore any vtable uses in unevaluated operands or for classes that do 17666 // not have a vtable. 17667 if (!Class->isDynamicClass() || Class->isDependentContext() || 17668 CurContext->isDependentContext() || isUnevaluatedContext()) 17669 return; 17670 // Do not mark as used if compiling for the device outside of the target 17671 // region. 17672 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 17673 !isInOpenMPDeclareTargetContext() && 17674 !isInOpenMPTargetExecutionDirective()) { 17675 if (!DefinitionRequired) 17676 MarkVirtualMembersReferenced(Loc, Class); 17677 return; 17678 } 17679 17680 // Try to insert this class into the map. 17681 LoadExternalVTableUses(); 17682 Class = Class->getCanonicalDecl(); 17683 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 17684 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 17685 if (!Pos.second) { 17686 // If we already had an entry, check to see if we are promoting this vtable 17687 // to require a definition. If so, we need to reappend to the VTableUses 17688 // list, since we may have already processed the first entry. 17689 if (DefinitionRequired && !Pos.first->second) { 17690 Pos.first->second = true; 17691 } else { 17692 // Otherwise, we can early exit. 17693 return; 17694 } 17695 } else { 17696 // The Microsoft ABI requires that we perform the destructor body 17697 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 17698 // the deleting destructor is emitted with the vtable, not with the 17699 // destructor definition as in the Itanium ABI. 17700 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17701 CXXDestructorDecl *DD = Class->getDestructor(); 17702 if (DD && DD->isVirtual() && !DD->isDeleted()) { 17703 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 17704 // If this is an out-of-line declaration, marking it referenced will 17705 // not do anything. Manually call CheckDestructor to look up operator 17706 // delete(). 17707 ContextRAII SavedContext(*this, DD); 17708 CheckDestructor(DD); 17709 } else { 17710 MarkFunctionReferenced(Loc, Class->getDestructor()); 17711 } 17712 } 17713 } 17714 } 17715 17716 // Local classes need to have their virtual members marked 17717 // immediately. For all other classes, we mark their virtual members 17718 // at the end of the translation unit. 17719 if (Class->isLocalClass()) 17720 MarkVirtualMembersReferenced(Loc, Class); 17721 else 17722 VTableUses.push_back(std::make_pair(Class, Loc)); 17723 } 17724 17725 bool Sema::DefineUsedVTables() { 17726 LoadExternalVTableUses(); 17727 if (VTableUses.empty()) 17728 return false; 17729 17730 // Note: The VTableUses vector could grow as a result of marking 17731 // the members of a class as "used", so we check the size each 17732 // time through the loop and prefer indices (which are stable) to 17733 // iterators (which are not). 17734 bool DefinedAnything = false; 17735 for (unsigned I = 0; I != VTableUses.size(); ++I) { 17736 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 17737 if (!Class) 17738 continue; 17739 TemplateSpecializationKind ClassTSK = 17740 Class->getTemplateSpecializationKind(); 17741 17742 SourceLocation Loc = VTableUses[I].second; 17743 17744 bool DefineVTable = true; 17745 17746 // If this class has a key function, but that key function is 17747 // defined in another translation unit, we don't need to emit the 17748 // vtable even though we're using it. 17749 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 17750 if (KeyFunction && !KeyFunction->hasBody()) { 17751 // The key function is in another translation unit. 17752 DefineVTable = false; 17753 TemplateSpecializationKind TSK = 17754 KeyFunction->getTemplateSpecializationKind(); 17755 assert(TSK != TSK_ExplicitInstantiationDefinition && 17756 TSK != TSK_ImplicitInstantiation && 17757 "Instantiations don't have key functions"); 17758 (void)TSK; 17759 } else if (!KeyFunction) { 17760 // If we have a class with no key function that is the subject 17761 // of an explicit instantiation declaration, suppress the 17762 // vtable; it will live with the explicit instantiation 17763 // definition. 17764 bool IsExplicitInstantiationDeclaration = 17765 ClassTSK == TSK_ExplicitInstantiationDeclaration; 17766 for (auto R : Class->redecls()) { 17767 TemplateSpecializationKind TSK 17768 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 17769 if (TSK == TSK_ExplicitInstantiationDeclaration) 17770 IsExplicitInstantiationDeclaration = true; 17771 else if (TSK == TSK_ExplicitInstantiationDefinition) { 17772 IsExplicitInstantiationDeclaration = false; 17773 break; 17774 } 17775 } 17776 17777 if (IsExplicitInstantiationDeclaration) 17778 DefineVTable = false; 17779 } 17780 17781 // The exception specifications for all virtual members may be needed even 17782 // if we are not providing an authoritative form of the vtable in this TU. 17783 // We may choose to emit it available_externally anyway. 17784 if (!DefineVTable) { 17785 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 17786 continue; 17787 } 17788 17789 // Mark all of the virtual members of this class as referenced, so 17790 // that we can build a vtable. Then, tell the AST consumer that a 17791 // vtable for this class is required. 17792 DefinedAnything = true; 17793 MarkVirtualMembersReferenced(Loc, Class); 17794 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 17795 if (VTablesUsed[Canonical]) 17796 Consumer.HandleVTable(Class); 17797 17798 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 17799 // no key function or the key function is inlined. Don't warn in C++ ABIs 17800 // that lack key functions, since the user won't be able to make one. 17801 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 17802 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation && 17803 ClassTSK != TSK_ExplicitInstantiationDefinition) { 17804 const FunctionDecl *KeyFunctionDef = nullptr; 17805 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 17806 KeyFunctionDef->isInlined())) 17807 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class; 17808 } 17809 } 17810 VTableUses.clear(); 17811 17812 return DefinedAnything; 17813 } 17814 17815 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 17816 const CXXRecordDecl *RD) { 17817 for (const auto *I : RD->methods()) 17818 if (I->isVirtual() && !I->isPure()) 17819 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 17820 } 17821 17822 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 17823 const CXXRecordDecl *RD, 17824 bool ConstexprOnly) { 17825 // Mark all functions which will appear in RD's vtable as used. 17826 CXXFinalOverriderMap FinalOverriders; 17827 RD->getFinalOverriders(FinalOverriders); 17828 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 17829 E = FinalOverriders.end(); 17830 I != E; ++I) { 17831 for (OverridingMethods::const_iterator OI = I->second.begin(), 17832 OE = I->second.end(); 17833 OI != OE; ++OI) { 17834 assert(OI->second.size() > 0 && "no final overrider"); 17835 CXXMethodDecl *Overrider = OI->second.front().Method; 17836 17837 // C++ [basic.def.odr]p2: 17838 // [...] A virtual member function is used if it is not pure. [...] 17839 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 17840 MarkFunctionReferenced(Loc, Overrider); 17841 } 17842 } 17843 17844 // Only classes that have virtual bases need a VTT. 17845 if (RD->getNumVBases() == 0) 17846 return; 17847 17848 for (const auto &I : RD->bases()) { 17849 const auto *Base = 17850 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 17851 if (Base->getNumVBases() == 0) 17852 continue; 17853 MarkVirtualMembersReferenced(Loc, Base); 17854 } 17855 } 17856 17857 /// SetIvarInitializers - This routine builds initialization ASTs for the 17858 /// Objective-C implementation whose ivars need be initialized. 17859 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 17860 if (!getLangOpts().CPlusPlus) 17861 return; 17862 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 17863 SmallVector<ObjCIvarDecl*, 8> ivars; 17864 CollectIvarsToConstructOrDestruct(OID, ivars); 17865 if (ivars.empty()) 17866 return; 17867 SmallVector<CXXCtorInitializer*, 32> AllToInit; 17868 for (unsigned i = 0; i < ivars.size(); i++) { 17869 FieldDecl *Field = ivars[i]; 17870 if (Field->isInvalidDecl()) 17871 continue; 17872 17873 CXXCtorInitializer *Member; 17874 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 17875 InitializationKind InitKind = 17876 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 17877 17878 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 17879 ExprResult MemberInit = 17880 InitSeq.Perform(*this, InitEntity, InitKind, None); 17881 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 17882 // Note, MemberInit could actually come back empty if no initialization 17883 // is required (e.g., because it would call a trivial default constructor) 17884 if (!MemberInit.get() || MemberInit.isInvalid()) 17885 continue; 17886 17887 Member = 17888 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 17889 SourceLocation(), 17890 MemberInit.getAs<Expr>(), 17891 SourceLocation()); 17892 AllToInit.push_back(Member); 17893 17894 // Be sure that the destructor is accessible and is marked as referenced. 17895 if (const RecordType *RecordTy = 17896 Context.getBaseElementType(Field->getType()) 17897 ->getAs<RecordType>()) { 17898 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 17899 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 17900 MarkFunctionReferenced(Field->getLocation(), Destructor); 17901 CheckDestructorAccess(Field->getLocation(), Destructor, 17902 PDiag(diag::err_access_dtor_ivar) 17903 << Context.getBaseElementType(Field->getType())); 17904 } 17905 } 17906 } 17907 ObjCImplementation->setIvarInitializers(Context, 17908 AllToInit.data(), AllToInit.size()); 17909 } 17910 } 17911 17912 static 17913 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 17914 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 17915 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 17916 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 17917 Sema &S) { 17918 if (Ctor->isInvalidDecl()) 17919 return; 17920 17921 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 17922 17923 // Target may not be determinable yet, for instance if this is a dependent 17924 // call in an uninstantiated template. 17925 if (Target) { 17926 const FunctionDecl *FNTarget = nullptr; 17927 (void)Target->hasBody(FNTarget); 17928 Target = const_cast<CXXConstructorDecl*>( 17929 cast_or_null<CXXConstructorDecl>(FNTarget)); 17930 } 17931 17932 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 17933 // Avoid dereferencing a null pointer here. 17934 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 17935 17936 if (!Current.insert(Canonical).second) 17937 return; 17938 17939 // We know that beyond here, we aren't chaining into a cycle. 17940 if (!Target || !Target->isDelegatingConstructor() || 17941 Target->isInvalidDecl() || Valid.count(TCanonical)) { 17942 Valid.insert(Current.begin(), Current.end()); 17943 Current.clear(); 17944 // We've hit a cycle. 17945 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 17946 Current.count(TCanonical)) { 17947 // If we haven't diagnosed this cycle yet, do so now. 17948 if (!Invalid.count(TCanonical)) { 17949 S.Diag((*Ctor->init_begin())->getSourceLocation(), 17950 diag::warn_delegating_ctor_cycle) 17951 << Ctor; 17952 17953 // Don't add a note for a function delegating directly to itself. 17954 if (TCanonical != Canonical) 17955 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 17956 17957 CXXConstructorDecl *C = Target; 17958 while (C->getCanonicalDecl() != Canonical) { 17959 const FunctionDecl *FNTarget = nullptr; 17960 (void)C->getTargetConstructor()->hasBody(FNTarget); 17961 assert(FNTarget && "Ctor cycle through bodiless function"); 17962 17963 C = const_cast<CXXConstructorDecl*>( 17964 cast<CXXConstructorDecl>(FNTarget)); 17965 S.Diag(C->getLocation(), diag::note_which_delegates_to); 17966 } 17967 } 17968 17969 Invalid.insert(Current.begin(), Current.end()); 17970 Current.clear(); 17971 } else { 17972 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 17973 } 17974 } 17975 17976 17977 void Sema::CheckDelegatingCtorCycles() { 17978 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 17979 17980 for (DelegatingCtorDeclsType::iterator 17981 I = DelegatingCtorDecls.begin(ExternalSource), 17982 E = DelegatingCtorDecls.end(); 17983 I != E; ++I) 17984 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 17985 17986 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 17987 (*CI)->setInvalidDecl(); 17988 } 17989 17990 namespace { 17991 /// AST visitor that finds references to the 'this' expression. 17992 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 17993 Sema &S; 17994 17995 public: 17996 explicit FindCXXThisExpr(Sema &S) : S(S) { } 17997 17998 bool VisitCXXThisExpr(CXXThisExpr *E) { 17999 S.Diag(E->getLocation(), diag::err_this_static_member_func) 18000 << E->isImplicit(); 18001 return false; 18002 } 18003 }; 18004 } 18005 18006 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 18007 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 18008 if (!TSInfo) 18009 return false; 18010 18011 TypeLoc TL = TSInfo->getTypeLoc(); 18012 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 18013 if (!ProtoTL) 18014 return false; 18015 18016 // C++11 [expr.prim.general]p3: 18017 // [The expression this] shall not appear before the optional 18018 // cv-qualifier-seq and it shall not appear within the declaration of a 18019 // static member function (although its type and value category are defined 18020 // within a static member function as they are within a non-static member 18021 // function). [ Note: this is because declaration matching does not occur 18022 // until the complete declarator is known. - end note ] 18023 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 18024 FindCXXThisExpr Finder(*this); 18025 18026 // If the return type came after the cv-qualifier-seq, check it now. 18027 if (Proto->hasTrailingReturn() && 18028 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 18029 return true; 18030 18031 // Check the exception specification. 18032 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 18033 return true; 18034 18035 // Check the trailing requires clause 18036 if (Expr *E = Method->getTrailingRequiresClause()) 18037 if (!Finder.TraverseStmt(E)) 18038 return true; 18039 18040 return checkThisInStaticMemberFunctionAttributes(Method); 18041 } 18042 18043 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 18044 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 18045 if (!TSInfo) 18046 return false; 18047 18048 TypeLoc TL = TSInfo->getTypeLoc(); 18049 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 18050 if (!ProtoTL) 18051 return false; 18052 18053 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 18054 FindCXXThisExpr Finder(*this); 18055 18056 switch (Proto->getExceptionSpecType()) { 18057 case EST_Unparsed: 18058 case EST_Uninstantiated: 18059 case EST_Unevaluated: 18060 case EST_BasicNoexcept: 18061 case EST_NoThrow: 18062 case EST_DynamicNone: 18063 case EST_MSAny: 18064 case EST_None: 18065 break; 18066 18067 case EST_DependentNoexcept: 18068 case EST_NoexceptFalse: 18069 case EST_NoexceptTrue: 18070 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 18071 return true; 18072 LLVM_FALLTHROUGH; 18073 18074 case EST_Dynamic: 18075 for (const auto &E : Proto->exceptions()) { 18076 if (!Finder.TraverseType(E)) 18077 return true; 18078 } 18079 break; 18080 } 18081 18082 return false; 18083 } 18084 18085 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 18086 FindCXXThisExpr Finder(*this); 18087 18088 // Check attributes. 18089 for (const auto *A : Method->attrs()) { 18090 // FIXME: This should be emitted by tblgen. 18091 Expr *Arg = nullptr; 18092 ArrayRef<Expr *> Args; 18093 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 18094 Arg = G->getArg(); 18095 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 18096 Arg = G->getArg(); 18097 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 18098 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 18099 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 18100 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 18101 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 18102 Arg = ETLF->getSuccessValue(); 18103 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 18104 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 18105 Arg = STLF->getSuccessValue(); 18106 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 18107 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 18108 Arg = LR->getArg(); 18109 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 18110 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 18111 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 18112 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 18113 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 18114 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 18115 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 18116 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 18117 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 18118 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 18119 18120 if (Arg && !Finder.TraverseStmt(Arg)) 18121 return true; 18122 18123 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 18124 if (!Finder.TraverseStmt(Args[I])) 18125 return true; 18126 } 18127 } 18128 18129 return false; 18130 } 18131 18132 void Sema::checkExceptionSpecification( 18133 bool IsTopLevel, ExceptionSpecificationType EST, 18134 ArrayRef<ParsedType> DynamicExceptions, 18135 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 18136 SmallVectorImpl<QualType> &Exceptions, 18137 FunctionProtoType::ExceptionSpecInfo &ESI) { 18138 Exceptions.clear(); 18139 ESI.Type = EST; 18140 if (EST == EST_Dynamic) { 18141 Exceptions.reserve(DynamicExceptions.size()); 18142 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 18143 // FIXME: Preserve type source info. 18144 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 18145 18146 if (IsTopLevel) { 18147 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 18148 collectUnexpandedParameterPacks(ET, Unexpanded); 18149 if (!Unexpanded.empty()) { 18150 DiagnoseUnexpandedParameterPacks( 18151 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 18152 Unexpanded); 18153 continue; 18154 } 18155 } 18156 18157 // Check that the type is valid for an exception spec, and 18158 // drop it if not. 18159 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 18160 Exceptions.push_back(ET); 18161 } 18162 ESI.Exceptions = Exceptions; 18163 return; 18164 } 18165 18166 if (isComputedNoexcept(EST)) { 18167 assert((NoexceptExpr->isTypeDependent() || 18168 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 18169 Context.BoolTy) && 18170 "Parser should have made sure that the expression is boolean"); 18171 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 18172 ESI.Type = EST_BasicNoexcept; 18173 return; 18174 } 18175 18176 ESI.NoexceptExpr = NoexceptExpr; 18177 return; 18178 } 18179 } 18180 18181 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 18182 ExceptionSpecificationType EST, 18183 SourceRange SpecificationRange, 18184 ArrayRef<ParsedType> DynamicExceptions, 18185 ArrayRef<SourceRange> DynamicExceptionRanges, 18186 Expr *NoexceptExpr) { 18187 if (!MethodD) 18188 return; 18189 18190 // Dig out the method we're referring to. 18191 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 18192 MethodD = FunTmpl->getTemplatedDecl(); 18193 18194 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 18195 if (!Method) 18196 return; 18197 18198 // Check the exception specification. 18199 llvm::SmallVector<QualType, 4> Exceptions; 18200 FunctionProtoType::ExceptionSpecInfo ESI; 18201 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 18202 DynamicExceptionRanges, NoexceptExpr, Exceptions, 18203 ESI); 18204 18205 // Update the exception specification on the function type. 18206 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 18207 18208 if (Method->isStatic()) 18209 checkThisInStaticMemberFunctionExceptionSpec(Method); 18210 18211 if (Method->isVirtual()) { 18212 // Check overrides, which we previously had to delay. 18213 for (const CXXMethodDecl *O : Method->overridden_methods()) 18214 CheckOverridingFunctionExceptionSpec(Method, O); 18215 } 18216 } 18217 18218 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 18219 /// 18220 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 18221 SourceLocation DeclStart, Declarator &D, 18222 Expr *BitWidth, 18223 InClassInitStyle InitStyle, 18224 AccessSpecifier AS, 18225 const ParsedAttr &MSPropertyAttr) { 18226 IdentifierInfo *II = D.getIdentifier(); 18227 if (!II) { 18228 Diag(DeclStart, diag::err_anonymous_property); 18229 return nullptr; 18230 } 18231 SourceLocation Loc = D.getIdentifierLoc(); 18232 18233 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 18234 QualType T = TInfo->getType(); 18235 if (getLangOpts().CPlusPlus) { 18236 CheckExtraCXXDefaultArguments(D); 18237 18238 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 18239 UPPC_DataMemberType)) { 18240 D.setInvalidType(); 18241 T = Context.IntTy; 18242 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 18243 } 18244 } 18245 18246 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 18247 18248 if (D.getDeclSpec().isInlineSpecified()) 18249 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 18250 << getLangOpts().CPlusPlus17; 18251 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 18252 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 18253 diag::err_invalid_thread) 18254 << DeclSpec::getSpecifierName(TSCS); 18255 18256 // Check to see if this name was declared as a member previously 18257 NamedDecl *PrevDecl = nullptr; 18258 LookupResult Previous(*this, II, Loc, LookupMemberName, 18259 ForVisibleRedeclaration); 18260 LookupName(Previous, S); 18261 switch (Previous.getResultKind()) { 18262 case LookupResult::Found: 18263 case LookupResult::FoundUnresolvedValue: 18264 PrevDecl = Previous.getAsSingle<NamedDecl>(); 18265 break; 18266 18267 case LookupResult::FoundOverloaded: 18268 PrevDecl = Previous.getRepresentativeDecl(); 18269 break; 18270 18271 case LookupResult::NotFound: 18272 case LookupResult::NotFoundInCurrentInstantiation: 18273 case LookupResult::Ambiguous: 18274 break; 18275 } 18276 18277 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18278 // Maybe we will complain about the shadowed template parameter. 18279 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 18280 // Just pretend that we didn't see the previous declaration. 18281 PrevDecl = nullptr; 18282 } 18283 18284 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 18285 PrevDecl = nullptr; 18286 18287 SourceLocation TSSL = D.getBeginLoc(); 18288 MSPropertyDecl *NewPD = 18289 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 18290 MSPropertyAttr.getPropertyDataGetter(), 18291 MSPropertyAttr.getPropertyDataSetter()); 18292 ProcessDeclAttributes(TUScope, NewPD, D); 18293 NewPD->setAccess(AS); 18294 18295 if (NewPD->isInvalidDecl()) 18296 Record->setInvalidDecl(); 18297 18298 if (D.getDeclSpec().isModulePrivateSpecified()) 18299 NewPD->setModulePrivate(); 18300 18301 if (NewPD->isInvalidDecl() && PrevDecl) { 18302 // Don't introduce NewFD into scope; there's already something 18303 // with the same name in the same scope. 18304 } else if (II) { 18305 PushOnScopeChains(NewPD, S); 18306 } else 18307 Record->addDecl(NewPD); 18308 18309 return NewPD; 18310 } 18311 18312 void Sema::ActOnStartFunctionDeclarationDeclarator( 18313 Declarator &Declarator, unsigned TemplateParameterDepth) { 18314 auto &Info = InventedParameterInfos.emplace_back(); 18315 TemplateParameterList *ExplicitParams = nullptr; 18316 ArrayRef<TemplateParameterList *> ExplicitLists = 18317 Declarator.getTemplateParameterLists(); 18318 if (!ExplicitLists.empty()) { 18319 bool IsMemberSpecialization, IsInvalid; 18320 ExplicitParams = MatchTemplateParametersToScopeSpecifier( 18321 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), 18322 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, 18323 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, 18324 /*SuppressDiagnostic=*/true); 18325 } 18326 if (ExplicitParams) { 18327 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); 18328 llvm::append_range(Info.TemplateParams, *ExplicitParams); 18329 Info.NumExplicitTemplateParams = ExplicitParams->size(); 18330 } else { 18331 Info.AutoTemplateParameterDepth = TemplateParameterDepth; 18332 Info.NumExplicitTemplateParams = 0; 18333 } 18334 } 18335 18336 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { 18337 auto &FSI = InventedParameterInfos.back(); 18338 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { 18339 if (FSI.NumExplicitTemplateParams != 0) { 18340 TemplateParameterList *ExplicitParams = 18341 Declarator.getTemplateParameterLists().back(); 18342 Declarator.setInventedTemplateParameterList( 18343 TemplateParameterList::Create( 18344 Context, ExplicitParams->getTemplateLoc(), 18345 ExplicitParams->getLAngleLoc(), FSI.TemplateParams, 18346 ExplicitParams->getRAngleLoc(), 18347 ExplicitParams->getRequiresClause())); 18348 } else { 18349 Declarator.setInventedTemplateParameterList( 18350 TemplateParameterList::Create( 18351 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, 18352 SourceLocation(), /*RequiresClause=*/nullptr)); 18353 } 18354 } 18355 InventedParameterInfos.pop_back(); 18356 } 18357