1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for C++ declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTConsumer.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/ASTLambda.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/ComparisonCategories.h" 20 #include "clang/AST/EvaluatedExprVisitor.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/RecordLayout.h" 23 #include "clang/AST/RecursiveASTVisitor.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/AST/TypeLoc.h" 26 #include "clang/AST/TypeOrdering.h" 27 #include "clang/Basic/AttributeCommonInfo.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/LiteralSupport.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Sema/CXXFieldCollector.h" 33 #include "clang/Sema/DeclSpec.h" 34 #include "clang/Sema/Initialization.h" 35 #include "clang/Sema/Lookup.h" 36 #include "clang/Sema/ParsedTemplate.h" 37 #include "clang/Sema/Scope.h" 38 #include "clang/Sema/ScopeInfo.h" 39 #include "clang/Sema/SemaInternal.h" 40 #include "clang/Sema/Template.h" 41 #include "llvm/ADT/ScopeExit.h" 42 #include "llvm/ADT/SmallString.h" 43 #include "llvm/ADT/STLExtras.h" 44 #include "llvm/ADT/StringExtras.h" 45 #include <map> 46 #include <set> 47 48 using namespace clang; 49 50 //===----------------------------------------------------------------------===// 51 // CheckDefaultArgumentVisitor 52 //===----------------------------------------------------------------------===// 53 54 namespace { 55 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 56 /// the default argument of a parameter to determine whether it 57 /// contains any ill-formed subexpressions. For example, this will 58 /// diagnose the use of local variables or parameters within the 59 /// default argument expression. 60 class CheckDefaultArgumentVisitor 61 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> { 62 Sema &S; 63 const Expr *DefaultArg; 64 65 public: 66 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg) 67 : S(S), DefaultArg(DefaultArg) {} 68 69 bool VisitExpr(const Expr *Node); 70 bool VisitDeclRefExpr(const DeclRefExpr *DRE); 71 bool VisitCXXThisExpr(const CXXThisExpr *ThisE); 72 bool VisitLambdaExpr(const LambdaExpr *Lambda); 73 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE); 74 }; 75 76 /// VisitExpr - Visit all of the children of this expression. 77 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) { 78 bool IsInvalid = false; 79 for (const Stmt *SubStmt : Node->children()) 80 IsInvalid |= Visit(SubStmt); 81 return IsInvalid; 82 } 83 84 /// VisitDeclRefExpr - Visit a reference to a declaration, to 85 /// determine whether this declaration can be used in the default 86 /// argument expression. 87 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) { 88 const NamedDecl *Decl = DRE->getDecl(); 89 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) { 90 // C++ [dcl.fct.default]p9: 91 // [...] parameters of a function shall not be used in default 92 // argument expressions, even if they are not evaluated. [...] 93 // 94 // C++17 [dcl.fct.default]p9 (by CWG 2082): 95 // [...] A parameter shall not appear as a potentially-evaluated 96 // expression in a default argument. [...] 97 // 98 if (DRE->isNonOdrUse() != NOUR_Unevaluated) 99 return S.Diag(DRE->getBeginLoc(), 100 diag::err_param_default_argument_references_param) 101 << Param->getDeclName() << DefaultArg->getSourceRange(); 102 } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) { 103 // C++ [dcl.fct.default]p7: 104 // Local variables shall not be used in default argument 105 // expressions. 106 // 107 // C++17 [dcl.fct.default]p7 (by CWG 2082): 108 // A local variable shall not appear as a potentially-evaluated 109 // expression in a default argument. 110 // 111 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346): 112 // Note: A local variable cannot be odr-used (6.3) in a default argument. 113 // 114 if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse()) 115 return S.Diag(DRE->getBeginLoc(), 116 diag::err_param_default_argument_references_local) 117 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 118 } 119 120 return false; 121 } 122 123 /// VisitCXXThisExpr - Visit a C++ "this" expression. 124 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) { 125 // C++ [dcl.fct.default]p8: 126 // The keyword this shall not be used in a default argument of a 127 // member function. 128 return S.Diag(ThisE->getBeginLoc(), 129 diag::err_param_default_argument_references_this) 130 << ThisE->getSourceRange(); 131 } 132 133 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr( 134 const PseudoObjectExpr *POE) { 135 bool Invalid = false; 136 for (const Expr *E : POE->semantics()) { 137 // Look through bindings. 138 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) { 139 E = OVE->getSourceExpr(); 140 assert(E && "pseudo-object binding without source expression?"); 141 } 142 143 Invalid |= Visit(E); 144 } 145 return Invalid; 146 } 147 148 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) { 149 // C++11 [expr.lambda.prim]p13: 150 // A lambda-expression appearing in a default argument shall not 151 // implicitly or explicitly capture any entity. 152 if (Lambda->capture_begin() == Lambda->capture_end()) 153 return false; 154 155 return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); 156 } 157 } // namespace 158 159 void 160 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 161 const CXXMethodDecl *Method) { 162 // If we have an MSAny spec already, don't bother. 163 if (!Method || ComputedEST == EST_MSAny) 164 return; 165 166 const FunctionProtoType *Proto 167 = Method->getType()->getAs<FunctionProtoType>(); 168 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 169 if (!Proto) 170 return; 171 172 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 173 174 // If we have a throw-all spec at this point, ignore the function. 175 if (ComputedEST == EST_None) 176 return; 177 178 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 179 EST = EST_BasicNoexcept; 180 181 switch (EST) { 182 case EST_Unparsed: 183 case EST_Uninstantiated: 184 case EST_Unevaluated: 185 llvm_unreachable("should not see unresolved exception specs here"); 186 187 // If this function can throw any exceptions, make a note of that. 188 case EST_MSAny: 189 case EST_None: 190 // FIXME: Whichever we see last of MSAny and None determines our result. 191 // We should make a consistent, order-independent choice here. 192 ClearExceptions(); 193 ComputedEST = EST; 194 return; 195 case EST_NoexceptFalse: 196 ClearExceptions(); 197 ComputedEST = EST_None; 198 return; 199 // FIXME: If the call to this decl is using any of its default arguments, we 200 // need to search them for potentially-throwing calls. 201 // If this function has a basic noexcept, it doesn't affect the outcome. 202 case EST_BasicNoexcept: 203 case EST_NoexceptTrue: 204 case EST_NoThrow: 205 return; 206 // If we're still at noexcept(true) and there's a throw() callee, 207 // change to that specification. 208 case EST_DynamicNone: 209 if (ComputedEST == EST_BasicNoexcept) 210 ComputedEST = EST_DynamicNone; 211 return; 212 case EST_DependentNoexcept: 213 llvm_unreachable( 214 "should not generate implicit declarations for dependent cases"); 215 case EST_Dynamic: 216 break; 217 } 218 assert(EST == EST_Dynamic && "EST case not considered earlier."); 219 assert(ComputedEST != EST_None && 220 "Shouldn't collect exceptions when throw-all is guaranteed."); 221 ComputedEST = EST_Dynamic; 222 // Record the exceptions in this function's exception specification. 223 for (const auto &E : Proto->exceptions()) 224 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 225 Exceptions.push_back(E); 226 } 227 228 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) { 229 if (!S || ComputedEST == EST_MSAny) 230 return; 231 232 // FIXME: 233 // 234 // C++0x [except.spec]p14: 235 // [An] implicit exception-specification specifies the type-id T if and 236 // only if T is allowed by the exception-specification of a function directly 237 // invoked by f's implicit definition; f shall allow all exceptions if any 238 // function it directly invokes allows all exceptions, and f shall allow no 239 // exceptions if every function it directly invokes allows no exceptions. 240 // 241 // Note in particular that if an implicit exception-specification is generated 242 // for a function containing a throw-expression, that specification can still 243 // be noexcept(true). 244 // 245 // Note also that 'directly invoked' is not defined in the standard, and there 246 // is no indication that we should only consider potentially-evaluated calls. 247 // 248 // Ultimately we should implement the intent of the standard: the exception 249 // specification should be the set of exceptions which can be thrown by the 250 // implicit definition. For now, we assume that any non-nothrow expression can 251 // throw any exception. 252 253 if (Self->canThrow(S)) 254 ComputedEST = EST_None; 255 } 256 257 ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 258 SourceLocation EqualLoc) { 259 if (RequireCompleteType(Param->getLocation(), Param->getType(), 260 diag::err_typecheck_decl_incomplete_type)) 261 return true; 262 263 // C++ [dcl.fct.default]p5 264 // A default argument expression is implicitly converted (clause 265 // 4) to the parameter type. The default argument expression has 266 // the same semantic constraints as the initializer expression in 267 // a declaration of a variable of the parameter type, using the 268 // copy-initialization semantics (8.5). 269 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 270 Param); 271 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 272 EqualLoc); 273 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 274 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 275 if (Result.isInvalid()) 276 return true; 277 Arg = Result.getAs<Expr>(); 278 279 CheckCompletedExpr(Arg, EqualLoc); 280 Arg = MaybeCreateExprWithCleanups(Arg); 281 282 return Arg; 283 } 284 285 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 286 SourceLocation EqualLoc) { 287 // Add the default argument to the parameter 288 Param->setDefaultArg(Arg); 289 290 // We have already instantiated this parameter; provide each of the 291 // instantiations with the uninstantiated default argument. 292 UnparsedDefaultArgInstantiationsMap::iterator InstPos 293 = UnparsedDefaultArgInstantiations.find(Param); 294 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 295 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 296 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 297 298 // We're done tracking this parameter's instantiations. 299 UnparsedDefaultArgInstantiations.erase(InstPos); 300 } 301 } 302 303 /// ActOnParamDefaultArgument - Check whether the default argument 304 /// provided for a function parameter is well-formed. If so, attach it 305 /// to the parameter declaration. 306 void 307 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 308 Expr *DefaultArg) { 309 if (!param || !DefaultArg) 310 return; 311 312 ParmVarDecl *Param = cast<ParmVarDecl>(param); 313 UnparsedDefaultArgLocs.erase(Param); 314 315 auto Fail = [&] { 316 Param->setInvalidDecl(); 317 Param->setDefaultArg(new (Context) OpaqueValueExpr( 318 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue)); 319 }; 320 321 // Default arguments are only permitted in C++ 322 if (!getLangOpts().CPlusPlus) { 323 Diag(EqualLoc, diag::err_param_default_argument) 324 << DefaultArg->getSourceRange(); 325 return Fail(); 326 } 327 328 // Check for unexpanded parameter packs. 329 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 330 return Fail(); 331 } 332 333 // C++11 [dcl.fct.default]p3 334 // A default argument expression [...] shall not be specified for a 335 // parameter pack. 336 if (Param->isParameterPack()) { 337 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 338 << DefaultArg->getSourceRange(); 339 // Recover by discarding the default argument. 340 Param->setDefaultArg(nullptr); 341 return; 342 } 343 344 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc); 345 if (Result.isInvalid()) 346 return Fail(); 347 348 DefaultArg = Result.getAs<Expr>(); 349 350 // Check that the default argument is well-formed 351 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg); 352 if (DefaultArgChecker.Visit(DefaultArg)) 353 return Fail(); 354 355 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 356 } 357 358 /// ActOnParamUnparsedDefaultArgument - We've seen a default 359 /// argument for a function parameter, but we can't parse it yet 360 /// because we're inside a class definition. Note that this default 361 /// argument will be parsed later. 362 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 363 SourceLocation EqualLoc, 364 SourceLocation ArgLoc) { 365 if (!param) 366 return; 367 368 ParmVarDecl *Param = cast<ParmVarDecl>(param); 369 Param->setUnparsedDefaultArg(); 370 UnparsedDefaultArgLocs[Param] = ArgLoc; 371 } 372 373 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 374 /// the default argument for the parameter param failed. 375 void Sema::ActOnParamDefaultArgumentError(Decl *param, 376 SourceLocation EqualLoc) { 377 if (!param) 378 return; 379 380 ParmVarDecl *Param = cast<ParmVarDecl>(param); 381 Param->setInvalidDecl(); 382 UnparsedDefaultArgLocs.erase(Param); 383 Param->setDefaultArg(new (Context) OpaqueValueExpr( 384 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue)); 385 } 386 387 /// CheckExtraCXXDefaultArguments - Check for any extra default 388 /// arguments in the declarator, which is not a function declaration 389 /// or definition and therefore is not permitted to have default 390 /// arguments. This routine should be invoked for every declarator 391 /// that is not a function declaration or definition. 392 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 393 // C++ [dcl.fct.default]p3 394 // A default argument expression shall be specified only in the 395 // parameter-declaration-clause of a function declaration or in a 396 // template-parameter (14.1). It shall not be specified for a 397 // parameter pack. If it is specified in a 398 // parameter-declaration-clause, it shall not occur within a 399 // declarator or abstract-declarator of a parameter-declaration. 400 bool MightBeFunction = D.isFunctionDeclarationContext(); 401 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 402 DeclaratorChunk &chunk = D.getTypeObject(i); 403 if (chunk.Kind == DeclaratorChunk::Function) { 404 if (MightBeFunction) { 405 // This is a function declaration. It can have default arguments, but 406 // keep looking in case its return type is a function type with default 407 // arguments. 408 MightBeFunction = false; 409 continue; 410 } 411 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 412 ++argIdx) { 413 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 414 if (Param->hasUnparsedDefaultArg()) { 415 std::unique_ptr<CachedTokens> Toks = 416 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 417 SourceRange SR; 418 if (Toks->size() > 1) 419 SR = SourceRange((*Toks)[1].getLocation(), 420 Toks->back().getLocation()); 421 else 422 SR = UnparsedDefaultArgLocs[Param]; 423 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 424 << SR; 425 } else if (Param->getDefaultArg()) { 426 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 427 << Param->getDefaultArg()->getSourceRange(); 428 Param->setDefaultArg(nullptr); 429 } 430 } 431 } else if (chunk.Kind != DeclaratorChunk::Paren) { 432 MightBeFunction = false; 433 } 434 } 435 } 436 437 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 438 return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) { 439 return P->hasDefaultArg() && !P->hasInheritedDefaultArg(); 440 }); 441 } 442 443 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 444 /// function, once we already know that they have the same 445 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 446 /// error, false otherwise. 447 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 448 Scope *S) { 449 bool Invalid = false; 450 451 // The declaration context corresponding to the scope is the semantic 452 // parent, unless this is a local function declaration, in which case 453 // it is that surrounding function. 454 DeclContext *ScopeDC = New->isLocalExternDecl() 455 ? New->getLexicalDeclContext() 456 : New->getDeclContext(); 457 458 // Find the previous declaration for the purpose of default arguments. 459 FunctionDecl *PrevForDefaultArgs = Old; 460 for (/**/; PrevForDefaultArgs; 461 // Don't bother looking back past the latest decl if this is a local 462 // extern declaration; nothing else could work. 463 PrevForDefaultArgs = New->isLocalExternDecl() 464 ? nullptr 465 : PrevForDefaultArgs->getPreviousDecl()) { 466 // Ignore hidden declarations. 467 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 468 continue; 469 470 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 471 !New->isCXXClassMember()) { 472 // Ignore default arguments of old decl if they are not in 473 // the same scope and this is not an out-of-line definition of 474 // a member function. 475 continue; 476 } 477 478 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 479 // If only one of these is a local function declaration, then they are 480 // declared in different scopes, even though isDeclInScope may think 481 // they're in the same scope. (If both are local, the scope check is 482 // sufficient, and if neither is local, then they are in the same scope.) 483 continue; 484 } 485 486 // We found the right previous declaration. 487 break; 488 } 489 490 // C++ [dcl.fct.default]p4: 491 // For non-template functions, default arguments can be added in 492 // later declarations of a function in the same 493 // scope. Declarations in different scopes have completely 494 // distinct sets of default arguments. That is, declarations in 495 // inner scopes do not acquire default arguments from 496 // declarations in outer scopes, and vice versa. In a given 497 // function declaration, all parameters subsequent to a 498 // parameter with a default argument shall have default 499 // arguments supplied in this or previous declarations. A 500 // default argument shall not be redefined by a later 501 // declaration (not even to the same value). 502 // 503 // C++ [dcl.fct.default]p6: 504 // Except for member functions of class templates, the default arguments 505 // in a member function definition that appears outside of the class 506 // definition are added to the set of default arguments provided by the 507 // member function declaration in the class definition. 508 for (unsigned p = 0, NumParams = PrevForDefaultArgs 509 ? PrevForDefaultArgs->getNumParams() 510 : 0; 511 p < NumParams; ++p) { 512 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 513 ParmVarDecl *NewParam = New->getParamDecl(p); 514 515 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 516 bool NewParamHasDfl = NewParam->hasDefaultArg(); 517 518 if (OldParamHasDfl && NewParamHasDfl) { 519 unsigned DiagDefaultParamID = 520 diag::err_param_default_argument_redefinition; 521 522 // MSVC accepts that default parameters be redefined for member functions 523 // of template class. The new default parameter's value is ignored. 524 Invalid = true; 525 if (getLangOpts().MicrosoftExt) { 526 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 527 if (MD && MD->getParent()->getDescribedClassTemplate()) { 528 // Merge the old default argument into the new parameter. 529 NewParam->setHasInheritedDefaultArg(); 530 if (OldParam->hasUninstantiatedDefaultArg()) 531 NewParam->setUninstantiatedDefaultArg( 532 OldParam->getUninstantiatedDefaultArg()); 533 else 534 NewParam->setDefaultArg(OldParam->getInit()); 535 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 536 Invalid = false; 537 } 538 } 539 540 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 541 // hint here. Alternatively, we could walk the type-source information 542 // for NewParam to find the last source location in the type... but it 543 // isn't worth the effort right now. This is the kind of test case that 544 // is hard to get right: 545 // int f(int); 546 // void g(int (*fp)(int) = f); 547 // void g(int (*fp)(int) = &f); 548 Diag(NewParam->getLocation(), DiagDefaultParamID) 549 << NewParam->getDefaultArgRange(); 550 551 // Look for the function declaration where the default argument was 552 // actually written, which may be a declaration prior to Old. 553 for (auto Older = PrevForDefaultArgs; 554 OldParam->hasInheritedDefaultArg(); /**/) { 555 Older = Older->getPreviousDecl(); 556 OldParam = Older->getParamDecl(p); 557 } 558 559 Diag(OldParam->getLocation(), diag::note_previous_definition) 560 << OldParam->getDefaultArgRange(); 561 } else if (OldParamHasDfl) { 562 // Merge the old default argument into the new parameter unless the new 563 // function is a friend declaration in a template class. In the latter 564 // case the default arguments will be inherited when the friend 565 // declaration will be instantiated. 566 if (New->getFriendObjectKind() == Decl::FOK_None || 567 !New->getLexicalDeclContext()->isDependentContext()) { 568 // It's important to use getInit() here; getDefaultArg() 569 // strips off any top-level ExprWithCleanups. 570 NewParam->setHasInheritedDefaultArg(); 571 if (OldParam->hasUnparsedDefaultArg()) 572 NewParam->setUnparsedDefaultArg(); 573 else if (OldParam->hasUninstantiatedDefaultArg()) 574 NewParam->setUninstantiatedDefaultArg( 575 OldParam->getUninstantiatedDefaultArg()); 576 else 577 NewParam->setDefaultArg(OldParam->getInit()); 578 } 579 } else if (NewParamHasDfl) { 580 if (New->getDescribedFunctionTemplate()) { 581 // Paragraph 4, quoted above, only applies to non-template functions. 582 Diag(NewParam->getLocation(), 583 diag::err_param_default_argument_template_redecl) 584 << NewParam->getDefaultArgRange(); 585 Diag(PrevForDefaultArgs->getLocation(), 586 diag::note_template_prev_declaration) 587 << false; 588 } else if (New->getTemplateSpecializationKind() 589 != TSK_ImplicitInstantiation && 590 New->getTemplateSpecializationKind() != TSK_Undeclared) { 591 // C++ [temp.expr.spec]p21: 592 // Default function arguments shall not be specified in a declaration 593 // or a definition for one of the following explicit specializations: 594 // - the explicit specialization of a function template; 595 // - the explicit specialization of a member function template; 596 // - the explicit specialization of a member function of a class 597 // template where the class template specialization to which the 598 // member function specialization belongs is implicitly 599 // instantiated. 600 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 601 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 602 << New->getDeclName() 603 << NewParam->getDefaultArgRange(); 604 } else if (New->getDeclContext()->isDependentContext()) { 605 // C++ [dcl.fct.default]p6 (DR217): 606 // Default arguments for a member function of a class template shall 607 // be specified on the initial declaration of the member function 608 // within the class template. 609 // 610 // Reading the tea leaves a bit in DR217 and its reference to DR205 611 // leads me to the conclusion that one cannot add default function 612 // arguments for an out-of-line definition of a member function of a 613 // dependent type. 614 int WhichKind = 2; 615 if (CXXRecordDecl *Record 616 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 617 if (Record->getDescribedClassTemplate()) 618 WhichKind = 0; 619 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 620 WhichKind = 1; 621 else 622 WhichKind = 2; 623 } 624 625 Diag(NewParam->getLocation(), 626 diag::err_param_default_argument_member_template_redecl) 627 << WhichKind 628 << NewParam->getDefaultArgRange(); 629 } 630 } 631 } 632 633 // DR1344: If a default argument is added outside a class definition and that 634 // default argument makes the function a special member function, the program 635 // is ill-formed. This can only happen for constructors. 636 if (isa<CXXConstructorDecl>(New) && 637 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 638 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 639 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 640 if (NewSM != OldSM) { 641 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 642 assert(NewParam->hasDefaultArg()); 643 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 644 << NewParam->getDefaultArgRange() << NewSM; 645 Diag(Old->getLocation(), diag::note_previous_declaration); 646 } 647 } 648 649 const FunctionDecl *Def; 650 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 651 // template has a constexpr specifier then all its declarations shall 652 // contain the constexpr specifier. 653 if (New->getConstexprKind() != Old->getConstexprKind()) { 654 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 655 << New << static_cast<int>(New->getConstexprKind()) 656 << static_cast<int>(Old->getConstexprKind()); 657 Diag(Old->getLocation(), diag::note_previous_declaration); 658 Invalid = true; 659 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 660 Old->isDefined(Def) && 661 // If a friend function is inlined but does not have 'inline' 662 // specifier, it is a definition. Do not report attribute conflict 663 // in this case, redefinition will be diagnosed later. 664 (New->isInlineSpecified() || 665 New->getFriendObjectKind() == Decl::FOK_None)) { 666 // C++11 [dcl.fcn.spec]p4: 667 // If the definition of a function appears in a translation unit before its 668 // first declaration as inline, the program is ill-formed. 669 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 670 Diag(Def->getLocation(), diag::note_previous_definition); 671 Invalid = true; 672 } 673 674 // C++17 [temp.deduct.guide]p3: 675 // Two deduction guide declarations in the same translation unit 676 // for the same class template shall not have equivalent 677 // parameter-declaration-clauses. 678 if (isa<CXXDeductionGuideDecl>(New) && 679 !New->isFunctionTemplateSpecialization() && isVisible(Old)) { 680 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 681 Diag(Old->getLocation(), diag::note_previous_declaration); 682 } 683 684 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 685 // argument expression, that declaration shall be a definition and shall be 686 // the only declaration of the function or function template in the 687 // translation unit. 688 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 689 functionDeclHasDefaultArgument(Old)) { 690 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 691 Diag(Old->getLocation(), diag::note_previous_declaration); 692 Invalid = true; 693 } 694 695 // C++11 [temp.friend]p4 (DR329): 696 // When a function is defined in a friend function declaration in a class 697 // template, the function is instantiated when the function is odr-used. 698 // The same restrictions on multiple declarations and definitions that 699 // apply to non-template function declarations and definitions also apply 700 // to these implicit definitions. 701 const FunctionDecl *OldDefinition = nullptr; 702 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() && 703 Old->isDefined(OldDefinition, true)) 704 CheckForFunctionRedefinition(New, OldDefinition); 705 706 return Invalid; 707 } 708 709 NamedDecl * 710 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 711 MultiTemplateParamsArg TemplateParamLists) { 712 assert(D.isDecompositionDeclarator()); 713 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 714 715 // The syntax only allows a decomposition declarator as a simple-declaration, 716 // a for-range-declaration, or a condition in Clang, but we parse it in more 717 // cases than that. 718 if (!D.mayHaveDecompositionDeclarator()) { 719 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 720 << Decomp.getSourceRange(); 721 return nullptr; 722 } 723 724 if (!TemplateParamLists.empty()) { 725 // FIXME: There's no rule against this, but there are also no rules that 726 // would actually make it usable, so we reject it for now. 727 Diag(TemplateParamLists.front()->getTemplateLoc(), 728 diag::err_decomp_decl_template); 729 return nullptr; 730 } 731 732 Diag(Decomp.getLSquareLoc(), 733 !getLangOpts().CPlusPlus17 734 ? diag::ext_decomp_decl 735 : D.getContext() == DeclaratorContext::Condition 736 ? diag::ext_decomp_decl_cond 737 : diag::warn_cxx14_compat_decomp_decl) 738 << Decomp.getSourceRange(); 739 740 // The semantic context is always just the current context. 741 DeclContext *const DC = CurContext; 742 743 // C++17 [dcl.dcl]/8: 744 // The decl-specifier-seq shall contain only the type-specifier auto 745 // and cv-qualifiers. 746 // C++2a [dcl.dcl]/8: 747 // If decl-specifier-seq contains any decl-specifier other than static, 748 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 749 auto &DS = D.getDeclSpec(); 750 { 751 SmallVector<StringRef, 8> BadSpecifiers; 752 SmallVector<SourceLocation, 8> BadSpecifierLocs; 753 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 754 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 755 if (auto SCS = DS.getStorageClassSpec()) { 756 if (SCS == DeclSpec::SCS_static) { 757 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 758 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 759 } else { 760 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 761 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 762 } 763 } 764 if (auto TSCS = DS.getThreadStorageClassSpec()) { 765 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 766 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 767 } 768 if (DS.hasConstexprSpecifier()) { 769 BadSpecifiers.push_back( 770 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 771 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 772 } 773 if (DS.isInlineSpecified()) { 774 BadSpecifiers.push_back("inline"); 775 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 776 } 777 if (!BadSpecifiers.empty()) { 778 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 779 Err << (int)BadSpecifiers.size() 780 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 781 // Don't add FixItHints to remove the specifiers; we do still respect 782 // them when building the underlying variable. 783 for (auto Loc : BadSpecifierLocs) 784 Err << SourceRange(Loc, Loc); 785 } else if (!CPlusPlus20Specifiers.empty()) { 786 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 787 getLangOpts().CPlusPlus20 788 ? diag::warn_cxx17_compat_decomp_decl_spec 789 : diag::ext_decomp_decl_spec); 790 Warn << (int)CPlusPlus20Specifiers.size() 791 << llvm::join(CPlusPlus20Specifiers.begin(), 792 CPlusPlus20Specifiers.end(), " "); 793 for (auto Loc : CPlusPlus20SpecifierLocs) 794 Warn << SourceRange(Loc, Loc); 795 } 796 // We can't recover from it being declared as a typedef. 797 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 798 return nullptr; 799 } 800 801 // C++2a [dcl.struct.bind]p1: 802 // A cv that includes volatile is deprecated 803 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && 804 getLangOpts().CPlusPlus20) 805 Diag(DS.getVolatileSpecLoc(), 806 diag::warn_deprecated_volatile_structured_binding); 807 808 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 809 QualType R = TInfo->getType(); 810 811 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 812 UPPC_DeclarationType)) 813 D.setInvalidType(); 814 815 // The syntax only allows a single ref-qualifier prior to the decomposition 816 // declarator. No other declarator chunks are permitted. Also check the type 817 // specifier here. 818 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 819 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 820 (D.getNumTypeObjects() == 1 && 821 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 822 Diag(Decomp.getLSquareLoc(), 823 (D.hasGroupingParens() || 824 (D.getNumTypeObjects() && 825 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 826 ? diag::err_decomp_decl_parens 827 : diag::err_decomp_decl_type) 828 << R; 829 830 // In most cases, there's no actual problem with an explicitly-specified 831 // type, but a function type won't work here, and ActOnVariableDeclarator 832 // shouldn't be called for such a type. 833 if (R->isFunctionType()) 834 D.setInvalidType(); 835 } 836 837 // Build the BindingDecls. 838 SmallVector<BindingDecl*, 8> Bindings; 839 840 // Build the BindingDecls. 841 for (auto &B : D.getDecompositionDeclarator().bindings()) { 842 // Check for name conflicts. 843 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 844 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 845 ForVisibleRedeclaration); 846 LookupName(Previous, S, 847 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 848 849 // It's not permitted to shadow a template parameter name. 850 if (Previous.isSingleResult() && 851 Previous.getFoundDecl()->isTemplateParameter()) { 852 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 853 Previous.getFoundDecl()); 854 Previous.clear(); 855 } 856 857 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 858 859 // Find the shadowed declaration before filtering for scope. 860 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 861 ? getShadowedDeclaration(BD, Previous) 862 : nullptr; 863 864 bool ConsiderLinkage = DC->isFunctionOrMethod() && 865 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 866 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 867 /*AllowInlineNamespace*/false); 868 869 if (!Previous.empty()) { 870 auto *Old = Previous.getRepresentativeDecl(); 871 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 872 Diag(Old->getLocation(), diag::note_previous_definition); 873 } else if (ShadowedDecl && !D.isRedeclaration()) { 874 CheckShadow(BD, ShadowedDecl, Previous); 875 } 876 PushOnScopeChains(BD, S, true); 877 Bindings.push_back(BD); 878 ParsingInitForAutoVars.insert(BD); 879 } 880 881 // There are no prior lookup results for the variable itself, because it 882 // is unnamed. 883 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 884 Decomp.getLSquareLoc()); 885 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 886 ForVisibleRedeclaration); 887 888 // Build the variable that holds the non-decomposed object. 889 bool AddToScope = true; 890 NamedDecl *New = 891 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 892 MultiTemplateParamsArg(), AddToScope, Bindings); 893 if (AddToScope) { 894 S->AddDecl(New); 895 CurContext->addHiddenDecl(New); 896 } 897 898 if (isInOpenMPDeclareTargetContext()) 899 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 900 901 return New; 902 } 903 904 static bool checkSimpleDecomposition( 905 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 906 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 907 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 908 if ((int64_t)Bindings.size() != NumElems) { 909 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 910 << DecompType << (unsigned)Bindings.size() 911 << (unsigned)NumElems.getLimitedValue(UINT_MAX) 912 << toString(NumElems, 10) << (NumElems < Bindings.size()); 913 return true; 914 } 915 916 unsigned I = 0; 917 for (auto *B : Bindings) { 918 SourceLocation Loc = B->getLocation(); 919 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 920 if (E.isInvalid()) 921 return true; 922 E = GetInit(Loc, E.get(), I++); 923 if (E.isInvalid()) 924 return true; 925 B->setBinding(ElemType, E.get()); 926 } 927 928 return false; 929 } 930 931 static bool checkArrayLikeDecomposition(Sema &S, 932 ArrayRef<BindingDecl *> Bindings, 933 ValueDecl *Src, QualType DecompType, 934 const llvm::APSInt &NumElems, 935 QualType ElemType) { 936 return checkSimpleDecomposition( 937 S, Bindings, Src, DecompType, NumElems, ElemType, 938 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 939 ExprResult E = S.ActOnIntegerConstant(Loc, I); 940 if (E.isInvalid()) 941 return ExprError(); 942 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 943 }); 944 } 945 946 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 947 ValueDecl *Src, QualType DecompType, 948 const ConstantArrayType *CAT) { 949 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 950 llvm::APSInt(CAT->getSize()), 951 CAT->getElementType()); 952 } 953 954 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 955 ValueDecl *Src, QualType DecompType, 956 const VectorType *VT) { 957 return checkArrayLikeDecomposition( 958 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 959 S.Context.getQualifiedType(VT->getElementType(), 960 DecompType.getQualifiers())); 961 } 962 963 static bool checkComplexDecomposition(Sema &S, 964 ArrayRef<BindingDecl *> Bindings, 965 ValueDecl *Src, QualType DecompType, 966 const ComplexType *CT) { 967 return checkSimpleDecomposition( 968 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 969 S.Context.getQualifiedType(CT->getElementType(), 970 DecompType.getQualifiers()), 971 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 972 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 973 }); 974 } 975 976 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 977 TemplateArgumentListInfo &Args, 978 const TemplateParameterList *Params) { 979 SmallString<128> SS; 980 llvm::raw_svector_ostream OS(SS); 981 bool First = true; 982 unsigned I = 0; 983 for (auto &Arg : Args.arguments()) { 984 if (!First) 985 OS << ", "; 986 Arg.getArgument().print( 987 PrintingPolicy, OS, 988 TemplateParameterList::shouldIncludeTypeForArgument(Params, I)); 989 First = false; 990 I++; 991 } 992 return std::string(OS.str()); 993 } 994 995 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 996 SourceLocation Loc, StringRef Trait, 997 TemplateArgumentListInfo &Args, 998 unsigned DiagID) { 999 auto DiagnoseMissing = [&] { 1000 if (DiagID) 1001 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 1002 Args, /*Params*/ nullptr); 1003 return true; 1004 }; 1005 1006 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 1007 NamespaceDecl *Std = S.getStdNamespace(); 1008 if (!Std) 1009 return DiagnoseMissing(); 1010 1011 // Look up the trait itself, within namespace std. We can diagnose various 1012 // problems with this lookup even if we've been asked to not diagnose a 1013 // missing specialization, because this can only fail if the user has been 1014 // declaring their own names in namespace std or we don't support the 1015 // standard library implementation in use. 1016 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 1017 Loc, Sema::LookupOrdinaryName); 1018 if (!S.LookupQualifiedName(Result, Std)) 1019 return DiagnoseMissing(); 1020 if (Result.isAmbiguous()) 1021 return true; 1022 1023 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 1024 if (!TraitTD) { 1025 Result.suppressDiagnostics(); 1026 NamedDecl *Found = *Result.begin(); 1027 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 1028 S.Diag(Found->getLocation(), diag::note_declared_at); 1029 return true; 1030 } 1031 1032 // Build the template-id. 1033 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 1034 if (TraitTy.isNull()) 1035 return true; 1036 if (!S.isCompleteType(Loc, TraitTy)) { 1037 if (DiagID) 1038 S.RequireCompleteType( 1039 Loc, TraitTy, DiagID, 1040 printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1041 TraitTD->getTemplateParameters())); 1042 return true; 1043 } 1044 1045 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1046 assert(RD && "specialization of class template is not a class?"); 1047 1048 // Look up the member of the trait type. 1049 S.LookupQualifiedName(TraitMemberLookup, RD); 1050 return TraitMemberLookup.isAmbiguous(); 1051 } 1052 1053 static TemplateArgumentLoc 1054 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1055 uint64_t I) { 1056 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1057 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1058 } 1059 1060 static TemplateArgumentLoc 1061 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1062 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1063 } 1064 1065 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1066 1067 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1068 llvm::APSInt &Size) { 1069 EnterExpressionEvaluationContext ContextRAII( 1070 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1071 1072 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1073 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1074 1075 // Form template argument list for tuple_size<T>. 1076 TemplateArgumentListInfo Args(Loc, Loc); 1077 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1078 1079 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1080 // it's not tuple-like. 1081 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1082 R.empty()) 1083 return IsTupleLike::NotTupleLike; 1084 1085 // If we get this far, we've committed to the tuple interpretation, but 1086 // we can still fail if there actually isn't a usable ::value. 1087 1088 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1089 LookupResult &R; 1090 TemplateArgumentListInfo &Args; 1091 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1092 : R(R), Args(Args) {} 1093 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 1094 SourceLocation Loc) override { 1095 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1096 << printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1097 /*Params*/ nullptr); 1098 } 1099 } Diagnoser(R, Args); 1100 1101 ExprResult E = 1102 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1103 if (E.isInvalid()) 1104 return IsTupleLike::Error; 1105 1106 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser); 1107 if (E.isInvalid()) 1108 return IsTupleLike::Error; 1109 1110 return IsTupleLike::TupleLike; 1111 } 1112 1113 /// \return std::tuple_element<I, T>::type. 1114 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1115 unsigned I, QualType T) { 1116 // Form template argument list for tuple_element<I, T>. 1117 TemplateArgumentListInfo Args(Loc, Loc); 1118 Args.addArgument( 1119 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1120 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1121 1122 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1123 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1124 if (lookupStdTypeTraitMember( 1125 S, R, Loc, "tuple_element", Args, 1126 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1127 return QualType(); 1128 1129 auto *TD = R.getAsSingle<TypeDecl>(); 1130 if (!TD) { 1131 R.suppressDiagnostics(); 1132 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1133 << printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1134 /*Params*/ nullptr); 1135 if (!R.empty()) 1136 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1137 return QualType(); 1138 } 1139 1140 return S.Context.getTypeDeclType(TD); 1141 } 1142 1143 namespace { 1144 struct InitializingBinding { 1145 Sema &S; 1146 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) { 1147 Sema::CodeSynthesisContext Ctx; 1148 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding; 1149 Ctx.PointOfInstantiation = BD->getLocation(); 1150 Ctx.Entity = BD; 1151 S.pushCodeSynthesisContext(Ctx); 1152 } 1153 ~InitializingBinding() { 1154 S.popCodeSynthesisContext(); 1155 } 1156 }; 1157 } 1158 1159 static bool checkTupleLikeDecomposition(Sema &S, 1160 ArrayRef<BindingDecl *> Bindings, 1161 VarDecl *Src, QualType DecompType, 1162 const llvm::APSInt &TupleSize) { 1163 if ((int64_t)Bindings.size() != TupleSize) { 1164 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1165 << DecompType << (unsigned)Bindings.size() 1166 << (unsigned)TupleSize.getLimitedValue(UINT_MAX) 1167 << toString(TupleSize, 10) << (TupleSize < Bindings.size()); 1168 return true; 1169 } 1170 1171 if (Bindings.empty()) 1172 return false; 1173 1174 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1175 1176 // [dcl.decomp]p3: 1177 // The unqualified-id get is looked up in the scope of E by class member 1178 // access lookup ... 1179 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1180 bool UseMemberGet = false; 1181 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1182 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1183 S.LookupQualifiedName(MemberGet, RD); 1184 if (MemberGet.isAmbiguous()) 1185 return true; 1186 // ... and if that finds at least one declaration that is a function 1187 // template whose first template parameter is a non-type parameter ... 1188 for (NamedDecl *D : MemberGet) { 1189 if (FunctionTemplateDecl *FTD = 1190 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1191 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1192 if (TPL->size() != 0 && 1193 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1194 // ... the initializer is e.get<i>(). 1195 UseMemberGet = true; 1196 break; 1197 } 1198 } 1199 } 1200 } 1201 1202 unsigned I = 0; 1203 for (auto *B : Bindings) { 1204 InitializingBinding InitContext(S, B); 1205 SourceLocation Loc = B->getLocation(); 1206 1207 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1208 if (E.isInvalid()) 1209 return true; 1210 1211 // e is an lvalue if the type of the entity is an lvalue reference and 1212 // an xvalue otherwise 1213 if (!Src->getType()->isLValueReferenceType()) 1214 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1215 E.get(), nullptr, VK_XValue, 1216 FPOptionsOverride()); 1217 1218 TemplateArgumentListInfo Args(Loc, Loc); 1219 Args.addArgument( 1220 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1221 1222 if (UseMemberGet) { 1223 // if [lookup of member get] finds at least one declaration, the 1224 // initializer is e.get<i-1>(). 1225 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1226 CXXScopeSpec(), SourceLocation(), nullptr, 1227 MemberGet, &Args, nullptr); 1228 if (E.isInvalid()) 1229 return true; 1230 1231 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1232 } else { 1233 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1234 // in the associated namespaces. 1235 Expr *Get = UnresolvedLookupExpr::Create( 1236 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1237 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1238 UnresolvedSetIterator(), UnresolvedSetIterator()); 1239 1240 Expr *Arg = E.get(); 1241 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1242 } 1243 if (E.isInvalid()) 1244 return true; 1245 Expr *Init = E.get(); 1246 1247 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1248 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1249 if (T.isNull()) 1250 return true; 1251 1252 // each vi is a variable of type "reference to T" initialized with the 1253 // initializer, where the reference is an lvalue reference if the 1254 // initializer is an lvalue and an rvalue reference otherwise 1255 QualType RefType = 1256 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1257 if (RefType.isNull()) 1258 return true; 1259 auto *RefVD = VarDecl::Create( 1260 S.Context, Src->getDeclContext(), Loc, Loc, 1261 B->getDeclName().getAsIdentifierInfo(), RefType, 1262 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1263 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1264 RefVD->setTSCSpec(Src->getTSCSpec()); 1265 RefVD->setImplicit(); 1266 if (Src->isInlineSpecified()) 1267 RefVD->setInlineSpecified(); 1268 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1269 1270 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1271 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1272 InitializationSequence Seq(S, Entity, Kind, Init); 1273 E = Seq.Perform(S, Entity, Kind, Init); 1274 if (E.isInvalid()) 1275 return true; 1276 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1277 if (E.isInvalid()) 1278 return true; 1279 RefVD->setInit(E.get()); 1280 S.CheckCompleteVariableDeclaration(RefVD); 1281 1282 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1283 DeclarationNameInfo(B->getDeclName(), Loc), 1284 RefVD); 1285 if (E.isInvalid()) 1286 return true; 1287 1288 B->setBinding(T, E.get()); 1289 I++; 1290 } 1291 1292 return false; 1293 } 1294 1295 /// Find the base class to decompose in a built-in decomposition of a class type. 1296 /// This base class search is, unfortunately, not quite like any other that we 1297 /// perform anywhere else in C++. 1298 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1299 const CXXRecordDecl *RD, 1300 CXXCastPath &BasePath) { 1301 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1302 CXXBasePath &Path) { 1303 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1304 }; 1305 1306 const CXXRecordDecl *ClassWithFields = nullptr; 1307 AccessSpecifier AS = AS_public; 1308 if (RD->hasDirectFields()) 1309 // [dcl.decomp]p4: 1310 // Otherwise, all of E's non-static data members shall be public direct 1311 // members of E ... 1312 ClassWithFields = RD; 1313 else { 1314 // ... or of ... 1315 CXXBasePaths Paths; 1316 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1317 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1318 // If no classes have fields, just decompose RD itself. (This will work 1319 // if and only if zero bindings were provided.) 1320 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1321 } 1322 1323 CXXBasePath *BestPath = nullptr; 1324 for (auto &P : Paths) { 1325 if (!BestPath) 1326 BestPath = &P; 1327 else if (!S.Context.hasSameType(P.back().Base->getType(), 1328 BestPath->back().Base->getType())) { 1329 // ... the same ... 1330 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1331 << false << RD << BestPath->back().Base->getType() 1332 << P.back().Base->getType(); 1333 return DeclAccessPair(); 1334 } else if (P.Access < BestPath->Access) { 1335 BestPath = &P; 1336 } 1337 } 1338 1339 // ... unambiguous ... 1340 QualType BaseType = BestPath->back().Base->getType(); 1341 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1342 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1343 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1344 return DeclAccessPair(); 1345 } 1346 1347 // ... [accessible, implied by other rules] base class of E. 1348 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1349 *BestPath, diag::err_decomp_decl_inaccessible_base); 1350 AS = BestPath->Access; 1351 1352 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1353 S.BuildBasePathArray(Paths, BasePath); 1354 } 1355 1356 // The above search did not check whether the selected class itself has base 1357 // classes with fields, so check that now. 1358 CXXBasePaths Paths; 1359 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1360 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1361 << (ClassWithFields == RD) << RD << ClassWithFields 1362 << Paths.front().back().Base->getType(); 1363 return DeclAccessPair(); 1364 } 1365 1366 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1367 } 1368 1369 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1370 ValueDecl *Src, QualType DecompType, 1371 const CXXRecordDecl *OrigRD) { 1372 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1373 diag::err_incomplete_type)) 1374 return true; 1375 1376 CXXCastPath BasePath; 1377 DeclAccessPair BasePair = 1378 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1379 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1380 if (!RD) 1381 return true; 1382 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1383 DecompType.getQualifiers()); 1384 1385 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1386 unsigned NumFields = 1387 std::count_if(RD->field_begin(), RD->field_end(), 1388 [](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 diag::err_constexpr_local_var_static) 1896 << isa<CXXConstructorDecl>(Dcl) 1897 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1898 } 1899 return false; 1900 } 1901 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1902 diag::err_constexpr_local_var_non_literal_type, 1903 isa<CXXConstructorDecl>(Dcl))) 1904 return false; 1905 if (!VD->getType()->isDependentType() && 1906 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1907 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1908 SemaRef.Diag( 1909 VD->getLocation(), 1910 SemaRef.getLangOpts().CPlusPlus20 1911 ? diag::warn_cxx17_compat_constexpr_local_var_no_init 1912 : diag::ext_constexpr_local_var_no_init) 1913 << isa<CXXConstructorDecl>(Dcl); 1914 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1915 return false; 1916 } 1917 continue; 1918 } 1919 } 1920 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1921 SemaRef.Diag(VD->getLocation(), 1922 SemaRef.getLangOpts().CPlusPlus14 1923 ? diag::warn_cxx11_compat_constexpr_local_var 1924 : diag::ext_constexpr_local_var) 1925 << isa<CXXConstructorDecl>(Dcl); 1926 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1927 return false; 1928 } 1929 continue; 1930 } 1931 1932 case Decl::NamespaceAlias: 1933 case Decl::Function: 1934 // These are disallowed in C++11 and permitted in C++1y. Allow them 1935 // everywhere as an extension. 1936 if (!Cxx1yLoc.isValid()) 1937 Cxx1yLoc = DS->getBeginLoc(); 1938 continue; 1939 1940 default: 1941 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1942 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1943 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1944 } 1945 return false; 1946 } 1947 } 1948 1949 return true; 1950 } 1951 1952 /// Check that the given field is initialized within a constexpr constructor. 1953 /// 1954 /// \param Dcl The constexpr constructor being checked. 1955 /// \param Field The field being checked. This may be a member of an anonymous 1956 /// struct or union nested within the class being checked. 1957 /// \param Inits All declarations, including anonymous struct/union members and 1958 /// indirect members, for which any initialization was provided. 1959 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1960 /// multiple notes for different members to the same error. 1961 /// \param Kind Whether we're diagnosing a constructor as written or determining 1962 /// whether the formal requirements are satisfied. 1963 /// \return \c false if we're checking for validity and the constructor does 1964 /// not satisfy the requirements on a constexpr constructor. 1965 static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1966 const FunctionDecl *Dcl, 1967 FieldDecl *Field, 1968 llvm::SmallSet<Decl*, 16> &Inits, 1969 bool &Diagnosed, 1970 Sema::CheckConstexprKind Kind) { 1971 // In C++20 onwards, there's nothing to check for validity. 1972 if (Kind == Sema::CheckConstexprKind::CheckValid && 1973 SemaRef.getLangOpts().CPlusPlus20) 1974 return true; 1975 1976 if (Field->isInvalidDecl()) 1977 return true; 1978 1979 if (Field->isUnnamedBitfield()) 1980 return true; 1981 1982 // Anonymous unions with no variant members and empty anonymous structs do not 1983 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1984 // indirect fields don't need initializing. 1985 if (Field->isAnonymousStructOrUnion() && 1986 (Field->getType()->isUnionType() 1987 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1988 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1989 return true; 1990 1991 if (!Inits.count(Field)) { 1992 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1993 if (!Diagnosed) { 1994 SemaRef.Diag(Dcl->getLocation(), 1995 SemaRef.getLangOpts().CPlusPlus20 1996 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init 1997 : diag::ext_constexpr_ctor_missing_init); 1998 Diagnosed = true; 1999 } 2000 SemaRef.Diag(Field->getLocation(), 2001 diag::note_constexpr_ctor_missing_init); 2002 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2003 return false; 2004 } 2005 } else if (Field->isAnonymousStructOrUnion()) { 2006 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 2007 for (auto *I : RD->fields()) 2008 // If an anonymous union contains an anonymous struct of which any member 2009 // is initialized, all members must be initialized. 2010 if (!RD->isUnion() || Inits.count(I)) 2011 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2012 Kind)) 2013 return false; 2014 } 2015 return true; 2016 } 2017 2018 /// Check the provided statement is allowed in a constexpr function 2019 /// definition. 2020 static bool 2021 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 2022 SmallVectorImpl<SourceLocation> &ReturnStmts, 2023 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 2024 Sema::CheckConstexprKind Kind) { 2025 // - its function-body shall be [...] a compound-statement that contains only 2026 switch (S->getStmtClass()) { 2027 case Stmt::NullStmtClass: 2028 // - null statements, 2029 return true; 2030 2031 case Stmt::DeclStmtClass: 2032 // - static_assert-declarations 2033 // - using-declarations, 2034 // - using-directives, 2035 // - typedef declarations and alias-declarations that do not define 2036 // classes or enumerations, 2037 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 2038 return false; 2039 return true; 2040 2041 case Stmt::ReturnStmtClass: 2042 // - and exactly one return statement; 2043 if (isa<CXXConstructorDecl>(Dcl)) { 2044 // C++1y allows return statements in constexpr constructors. 2045 if (!Cxx1yLoc.isValid()) 2046 Cxx1yLoc = S->getBeginLoc(); 2047 return true; 2048 } 2049 2050 ReturnStmts.push_back(S->getBeginLoc()); 2051 return true; 2052 2053 case Stmt::CompoundStmtClass: { 2054 // C++1y allows compound-statements. 2055 if (!Cxx1yLoc.isValid()) 2056 Cxx1yLoc = S->getBeginLoc(); 2057 2058 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2059 for (auto *BodyIt : CompStmt->body()) { 2060 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2061 Cxx1yLoc, Cxx2aLoc, Kind)) 2062 return false; 2063 } 2064 return true; 2065 } 2066 2067 case Stmt::AttributedStmtClass: 2068 if (!Cxx1yLoc.isValid()) 2069 Cxx1yLoc = S->getBeginLoc(); 2070 return true; 2071 2072 case Stmt::IfStmtClass: { 2073 // C++1y allows if-statements. 2074 if (!Cxx1yLoc.isValid()) 2075 Cxx1yLoc = S->getBeginLoc(); 2076 2077 IfStmt *If = cast<IfStmt>(S); 2078 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2079 Cxx1yLoc, Cxx2aLoc, Kind)) 2080 return false; 2081 if (If->getElse() && 2082 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2083 Cxx1yLoc, Cxx2aLoc, Kind)) 2084 return false; 2085 return true; 2086 } 2087 2088 case Stmt::WhileStmtClass: 2089 case Stmt::DoStmtClass: 2090 case Stmt::ForStmtClass: 2091 case Stmt::CXXForRangeStmtClass: 2092 case Stmt::ContinueStmtClass: 2093 // C++1y allows all of these. We don't allow them as extensions in C++11, 2094 // because they don't make sense without variable mutation. 2095 if (!SemaRef.getLangOpts().CPlusPlus14) 2096 break; 2097 if (!Cxx1yLoc.isValid()) 2098 Cxx1yLoc = S->getBeginLoc(); 2099 for (Stmt *SubStmt : S->children()) 2100 if (SubStmt && 2101 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2102 Cxx1yLoc, Cxx2aLoc, Kind)) 2103 return false; 2104 return true; 2105 2106 case Stmt::SwitchStmtClass: 2107 case Stmt::CaseStmtClass: 2108 case Stmt::DefaultStmtClass: 2109 case Stmt::BreakStmtClass: 2110 // C++1y allows switch-statements, and since they don't need variable 2111 // mutation, we can reasonably allow them in C++11 as an extension. 2112 if (!Cxx1yLoc.isValid()) 2113 Cxx1yLoc = S->getBeginLoc(); 2114 for (Stmt *SubStmt : S->children()) 2115 if (SubStmt && 2116 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2117 Cxx1yLoc, Cxx2aLoc, Kind)) 2118 return false; 2119 return true; 2120 2121 case Stmt::GCCAsmStmtClass: 2122 case Stmt::MSAsmStmtClass: 2123 // C++2a allows inline assembly statements. 2124 case Stmt::CXXTryStmtClass: 2125 if (Cxx2aLoc.isInvalid()) 2126 Cxx2aLoc = S->getBeginLoc(); 2127 for (Stmt *SubStmt : S->children()) { 2128 if (SubStmt && 2129 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2130 Cxx1yLoc, Cxx2aLoc, Kind)) 2131 return false; 2132 } 2133 return true; 2134 2135 case Stmt::CXXCatchStmtClass: 2136 // Do not bother checking the language mode (already covered by the 2137 // try block check). 2138 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2139 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2140 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2141 return false; 2142 return true; 2143 2144 default: 2145 if (!isa<Expr>(S)) 2146 break; 2147 2148 // C++1y allows expression-statements. 2149 if (!Cxx1yLoc.isValid()) 2150 Cxx1yLoc = S->getBeginLoc(); 2151 return true; 2152 } 2153 2154 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2155 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2156 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2157 } 2158 return false; 2159 } 2160 2161 /// Check the body for the given constexpr function declaration only contains 2162 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2163 /// 2164 /// \return true if the body is OK, false if we have found or diagnosed a 2165 /// problem. 2166 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2167 Stmt *Body, 2168 Sema::CheckConstexprKind Kind) { 2169 SmallVector<SourceLocation, 4> ReturnStmts; 2170 2171 if (isa<CXXTryStmt>(Body)) { 2172 // C++11 [dcl.constexpr]p3: 2173 // The definition of a constexpr function shall satisfy the following 2174 // constraints: [...] 2175 // - its function-body shall be = delete, = default, or a 2176 // compound-statement 2177 // 2178 // C++11 [dcl.constexpr]p4: 2179 // In the definition of a constexpr constructor, [...] 2180 // - its function-body shall not be a function-try-block; 2181 // 2182 // This restriction is lifted in C++2a, as long as inner statements also 2183 // apply the general constexpr rules. 2184 switch (Kind) { 2185 case Sema::CheckConstexprKind::CheckValid: 2186 if (!SemaRef.getLangOpts().CPlusPlus20) 2187 return false; 2188 break; 2189 2190 case Sema::CheckConstexprKind::Diagnose: 2191 SemaRef.Diag(Body->getBeginLoc(), 2192 !SemaRef.getLangOpts().CPlusPlus20 2193 ? diag::ext_constexpr_function_try_block_cxx20 2194 : diag::warn_cxx17_compat_constexpr_function_try_block) 2195 << isa<CXXConstructorDecl>(Dcl); 2196 break; 2197 } 2198 } 2199 2200 // - its function-body shall be [...] a compound-statement that contains only 2201 // [... list of cases ...] 2202 // 2203 // Note that walking the children here is enough to properly check for 2204 // CompoundStmt and CXXTryStmt body. 2205 SourceLocation Cxx1yLoc, Cxx2aLoc; 2206 for (Stmt *SubStmt : Body->children()) { 2207 if (SubStmt && 2208 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2209 Cxx1yLoc, Cxx2aLoc, Kind)) 2210 return false; 2211 } 2212 2213 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2214 // If this is only valid as an extension, report that we don't satisfy the 2215 // constraints of the current language. 2216 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) || 2217 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2218 return false; 2219 } else if (Cxx2aLoc.isValid()) { 2220 SemaRef.Diag(Cxx2aLoc, 2221 SemaRef.getLangOpts().CPlusPlus20 2222 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2223 : diag::ext_constexpr_body_invalid_stmt_cxx20) 2224 << isa<CXXConstructorDecl>(Dcl); 2225 } else if (Cxx1yLoc.isValid()) { 2226 SemaRef.Diag(Cxx1yLoc, 2227 SemaRef.getLangOpts().CPlusPlus14 2228 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2229 : diag::ext_constexpr_body_invalid_stmt) 2230 << isa<CXXConstructorDecl>(Dcl); 2231 } 2232 2233 if (const CXXConstructorDecl *Constructor 2234 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2235 const CXXRecordDecl *RD = Constructor->getParent(); 2236 // DR1359: 2237 // - every non-variant non-static data member and base class sub-object 2238 // shall be initialized; 2239 // DR1460: 2240 // - if the class is a union having variant members, exactly one of them 2241 // shall be initialized; 2242 if (RD->isUnion()) { 2243 if (Constructor->getNumCtorInitializers() == 0 && 2244 RD->hasVariantMembers()) { 2245 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2246 SemaRef.Diag( 2247 Dcl->getLocation(), 2248 SemaRef.getLangOpts().CPlusPlus20 2249 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2250 : diag::ext_constexpr_union_ctor_no_init); 2251 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2252 return false; 2253 } 2254 } 2255 } else if (!Constructor->isDependentContext() && 2256 !Constructor->isDelegatingConstructor()) { 2257 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2258 2259 // Skip detailed checking if we have enough initializers, and we would 2260 // allow at most one initializer per member. 2261 bool AnyAnonStructUnionMembers = false; 2262 unsigned Fields = 0; 2263 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2264 E = RD->field_end(); I != E; ++I, ++Fields) { 2265 if (I->isAnonymousStructOrUnion()) { 2266 AnyAnonStructUnionMembers = true; 2267 break; 2268 } 2269 } 2270 // DR1460: 2271 // - if the class is a union-like class, but is not a union, for each of 2272 // its anonymous union members having variant members, exactly one of 2273 // them shall be initialized; 2274 if (AnyAnonStructUnionMembers || 2275 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2276 // Check initialization of non-static data members. Base classes are 2277 // always initialized so do not need to be checked. Dependent bases 2278 // might not have initializers in the member initializer list. 2279 llvm::SmallSet<Decl*, 16> Inits; 2280 for (const auto *I: Constructor->inits()) { 2281 if (FieldDecl *FD = I->getMember()) 2282 Inits.insert(FD); 2283 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2284 Inits.insert(ID->chain_begin(), ID->chain_end()); 2285 } 2286 2287 bool Diagnosed = false; 2288 for (auto *I : RD->fields()) 2289 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2290 Kind)) 2291 return false; 2292 } 2293 } 2294 } else { 2295 if (ReturnStmts.empty()) { 2296 // C++1y doesn't require constexpr functions to contain a 'return' 2297 // statement. We still do, unless the return type might be void, because 2298 // otherwise if there's no return statement, the function cannot 2299 // be used in a core constant expression. 2300 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2301 (Dcl->getReturnType()->isVoidType() || 2302 Dcl->getReturnType()->isDependentType()); 2303 switch (Kind) { 2304 case Sema::CheckConstexprKind::Diagnose: 2305 SemaRef.Diag(Dcl->getLocation(), 2306 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2307 : diag::err_constexpr_body_no_return) 2308 << Dcl->isConsteval(); 2309 if (!OK) 2310 return false; 2311 break; 2312 2313 case Sema::CheckConstexprKind::CheckValid: 2314 // The formal requirements don't include this rule in C++14, even 2315 // though the "must be able to produce a constant expression" rules 2316 // still imply it in some cases. 2317 if (!SemaRef.getLangOpts().CPlusPlus14) 2318 return false; 2319 break; 2320 } 2321 } else if (ReturnStmts.size() > 1) { 2322 switch (Kind) { 2323 case Sema::CheckConstexprKind::Diagnose: 2324 SemaRef.Diag( 2325 ReturnStmts.back(), 2326 SemaRef.getLangOpts().CPlusPlus14 2327 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2328 : diag::ext_constexpr_body_multiple_return); 2329 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2330 SemaRef.Diag(ReturnStmts[I], 2331 diag::note_constexpr_body_previous_return); 2332 break; 2333 2334 case Sema::CheckConstexprKind::CheckValid: 2335 if (!SemaRef.getLangOpts().CPlusPlus14) 2336 return false; 2337 break; 2338 } 2339 } 2340 } 2341 2342 // C++11 [dcl.constexpr]p5: 2343 // if no function argument values exist such that the function invocation 2344 // substitution would produce a constant expression, the program is 2345 // ill-formed; no diagnostic required. 2346 // C++11 [dcl.constexpr]p3: 2347 // - every constructor call and implicit conversion used in initializing the 2348 // return value shall be one of those allowed in a constant expression. 2349 // C++11 [dcl.constexpr]p4: 2350 // - every constructor involved in initializing non-static data members and 2351 // base class sub-objects shall be a constexpr constructor. 2352 // 2353 // Note that this rule is distinct from the "requirements for a constexpr 2354 // function", so is not checked in CheckValid mode. 2355 SmallVector<PartialDiagnosticAt, 8> Diags; 2356 if (Kind == Sema::CheckConstexprKind::Diagnose && 2357 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2358 SemaRef.Diag(Dcl->getLocation(), 2359 diag::ext_constexpr_function_never_constant_expr) 2360 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2361 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2362 SemaRef.Diag(Diags[I].first, Diags[I].second); 2363 // Don't return false here: we allow this for compatibility in 2364 // system headers. 2365 } 2366 2367 return true; 2368 } 2369 2370 /// Get the class that is directly named by the current context. This is the 2371 /// class for which an unqualified-id in this scope could name a constructor 2372 /// or destructor. 2373 /// 2374 /// If the scope specifier denotes a class, this will be that class. 2375 /// If the scope specifier is empty, this will be the class whose 2376 /// member-specification we are currently within. Otherwise, there 2377 /// is no such class. 2378 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2379 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2380 2381 if (SS && SS->isInvalid()) 2382 return nullptr; 2383 2384 if (SS && SS->isNotEmpty()) { 2385 DeclContext *DC = computeDeclContext(*SS, true); 2386 return dyn_cast_or_null<CXXRecordDecl>(DC); 2387 } 2388 2389 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2390 } 2391 2392 /// isCurrentClassName - Determine whether the identifier II is the 2393 /// name of the class type currently being defined. In the case of 2394 /// nested classes, this will only return true if II is the name of 2395 /// the innermost class. 2396 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2397 const CXXScopeSpec *SS) { 2398 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2399 return CurDecl && &II == CurDecl->getIdentifier(); 2400 } 2401 2402 /// Determine whether the identifier II is a typo for the name of 2403 /// the class type currently being defined. If so, update it to the identifier 2404 /// that should have been used. 2405 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2406 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2407 2408 if (!getLangOpts().SpellChecking) 2409 return false; 2410 2411 CXXRecordDecl *CurDecl; 2412 if (SS && SS->isSet() && !SS->isInvalid()) { 2413 DeclContext *DC = computeDeclContext(*SS, true); 2414 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2415 } else 2416 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2417 2418 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2419 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2420 < II->getLength()) { 2421 II = CurDecl->getIdentifier(); 2422 return true; 2423 } 2424 2425 return false; 2426 } 2427 2428 /// Determine whether the given class is a base class of the given 2429 /// class, including looking at dependent bases. 2430 static bool findCircularInheritance(const CXXRecordDecl *Class, 2431 const CXXRecordDecl *Current) { 2432 SmallVector<const CXXRecordDecl*, 8> Queue; 2433 2434 Class = Class->getCanonicalDecl(); 2435 while (true) { 2436 for (const auto &I : Current->bases()) { 2437 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2438 if (!Base) 2439 continue; 2440 2441 Base = Base->getDefinition(); 2442 if (!Base) 2443 continue; 2444 2445 if (Base->getCanonicalDecl() == Class) 2446 return true; 2447 2448 Queue.push_back(Base); 2449 } 2450 2451 if (Queue.empty()) 2452 return false; 2453 2454 Current = Queue.pop_back_val(); 2455 } 2456 2457 return false; 2458 } 2459 2460 /// Check the validity of a C++ base class specifier. 2461 /// 2462 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2463 /// and returns NULL otherwise. 2464 CXXBaseSpecifier * 2465 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2466 SourceRange SpecifierRange, 2467 bool Virtual, AccessSpecifier Access, 2468 TypeSourceInfo *TInfo, 2469 SourceLocation EllipsisLoc) { 2470 QualType BaseType = TInfo->getType(); 2471 if (BaseType->containsErrors()) { 2472 // Already emitted a diagnostic when parsing the error type. 2473 return nullptr; 2474 } 2475 // C++ [class.union]p1: 2476 // A union shall not have base classes. 2477 if (Class->isUnion()) { 2478 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2479 << SpecifierRange; 2480 return nullptr; 2481 } 2482 2483 if (EllipsisLoc.isValid() && 2484 !TInfo->getType()->containsUnexpandedParameterPack()) { 2485 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2486 << TInfo->getTypeLoc().getSourceRange(); 2487 EllipsisLoc = SourceLocation(); 2488 } 2489 2490 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2491 2492 if (BaseType->isDependentType()) { 2493 // Make sure that we don't have circular inheritance among our dependent 2494 // bases. For non-dependent bases, the check for completeness below handles 2495 // this. 2496 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2497 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2498 ((BaseDecl = BaseDecl->getDefinition()) && 2499 findCircularInheritance(Class, BaseDecl))) { 2500 Diag(BaseLoc, diag::err_circular_inheritance) 2501 << BaseType << Context.getTypeDeclType(Class); 2502 2503 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2504 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2505 << BaseType; 2506 2507 return nullptr; 2508 } 2509 } 2510 2511 // Make sure that we don't make an ill-formed AST where the type of the 2512 // Class is non-dependent and its attached base class specifier is an 2513 // dependent type, which violates invariants in many clang code paths (e.g. 2514 // constexpr evaluator). If this case happens (in errory-recovery mode), we 2515 // explicitly mark the Class decl invalid. The diagnostic was already 2516 // emitted. 2517 if (!Class->getTypeForDecl()->isDependentType()) 2518 Class->setInvalidDecl(); 2519 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2520 Class->getTagKind() == TTK_Class, 2521 Access, TInfo, EllipsisLoc); 2522 } 2523 2524 // Base specifiers must be record types. 2525 if (!BaseType->isRecordType()) { 2526 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2527 return nullptr; 2528 } 2529 2530 // C++ [class.union]p1: 2531 // A union shall not be used as a base class. 2532 if (BaseType->isUnionType()) { 2533 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2534 return nullptr; 2535 } 2536 2537 // For the MS ABI, propagate DLL attributes to base class templates. 2538 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2539 if (Attr *ClassAttr = getDLLAttr(Class)) { 2540 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2541 BaseType->getAsCXXRecordDecl())) { 2542 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2543 BaseLoc); 2544 } 2545 } 2546 } 2547 2548 // C++ [class.derived]p2: 2549 // The class-name in a base-specifier shall not be an incompletely 2550 // defined class. 2551 if (RequireCompleteType(BaseLoc, BaseType, 2552 diag::err_incomplete_base_class, SpecifierRange)) { 2553 Class->setInvalidDecl(); 2554 return nullptr; 2555 } 2556 2557 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2558 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2559 assert(BaseDecl && "Record type has no declaration"); 2560 BaseDecl = BaseDecl->getDefinition(); 2561 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2562 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2563 assert(CXXBaseDecl && "Base type is not a C++ type"); 2564 2565 // Microsoft docs say: 2566 // "If a base-class has a code_seg attribute, derived classes must have the 2567 // same attribute." 2568 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2569 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2570 if ((DerivedCSA || BaseCSA) && 2571 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2572 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2573 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2574 << CXXBaseDecl; 2575 return nullptr; 2576 } 2577 2578 // A class which contains a flexible array member is not suitable for use as a 2579 // base class: 2580 // - If the layout determines that a base comes before another base, 2581 // the flexible array member would index into the subsequent base. 2582 // - If the layout determines that base comes before the derived class, 2583 // the flexible array member would index into the derived class. 2584 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2585 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2586 << CXXBaseDecl->getDeclName(); 2587 return nullptr; 2588 } 2589 2590 // C++ [class]p3: 2591 // If a class is marked final and it appears as a base-type-specifier in 2592 // base-clause, the program is ill-formed. 2593 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2594 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2595 << CXXBaseDecl->getDeclName() 2596 << FA->isSpelledAsSealed(); 2597 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2598 << CXXBaseDecl->getDeclName() << FA->getRange(); 2599 return nullptr; 2600 } 2601 2602 if (BaseDecl->isInvalidDecl()) 2603 Class->setInvalidDecl(); 2604 2605 // Create the base specifier. 2606 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2607 Class->getTagKind() == TTK_Class, 2608 Access, TInfo, EllipsisLoc); 2609 } 2610 2611 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2612 /// one entry in the base class list of a class specifier, for 2613 /// example: 2614 /// class foo : public bar, virtual private baz { 2615 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2616 BaseResult 2617 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2618 ParsedAttributes &Attributes, 2619 bool Virtual, AccessSpecifier Access, 2620 ParsedType basetype, SourceLocation BaseLoc, 2621 SourceLocation EllipsisLoc) { 2622 if (!classdecl) 2623 return true; 2624 2625 AdjustDeclIfTemplate(classdecl); 2626 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2627 if (!Class) 2628 return true; 2629 2630 // We haven't yet attached the base specifiers. 2631 Class->setIsParsingBaseSpecifiers(); 2632 2633 // We do not support any C++11 attributes on base-specifiers yet. 2634 // Diagnose any attributes we see. 2635 for (const ParsedAttr &AL : Attributes) { 2636 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2637 continue; 2638 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2639 ? (unsigned)diag::warn_unknown_attribute_ignored 2640 : (unsigned)diag::err_base_specifier_attribute) 2641 << AL << AL.getRange(); 2642 } 2643 2644 TypeSourceInfo *TInfo = nullptr; 2645 GetTypeFromParser(basetype, &TInfo); 2646 2647 if (EllipsisLoc.isInvalid() && 2648 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2649 UPPC_BaseType)) 2650 return true; 2651 2652 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2653 Virtual, Access, TInfo, 2654 EllipsisLoc)) 2655 return BaseSpec; 2656 else 2657 Class->setInvalidDecl(); 2658 2659 return true; 2660 } 2661 2662 /// Use small set to collect indirect bases. As this is only used 2663 /// locally, there's no need to abstract the small size parameter. 2664 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2665 2666 /// Recursively add the bases of Type. Don't add Type itself. 2667 static void 2668 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2669 const QualType &Type) 2670 { 2671 // Even though the incoming type is a base, it might not be 2672 // a class -- it could be a template parm, for instance. 2673 if (auto Rec = Type->getAs<RecordType>()) { 2674 auto Decl = Rec->getAsCXXRecordDecl(); 2675 2676 // Iterate over its bases. 2677 for (const auto &BaseSpec : Decl->bases()) { 2678 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2679 .getUnqualifiedType(); 2680 if (Set.insert(Base).second) 2681 // If we've not already seen it, recurse. 2682 NoteIndirectBases(Context, Set, Base); 2683 } 2684 } 2685 } 2686 2687 /// Performs the actual work of attaching the given base class 2688 /// specifiers to a C++ class. 2689 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2690 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2691 if (Bases.empty()) 2692 return false; 2693 2694 // Used to keep track of which base types we have already seen, so 2695 // that we can properly diagnose redundant direct base types. Note 2696 // that the key is always the unqualified canonical type of the base 2697 // class. 2698 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2699 2700 // Used to track indirect bases so we can see if a direct base is 2701 // ambiguous. 2702 IndirectBaseSet IndirectBaseTypes; 2703 2704 // Copy non-redundant base specifiers into permanent storage. 2705 unsigned NumGoodBases = 0; 2706 bool Invalid = false; 2707 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2708 QualType NewBaseType 2709 = Context.getCanonicalType(Bases[idx]->getType()); 2710 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2711 2712 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2713 if (KnownBase) { 2714 // C++ [class.mi]p3: 2715 // A class shall not be specified as a direct base class of a 2716 // derived class more than once. 2717 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2718 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2719 2720 // Delete the duplicate base class specifier; we're going to 2721 // overwrite its pointer later. 2722 Context.Deallocate(Bases[idx]); 2723 2724 Invalid = true; 2725 } else { 2726 // Okay, add this new base class. 2727 KnownBase = Bases[idx]; 2728 Bases[NumGoodBases++] = Bases[idx]; 2729 2730 // Note this base's direct & indirect bases, if there could be ambiguity. 2731 if (Bases.size() > 1) 2732 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2733 2734 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2735 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2736 if (Class->isInterface() && 2737 (!RD->isInterfaceLike() || 2738 KnownBase->getAccessSpecifier() != AS_public)) { 2739 // The Microsoft extension __interface does not permit bases that 2740 // are not themselves public interfaces. 2741 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2742 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2743 << RD->getSourceRange(); 2744 Invalid = true; 2745 } 2746 if (RD->hasAttr<WeakAttr>()) 2747 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2748 } 2749 } 2750 } 2751 2752 // Attach the remaining base class specifiers to the derived class. 2753 Class->setBases(Bases.data(), NumGoodBases); 2754 2755 // Check that the only base classes that are duplicate are virtual. 2756 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2757 // Check whether this direct base is inaccessible due to ambiguity. 2758 QualType BaseType = Bases[idx]->getType(); 2759 2760 // Skip all dependent types in templates being used as base specifiers. 2761 // Checks below assume that the base specifier is a CXXRecord. 2762 if (BaseType->isDependentType()) 2763 continue; 2764 2765 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2766 .getUnqualifiedType(); 2767 2768 if (IndirectBaseTypes.count(CanonicalBase)) { 2769 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2770 /*DetectVirtual=*/true); 2771 bool found 2772 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2773 assert(found); 2774 (void)found; 2775 2776 if (Paths.isAmbiguous(CanonicalBase)) 2777 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2778 << BaseType << getAmbiguousPathsDisplayString(Paths) 2779 << Bases[idx]->getSourceRange(); 2780 else 2781 assert(Bases[idx]->isVirtual()); 2782 } 2783 2784 // Delete the base class specifier, since its data has been copied 2785 // into the CXXRecordDecl. 2786 Context.Deallocate(Bases[idx]); 2787 } 2788 2789 return Invalid; 2790 } 2791 2792 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2793 /// class, after checking whether there are any duplicate base 2794 /// classes. 2795 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2796 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2797 if (!ClassDecl || Bases.empty()) 2798 return; 2799 2800 AdjustDeclIfTemplate(ClassDecl); 2801 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2802 } 2803 2804 /// Determine whether the type \p Derived is a C++ class that is 2805 /// derived from the type \p Base. 2806 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2807 if (!getLangOpts().CPlusPlus) 2808 return false; 2809 2810 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2811 if (!DerivedRD) 2812 return false; 2813 2814 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2815 if (!BaseRD) 2816 return false; 2817 2818 // If either the base or the derived type is invalid, don't try to 2819 // check whether one is derived from the other. 2820 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2821 return false; 2822 2823 // FIXME: In a modules build, do we need the entire path to be visible for us 2824 // to be able to use the inheritance relationship? 2825 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2826 return false; 2827 2828 return DerivedRD->isDerivedFrom(BaseRD); 2829 } 2830 2831 /// Determine whether the type \p Derived is a C++ class that is 2832 /// derived from the type \p Base. 2833 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2834 CXXBasePaths &Paths) { 2835 if (!getLangOpts().CPlusPlus) 2836 return false; 2837 2838 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2839 if (!DerivedRD) 2840 return false; 2841 2842 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2843 if (!BaseRD) 2844 return false; 2845 2846 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2847 return false; 2848 2849 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2850 } 2851 2852 static void BuildBasePathArray(const CXXBasePath &Path, 2853 CXXCastPath &BasePathArray) { 2854 // We first go backward and check if we have a virtual base. 2855 // FIXME: It would be better if CXXBasePath had the base specifier for 2856 // the nearest virtual base. 2857 unsigned Start = 0; 2858 for (unsigned I = Path.size(); I != 0; --I) { 2859 if (Path[I - 1].Base->isVirtual()) { 2860 Start = I - 1; 2861 break; 2862 } 2863 } 2864 2865 // Now add all bases. 2866 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2867 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2868 } 2869 2870 2871 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2872 CXXCastPath &BasePathArray) { 2873 assert(BasePathArray.empty() && "Base path array must be empty!"); 2874 assert(Paths.isRecordingPaths() && "Must record paths!"); 2875 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2876 } 2877 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2878 /// conversion (where Derived and Base are class types) is 2879 /// well-formed, meaning that the conversion is unambiguous (and 2880 /// that all of the base classes are accessible). Returns true 2881 /// and emits a diagnostic if the code is ill-formed, returns false 2882 /// otherwise. Loc is the location where this routine should point to 2883 /// if there is an error, and Range is the source range to highlight 2884 /// if there is an error. 2885 /// 2886 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the 2887 /// diagnostic for the respective type of error will be suppressed, but the 2888 /// check for ill-formed code will still be performed. 2889 bool 2890 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2891 unsigned InaccessibleBaseID, 2892 unsigned AmbiguousBaseConvID, 2893 SourceLocation Loc, SourceRange Range, 2894 DeclarationName Name, 2895 CXXCastPath *BasePath, 2896 bool IgnoreAccess) { 2897 // First, determine whether the path from Derived to Base is 2898 // ambiguous. This is slightly more expensive than checking whether 2899 // the Derived to Base conversion exists, because here we need to 2900 // explore multiple paths to determine if there is an ambiguity. 2901 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2902 /*DetectVirtual=*/false); 2903 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2904 if (!DerivationOkay) 2905 return true; 2906 2907 const CXXBasePath *Path = nullptr; 2908 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2909 Path = &Paths.front(); 2910 2911 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2912 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2913 // user to access such bases. 2914 if (!Path && getLangOpts().MSVCCompat) { 2915 for (const CXXBasePath &PossiblePath : Paths) { 2916 if (PossiblePath.size() == 1) { 2917 Path = &PossiblePath; 2918 if (AmbiguousBaseConvID) 2919 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2920 << Base << Derived << Range; 2921 break; 2922 } 2923 } 2924 } 2925 2926 if (Path) { 2927 if (!IgnoreAccess) { 2928 // Check that the base class can be accessed. 2929 switch ( 2930 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2931 case AR_inaccessible: 2932 return true; 2933 case AR_accessible: 2934 case AR_dependent: 2935 case AR_delayed: 2936 break; 2937 } 2938 } 2939 2940 // Build a base path if necessary. 2941 if (BasePath) 2942 ::BuildBasePathArray(*Path, *BasePath); 2943 return false; 2944 } 2945 2946 if (AmbiguousBaseConvID) { 2947 // We know that the derived-to-base conversion is ambiguous, and 2948 // we're going to produce a diagnostic. Perform the derived-to-base 2949 // search just one more time to compute all of the possible paths so 2950 // that we can print them out. This is more expensive than any of 2951 // the previous derived-to-base checks we've done, but at this point 2952 // performance isn't as much of an issue. 2953 Paths.clear(); 2954 Paths.setRecordingPaths(true); 2955 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2956 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2957 (void)StillOkay; 2958 2959 // Build up a textual representation of the ambiguous paths, e.g., 2960 // D -> B -> A, that will be used to illustrate the ambiguous 2961 // conversions in the diagnostic. We only print one of the paths 2962 // to each base class subobject. 2963 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2964 2965 Diag(Loc, AmbiguousBaseConvID) 2966 << Derived << Base << PathDisplayStr << Range << Name; 2967 } 2968 return true; 2969 } 2970 2971 bool 2972 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2973 SourceLocation Loc, SourceRange Range, 2974 CXXCastPath *BasePath, 2975 bool IgnoreAccess) { 2976 return CheckDerivedToBaseConversion( 2977 Derived, Base, diag::err_upcast_to_inaccessible_base, 2978 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2979 BasePath, IgnoreAccess); 2980 } 2981 2982 2983 /// Builds a string representing ambiguous paths from a 2984 /// specific derived class to different subobjects of the same base 2985 /// class. 2986 /// 2987 /// This function builds a string that can be used in error messages 2988 /// to show the different paths that one can take through the 2989 /// inheritance hierarchy to go from the derived class to different 2990 /// subobjects of a base class. The result looks something like this: 2991 /// @code 2992 /// struct D -> struct B -> struct A 2993 /// struct D -> struct C -> struct A 2994 /// @endcode 2995 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2996 std::string PathDisplayStr; 2997 std::set<unsigned> DisplayedPaths; 2998 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2999 Path != Paths.end(); ++Path) { 3000 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 3001 // We haven't displayed a path to this particular base 3002 // class subobject yet. 3003 PathDisplayStr += "\n "; 3004 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 3005 for (CXXBasePath::const_iterator Element = Path->begin(); 3006 Element != Path->end(); ++Element) 3007 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 3008 } 3009 } 3010 3011 return PathDisplayStr; 3012 } 3013 3014 //===----------------------------------------------------------------------===// 3015 // C++ class member Handling 3016 //===----------------------------------------------------------------------===// 3017 3018 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 3019 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 3020 SourceLocation ColonLoc, 3021 const ParsedAttributesView &Attrs) { 3022 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 3023 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 3024 ASLoc, ColonLoc); 3025 CurContext->addHiddenDecl(ASDecl); 3026 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 3027 } 3028 3029 /// CheckOverrideControl - Check C++11 override control semantics. 3030 void Sema::CheckOverrideControl(NamedDecl *D) { 3031 if (D->isInvalidDecl()) 3032 return; 3033 3034 // We only care about "override" and "final" declarations. 3035 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 3036 return; 3037 3038 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3039 3040 // We can't check dependent instance methods. 3041 if (MD && MD->isInstance() && 3042 (MD->getParent()->hasAnyDependentBases() || 3043 MD->getType()->isDependentType())) 3044 return; 3045 3046 if (MD && !MD->isVirtual()) { 3047 // If we have a non-virtual method, check if if hides a virtual method. 3048 // (In that case, it's most likely the method has the wrong type.) 3049 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 3050 FindHiddenVirtualMethods(MD, OverloadedMethods); 3051 3052 if (!OverloadedMethods.empty()) { 3053 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3054 Diag(OA->getLocation(), 3055 diag::override_keyword_hides_virtual_member_function) 3056 << "override" << (OverloadedMethods.size() > 1); 3057 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3058 Diag(FA->getLocation(), 3059 diag::override_keyword_hides_virtual_member_function) 3060 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3061 << (OverloadedMethods.size() > 1); 3062 } 3063 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3064 MD->setInvalidDecl(); 3065 return; 3066 } 3067 // Fall through into the general case diagnostic. 3068 // FIXME: We might want to attempt typo correction here. 3069 } 3070 3071 if (!MD || !MD->isVirtual()) { 3072 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3073 Diag(OA->getLocation(), 3074 diag::override_keyword_only_allowed_on_virtual_member_functions) 3075 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3076 D->dropAttr<OverrideAttr>(); 3077 } 3078 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3079 Diag(FA->getLocation(), 3080 diag::override_keyword_only_allowed_on_virtual_member_functions) 3081 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3082 << FixItHint::CreateRemoval(FA->getLocation()); 3083 D->dropAttr<FinalAttr>(); 3084 } 3085 return; 3086 } 3087 3088 // C++11 [class.virtual]p5: 3089 // If a function is marked with the virt-specifier override and 3090 // does not override a member function of a base class, the program is 3091 // ill-formed. 3092 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3093 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3094 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3095 << MD->getDeclName(); 3096 } 3097 3098 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { 3099 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3100 return; 3101 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3102 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3103 return; 3104 3105 SourceLocation Loc = MD->getLocation(); 3106 SourceLocation SpellingLoc = Loc; 3107 if (getSourceManager().isMacroArgExpansion(Loc)) 3108 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3109 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3110 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3111 return; 3112 3113 if (MD->size_overridden_methods() > 0) { 3114 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { 3115 unsigned DiagID = 3116 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation()) 3117 ? DiagInconsistent 3118 : DiagSuggest; 3119 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3120 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3121 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3122 }; 3123 if (isa<CXXDestructorDecl>(MD)) 3124 EmitDiag( 3125 diag::warn_inconsistent_destructor_marked_not_override_overriding, 3126 diag::warn_suggest_destructor_marked_not_override_overriding); 3127 else 3128 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding, 3129 diag::warn_suggest_function_marked_not_override_overriding); 3130 } 3131 } 3132 3133 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3134 /// function overrides a virtual member function marked 'final', according to 3135 /// C++11 [class.virtual]p4. 3136 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3137 const CXXMethodDecl *Old) { 3138 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3139 if (!FA) 3140 return false; 3141 3142 Diag(New->getLocation(), diag::err_final_function_overridden) 3143 << New->getDeclName() 3144 << FA->isSpelledAsSealed(); 3145 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3146 return true; 3147 } 3148 3149 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3150 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3151 // FIXME: Destruction of ObjC lifetime types has side-effects. 3152 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3153 return !RD->isCompleteDefinition() || 3154 !RD->hasTrivialDefaultConstructor() || 3155 !RD->hasTrivialDestructor(); 3156 return false; 3157 } 3158 3159 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3160 ParsedAttributesView::const_iterator Itr = 3161 llvm::find_if(list, [](const ParsedAttr &AL) { 3162 return AL.isDeclspecPropertyAttribute(); 3163 }); 3164 if (Itr != list.end()) 3165 return &*Itr; 3166 return nullptr; 3167 } 3168 3169 // Check if there is a field shadowing. 3170 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3171 DeclarationName FieldName, 3172 const CXXRecordDecl *RD, 3173 bool DeclIsField) { 3174 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3175 return; 3176 3177 // To record a shadowed field in a base 3178 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3179 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3180 CXXBasePath &Path) { 3181 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3182 // Record an ambiguous path directly 3183 if (Bases.find(Base) != Bases.end()) 3184 return true; 3185 for (const auto Field : Base->lookup(FieldName)) { 3186 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3187 Field->getAccess() != AS_private) { 3188 assert(Field->getAccess() != AS_none); 3189 assert(Bases.find(Base) == Bases.end()); 3190 Bases[Base] = Field; 3191 return true; 3192 } 3193 } 3194 return false; 3195 }; 3196 3197 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3198 /*DetectVirtual=*/true); 3199 if (!RD->lookupInBases(FieldShadowed, Paths)) 3200 return; 3201 3202 for (const auto &P : Paths) { 3203 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3204 auto It = Bases.find(Base); 3205 // Skip duplicated bases 3206 if (It == Bases.end()) 3207 continue; 3208 auto BaseField = It->second; 3209 assert(BaseField->getAccess() != AS_private); 3210 if (AS_none != 3211 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3212 Diag(Loc, diag::warn_shadow_field) 3213 << FieldName << RD << Base << DeclIsField; 3214 Diag(BaseField->getLocation(), diag::note_shadow_field); 3215 Bases.erase(It); 3216 } 3217 } 3218 } 3219 3220 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3221 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3222 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3223 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3224 /// present (but parsing it has been deferred). 3225 NamedDecl * 3226 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3227 MultiTemplateParamsArg TemplateParameterLists, 3228 Expr *BW, const VirtSpecifiers &VS, 3229 InClassInitStyle InitStyle) { 3230 const DeclSpec &DS = D.getDeclSpec(); 3231 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3232 DeclarationName Name = NameInfo.getName(); 3233 SourceLocation Loc = NameInfo.getLoc(); 3234 3235 // For anonymous bitfields, the location should point to the type. 3236 if (Loc.isInvalid()) 3237 Loc = D.getBeginLoc(); 3238 3239 Expr *BitWidth = static_cast<Expr*>(BW); 3240 3241 assert(isa<CXXRecordDecl>(CurContext)); 3242 assert(!DS.isFriendSpecified()); 3243 3244 bool isFunc = D.isDeclarationOfFunction(); 3245 const ParsedAttr *MSPropertyAttr = 3246 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3247 3248 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3249 // The Microsoft extension __interface only permits public member functions 3250 // and prohibits constructors, destructors, operators, non-public member 3251 // functions, static methods and data members. 3252 unsigned InvalidDecl; 3253 bool ShowDeclName = true; 3254 if (!isFunc && 3255 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3256 InvalidDecl = 0; 3257 else if (!isFunc) 3258 InvalidDecl = 1; 3259 else if (AS != AS_public) 3260 InvalidDecl = 2; 3261 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3262 InvalidDecl = 3; 3263 else switch (Name.getNameKind()) { 3264 case DeclarationName::CXXConstructorName: 3265 InvalidDecl = 4; 3266 ShowDeclName = false; 3267 break; 3268 3269 case DeclarationName::CXXDestructorName: 3270 InvalidDecl = 5; 3271 ShowDeclName = false; 3272 break; 3273 3274 case DeclarationName::CXXOperatorName: 3275 case DeclarationName::CXXConversionFunctionName: 3276 InvalidDecl = 6; 3277 break; 3278 3279 default: 3280 InvalidDecl = 0; 3281 break; 3282 } 3283 3284 if (InvalidDecl) { 3285 if (ShowDeclName) 3286 Diag(Loc, diag::err_invalid_member_in_interface) 3287 << (InvalidDecl-1) << Name; 3288 else 3289 Diag(Loc, diag::err_invalid_member_in_interface) 3290 << (InvalidDecl-1) << ""; 3291 return nullptr; 3292 } 3293 } 3294 3295 // C++ 9.2p6: A member shall not be declared to have automatic storage 3296 // duration (auto, register) or with the extern storage-class-specifier. 3297 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3298 // data members and cannot be applied to names declared const or static, 3299 // and cannot be applied to reference members. 3300 switch (DS.getStorageClassSpec()) { 3301 case DeclSpec::SCS_unspecified: 3302 case DeclSpec::SCS_typedef: 3303 case DeclSpec::SCS_static: 3304 break; 3305 case DeclSpec::SCS_mutable: 3306 if (isFunc) { 3307 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3308 3309 // FIXME: It would be nicer if the keyword was ignored only for this 3310 // declarator. Otherwise we could get follow-up errors. 3311 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3312 } 3313 break; 3314 default: 3315 Diag(DS.getStorageClassSpecLoc(), 3316 diag::err_storageclass_invalid_for_member); 3317 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3318 break; 3319 } 3320 3321 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3322 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3323 !isFunc); 3324 3325 if (DS.hasConstexprSpecifier() && isInstField) { 3326 SemaDiagnosticBuilder B = 3327 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3328 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3329 if (InitStyle == ICIS_NoInit) { 3330 B << 0 << 0; 3331 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3332 B << FixItHint::CreateRemoval(ConstexprLoc); 3333 else { 3334 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3335 D.getMutableDeclSpec().ClearConstexprSpec(); 3336 const char *PrevSpec; 3337 unsigned DiagID; 3338 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3339 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3340 (void)Failed; 3341 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3342 } 3343 } else { 3344 B << 1; 3345 const char *PrevSpec; 3346 unsigned DiagID; 3347 if (D.getMutableDeclSpec().SetStorageClassSpec( 3348 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3349 Context.getPrintingPolicy())) { 3350 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3351 "This is the only DeclSpec that should fail to be applied"); 3352 B << 1; 3353 } else { 3354 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3355 isInstField = false; 3356 } 3357 } 3358 } 3359 3360 NamedDecl *Member; 3361 if (isInstField) { 3362 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3363 3364 // Data members must have identifiers for names. 3365 if (!Name.isIdentifier()) { 3366 Diag(Loc, diag::err_bad_variable_name) 3367 << Name; 3368 return nullptr; 3369 } 3370 3371 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3372 3373 // Member field could not be with "template" keyword. 3374 // So TemplateParameterLists should be empty in this case. 3375 if (TemplateParameterLists.size()) { 3376 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3377 if (TemplateParams->size()) { 3378 // There is no such thing as a member field template. 3379 Diag(D.getIdentifierLoc(), diag::err_template_member) 3380 << II 3381 << SourceRange(TemplateParams->getTemplateLoc(), 3382 TemplateParams->getRAngleLoc()); 3383 } else { 3384 // There is an extraneous 'template<>' for this member. 3385 Diag(TemplateParams->getTemplateLoc(), 3386 diag::err_template_member_noparams) 3387 << II 3388 << SourceRange(TemplateParams->getTemplateLoc(), 3389 TemplateParams->getRAngleLoc()); 3390 } 3391 return nullptr; 3392 } 3393 3394 if (SS.isSet() && !SS.isInvalid()) { 3395 // The user provided a superfluous scope specifier inside a class 3396 // definition: 3397 // 3398 // class X { 3399 // int X::member; 3400 // }; 3401 if (DeclContext *DC = computeDeclContext(SS, false)) 3402 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3403 D.getName().getKind() == 3404 UnqualifiedIdKind::IK_TemplateId); 3405 else 3406 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3407 << Name << SS.getRange(); 3408 3409 SS.clear(); 3410 } 3411 3412 if (MSPropertyAttr) { 3413 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3414 BitWidth, InitStyle, AS, *MSPropertyAttr); 3415 if (!Member) 3416 return nullptr; 3417 isInstField = false; 3418 } else { 3419 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3420 BitWidth, InitStyle, AS); 3421 if (!Member) 3422 return nullptr; 3423 } 3424 3425 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3426 } else { 3427 Member = HandleDeclarator(S, D, TemplateParameterLists); 3428 if (!Member) 3429 return nullptr; 3430 3431 // Non-instance-fields can't have a bitfield. 3432 if (BitWidth) { 3433 if (Member->isInvalidDecl()) { 3434 // don't emit another diagnostic. 3435 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3436 // C++ 9.6p3: A bit-field shall not be a static member. 3437 // "static member 'A' cannot be a bit-field" 3438 Diag(Loc, diag::err_static_not_bitfield) 3439 << Name << BitWidth->getSourceRange(); 3440 } else if (isa<TypedefDecl>(Member)) { 3441 // "typedef member 'x' cannot be a bit-field" 3442 Diag(Loc, diag::err_typedef_not_bitfield) 3443 << Name << BitWidth->getSourceRange(); 3444 } else { 3445 // A function typedef ("typedef int f(); f a;"). 3446 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3447 Diag(Loc, diag::err_not_integral_type_bitfield) 3448 << Name << cast<ValueDecl>(Member)->getType() 3449 << BitWidth->getSourceRange(); 3450 } 3451 3452 BitWidth = nullptr; 3453 Member->setInvalidDecl(); 3454 } 3455 3456 NamedDecl *NonTemplateMember = Member; 3457 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3458 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3459 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3460 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3461 3462 Member->setAccess(AS); 3463 3464 // If we have declared a member function template or static data member 3465 // template, set the access of the templated declaration as well. 3466 if (NonTemplateMember != Member) 3467 NonTemplateMember->setAccess(AS); 3468 3469 // C++ [temp.deduct.guide]p3: 3470 // A deduction guide [...] for a member class template [shall be 3471 // declared] with the same access [as the template]. 3472 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3473 auto *TD = DG->getDeducedTemplate(); 3474 // Access specifiers are only meaningful if both the template and the 3475 // deduction guide are from the same scope. 3476 if (AS != TD->getAccess() && 3477 TD->getDeclContext()->getRedeclContext()->Equals( 3478 DG->getDeclContext()->getRedeclContext())) { 3479 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3480 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3481 << TD->getAccess(); 3482 const AccessSpecDecl *LastAccessSpec = nullptr; 3483 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3484 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3485 LastAccessSpec = AccessSpec; 3486 } 3487 assert(LastAccessSpec && "differing access with no access specifier"); 3488 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3489 << AS; 3490 } 3491 } 3492 } 3493 3494 if (VS.isOverrideSpecified()) 3495 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3496 AttributeCommonInfo::AS_Keyword)); 3497 if (VS.isFinalSpecified()) 3498 Member->addAttr(FinalAttr::Create( 3499 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3500 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3501 3502 if (VS.getLastLocation().isValid()) { 3503 // Update the end location of a method that has a virt-specifiers. 3504 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3505 MD->setRangeEnd(VS.getLastLocation()); 3506 } 3507 3508 CheckOverrideControl(Member); 3509 3510 assert((Name || isInstField) && "No identifier for non-field ?"); 3511 3512 if (isInstField) { 3513 FieldDecl *FD = cast<FieldDecl>(Member); 3514 FieldCollector->Add(FD); 3515 3516 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3517 // Remember all explicit private FieldDecls that have a name, no side 3518 // effects and are not part of a dependent type declaration. 3519 if (!FD->isImplicit() && FD->getDeclName() && 3520 FD->getAccess() == AS_private && 3521 !FD->hasAttr<UnusedAttr>() && 3522 !FD->getParent()->isDependentContext() && 3523 !InitializationHasSideEffects(*FD)) 3524 UnusedPrivateFields.insert(FD); 3525 } 3526 } 3527 3528 return Member; 3529 } 3530 3531 namespace { 3532 class UninitializedFieldVisitor 3533 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3534 Sema &S; 3535 // List of Decls to generate a warning on. Also remove Decls that become 3536 // initialized. 3537 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3538 // List of base classes of the record. Classes are removed after their 3539 // initializers. 3540 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3541 // Vector of decls to be removed from the Decl set prior to visiting the 3542 // nodes. These Decls may have been initialized in the prior initializer. 3543 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3544 // If non-null, add a note to the warning pointing back to the constructor. 3545 const CXXConstructorDecl *Constructor; 3546 // Variables to hold state when processing an initializer list. When 3547 // InitList is true, special case initialization of FieldDecls matching 3548 // InitListFieldDecl. 3549 bool InitList; 3550 FieldDecl *InitListFieldDecl; 3551 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3552 3553 public: 3554 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3555 UninitializedFieldVisitor(Sema &S, 3556 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3557 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3558 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3559 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3560 3561 // Returns true if the use of ME is not an uninitialized use. 3562 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3563 bool CheckReferenceOnly) { 3564 llvm::SmallVector<FieldDecl*, 4> Fields; 3565 bool ReferenceField = false; 3566 while (ME) { 3567 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3568 if (!FD) 3569 return false; 3570 Fields.push_back(FD); 3571 if (FD->getType()->isReferenceType()) 3572 ReferenceField = true; 3573 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3574 } 3575 3576 // Binding a reference to an uninitialized field is not an 3577 // uninitialized use. 3578 if (CheckReferenceOnly && !ReferenceField) 3579 return true; 3580 3581 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3582 // Discard the first field since it is the field decl that is being 3583 // initialized. 3584 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3585 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3586 } 3587 3588 for (auto UsedIter = UsedFieldIndex.begin(), 3589 UsedEnd = UsedFieldIndex.end(), 3590 OrigIter = InitFieldIndex.begin(), 3591 OrigEnd = InitFieldIndex.end(); 3592 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3593 if (*UsedIter < *OrigIter) 3594 return true; 3595 if (*UsedIter > *OrigIter) 3596 break; 3597 } 3598 3599 return false; 3600 } 3601 3602 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3603 bool AddressOf) { 3604 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3605 return; 3606 3607 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3608 // or union. 3609 MemberExpr *FieldME = ME; 3610 3611 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3612 3613 Expr *Base = ME; 3614 while (MemberExpr *SubME = 3615 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3616 3617 if (isa<VarDecl>(SubME->getMemberDecl())) 3618 return; 3619 3620 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3621 if (!FD->isAnonymousStructOrUnion()) 3622 FieldME = SubME; 3623 3624 if (!FieldME->getType().isPODType(S.Context)) 3625 AllPODFields = false; 3626 3627 Base = SubME->getBase(); 3628 } 3629 3630 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) { 3631 Visit(Base); 3632 return; 3633 } 3634 3635 if (AddressOf && AllPODFields) 3636 return; 3637 3638 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3639 3640 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3641 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3642 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3643 } 3644 3645 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3646 QualType T = BaseCast->getType(); 3647 if (T->isPointerType() && 3648 BaseClasses.count(T->getPointeeType())) { 3649 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3650 << T->getPointeeType() << FoundVD; 3651 } 3652 } 3653 } 3654 3655 if (!Decls.count(FoundVD)) 3656 return; 3657 3658 const bool IsReference = FoundVD->getType()->isReferenceType(); 3659 3660 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3661 // Special checking for initializer lists. 3662 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3663 return; 3664 } 3665 } else { 3666 // Prevent double warnings on use of unbounded references. 3667 if (CheckReferenceOnly && !IsReference) 3668 return; 3669 } 3670 3671 unsigned diag = IsReference 3672 ? diag::warn_reference_field_is_uninit 3673 : diag::warn_field_is_uninit; 3674 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3675 if (Constructor) 3676 S.Diag(Constructor->getLocation(), 3677 diag::note_uninit_in_this_constructor) 3678 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3679 3680 } 3681 3682 void HandleValue(Expr *E, bool AddressOf) { 3683 E = E->IgnoreParens(); 3684 3685 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3686 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3687 AddressOf /*AddressOf*/); 3688 return; 3689 } 3690 3691 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3692 Visit(CO->getCond()); 3693 HandleValue(CO->getTrueExpr(), AddressOf); 3694 HandleValue(CO->getFalseExpr(), AddressOf); 3695 return; 3696 } 3697 3698 if (BinaryConditionalOperator *BCO = 3699 dyn_cast<BinaryConditionalOperator>(E)) { 3700 Visit(BCO->getCond()); 3701 HandleValue(BCO->getFalseExpr(), AddressOf); 3702 return; 3703 } 3704 3705 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3706 HandleValue(OVE->getSourceExpr(), AddressOf); 3707 return; 3708 } 3709 3710 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3711 switch (BO->getOpcode()) { 3712 default: 3713 break; 3714 case(BO_PtrMemD): 3715 case(BO_PtrMemI): 3716 HandleValue(BO->getLHS(), AddressOf); 3717 Visit(BO->getRHS()); 3718 return; 3719 case(BO_Comma): 3720 Visit(BO->getLHS()); 3721 HandleValue(BO->getRHS(), AddressOf); 3722 return; 3723 } 3724 } 3725 3726 Visit(E); 3727 } 3728 3729 void CheckInitListExpr(InitListExpr *ILE) { 3730 InitFieldIndex.push_back(0); 3731 for (auto Child : ILE->children()) { 3732 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3733 CheckInitListExpr(SubList); 3734 } else { 3735 Visit(Child); 3736 } 3737 ++InitFieldIndex.back(); 3738 } 3739 InitFieldIndex.pop_back(); 3740 } 3741 3742 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3743 FieldDecl *Field, const Type *BaseClass) { 3744 // Remove Decls that may have been initialized in the previous 3745 // initializer. 3746 for (ValueDecl* VD : DeclsToRemove) 3747 Decls.erase(VD); 3748 DeclsToRemove.clear(); 3749 3750 Constructor = FieldConstructor; 3751 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3752 3753 if (ILE && Field) { 3754 InitList = true; 3755 InitListFieldDecl = Field; 3756 InitFieldIndex.clear(); 3757 CheckInitListExpr(ILE); 3758 } else { 3759 InitList = false; 3760 Visit(E); 3761 } 3762 3763 if (Field) 3764 Decls.erase(Field); 3765 if (BaseClass) 3766 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3767 } 3768 3769 void VisitMemberExpr(MemberExpr *ME) { 3770 // All uses of unbounded reference fields will warn. 3771 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3772 } 3773 3774 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3775 if (E->getCastKind() == CK_LValueToRValue) { 3776 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3777 return; 3778 } 3779 3780 Inherited::VisitImplicitCastExpr(E); 3781 } 3782 3783 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3784 if (E->getConstructor()->isCopyConstructor()) { 3785 Expr *ArgExpr = E->getArg(0); 3786 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3787 if (ILE->getNumInits() == 1) 3788 ArgExpr = ILE->getInit(0); 3789 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3790 if (ICE->getCastKind() == CK_NoOp) 3791 ArgExpr = ICE->getSubExpr(); 3792 HandleValue(ArgExpr, false /*AddressOf*/); 3793 return; 3794 } 3795 Inherited::VisitCXXConstructExpr(E); 3796 } 3797 3798 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3799 Expr *Callee = E->getCallee(); 3800 if (isa<MemberExpr>(Callee)) { 3801 HandleValue(Callee, false /*AddressOf*/); 3802 for (auto Arg : E->arguments()) 3803 Visit(Arg); 3804 return; 3805 } 3806 3807 Inherited::VisitCXXMemberCallExpr(E); 3808 } 3809 3810 void VisitCallExpr(CallExpr *E) { 3811 // Treat std::move as a use. 3812 if (E->isCallToStdMove()) { 3813 HandleValue(E->getArg(0), /*AddressOf=*/false); 3814 return; 3815 } 3816 3817 Inherited::VisitCallExpr(E); 3818 } 3819 3820 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3821 Expr *Callee = E->getCallee(); 3822 3823 if (isa<UnresolvedLookupExpr>(Callee)) 3824 return Inherited::VisitCXXOperatorCallExpr(E); 3825 3826 Visit(Callee); 3827 for (auto Arg : E->arguments()) 3828 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3829 } 3830 3831 void VisitBinaryOperator(BinaryOperator *E) { 3832 // If a field assignment is detected, remove the field from the 3833 // uninitiailized field set. 3834 if (E->getOpcode() == BO_Assign) 3835 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3836 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3837 if (!FD->getType()->isReferenceType()) 3838 DeclsToRemove.push_back(FD); 3839 3840 if (E->isCompoundAssignmentOp()) { 3841 HandleValue(E->getLHS(), false /*AddressOf*/); 3842 Visit(E->getRHS()); 3843 return; 3844 } 3845 3846 Inherited::VisitBinaryOperator(E); 3847 } 3848 3849 void VisitUnaryOperator(UnaryOperator *E) { 3850 if (E->isIncrementDecrementOp()) { 3851 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3852 return; 3853 } 3854 if (E->getOpcode() == UO_AddrOf) { 3855 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3856 HandleValue(ME->getBase(), true /*AddressOf*/); 3857 return; 3858 } 3859 } 3860 3861 Inherited::VisitUnaryOperator(E); 3862 } 3863 }; 3864 3865 // Diagnose value-uses of fields to initialize themselves, e.g. 3866 // foo(foo) 3867 // where foo is not also a parameter to the constructor. 3868 // Also diagnose across field uninitialized use such as 3869 // x(y), y(x) 3870 // TODO: implement -Wuninitialized and fold this into that framework. 3871 static void DiagnoseUninitializedFields( 3872 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3873 3874 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3875 Constructor->getLocation())) { 3876 return; 3877 } 3878 3879 if (Constructor->isInvalidDecl()) 3880 return; 3881 3882 const CXXRecordDecl *RD = Constructor->getParent(); 3883 3884 if (RD->isDependentContext()) 3885 return; 3886 3887 // Holds fields that are uninitialized. 3888 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3889 3890 // At the beginning, all fields are uninitialized. 3891 for (auto *I : RD->decls()) { 3892 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3893 UninitializedFields.insert(FD); 3894 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3895 UninitializedFields.insert(IFD->getAnonField()); 3896 } 3897 } 3898 3899 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3900 for (auto I : RD->bases()) 3901 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3902 3903 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3904 return; 3905 3906 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3907 UninitializedFields, 3908 UninitializedBaseClasses); 3909 3910 for (const auto *FieldInit : Constructor->inits()) { 3911 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3912 break; 3913 3914 Expr *InitExpr = FieldInit->getInit(); 3915 if (!InitExpr) 3916 continue; 3917 3918 if (CXXDefaultInitExpr *Default = 3919 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3920 InitExpr = Default->getExpr(); 3921 if (!InitExpr) 3922 continue; 3923 // In class initializers will point to the constructor. 3924 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3925 FieldInit->getAnyMember(), 3926 FieldInit->getBaseClass()); 3927 } else { 3928 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3929 FieldInit->getAnyMember(), 3930 FieldInit->getBaseClass()); 3931 } 3932 } 3933 } 3934 } // namespace 3935 3936 /// Enter a new C++ default initializer scope. After calling this, the 3937 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3938 /// parsing or instantiating the initializer failed. 3939 void Sema::ActOnStartCXXInClassMemberInitializer() { 3940 // Create a synthetic function scope to represent the call to the constructor 3941 // that notionally surrounds a use of this initializer. 3942 PushFunctionScope(); 3943 } 3944 3945 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 3946 if (!D.isFunctionDeclarator()) 3947 return; 3948 auto &FTI = D.getFunctionTypeInfo(); 3949 if (!FTI.Params) 3950 return; 3951 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 3952 FTI.NumParams)) { 3953 auto *ParamDecl = cast<NamedDecl>(Param.Param); 3954 if (ParamDecl->getDeclName()) 3955 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 3956 } 3957 } 3958 3959 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 3960 return ActOnRequiresClause(ConstraintExpr); 3961 } 3962 3963 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) { 3964 if (ConstraintExpr.isInvalid()) 3965 return ExprError(); 3966 3967 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr); 3968 if (ConstraintExpr.isInvalid()) 3969 return ExprError(); 3970 3971 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(), 3972 UPPC_RequiresClause)) 3973 return ExprError(); 3974 3975 return ConstraintExpr; 3976 } 3977 3978 /// This is invoked after parsing an in-class initializer for a 3979 /// non-static C++ class member, and after instantiating an in-class initializer 3980 /// in a class template. Such actions are deferred until the class is complete. 3981 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3982 SourceLocation InitLoc, 3983 Expr *InitExpr) { 3984 // Pop the notional constructor scope we created earlier. 3985 PopFunctionScopeInfo(nullptr, D); 3986 3987 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3988 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3989 "must set init style when field is created"); 3990 3991 if (!InitExpr) { 3992 D->setInvalidDecl(); 3993 if (FD) 3994 FD->removeInClassInitializer(); 3995 return; 3996 } 3997 3998 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3999 FD->setInvalidDecl(); 4000 FD->removeInClassInitializer(); 4001 return; 4002 } 4003 4004 ExprResult Init = InitExpr; 4005 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 4006 InitializedEntity Entity = 4007 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 4008 InitializationKind Kind = 4009 FD->getInClassInitStyle() == ICIS_ListInit 4010 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 4011 InitExpr->getBeginLoc(), 4012 InitExpr->getEndLoc()) 4013 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 4014 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 4015 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 4016 if (Init.isInvalid()) { 4017 FD->setInvalidDecl(); 4018 return; 4019 } 4020 } 4021 4022 // C++11 [class.base.init]p7: 4023 // The initialization of each base and member constitutes a 4024 // full-expression. 4025 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 4026 if (Init.isInvalid()) { 4027 FD->setInvalidDecl(); 4028 return; 4029 } 4030 4031 InitExpr = Init.get(); 4032 4033 FD->setInClassInitializer(InitExpr); 4034 } 4035 4036 /// Find the direct and/or virtual base specifiers that 4037 /// correspond to the given base type, for use in base initialization 4038 /// within a constructor. 4039 static bool FindBaseInitializer(Sema &SemaRef, 4040 CXXRecordDecl *ClassDecl, 4041 QualType BaseType, 4042 const CXXBaseSpecifier *&DirectBaseSpec, 4043 const CXXBaseSpecifier *&VirtualBaseSpec) { 4044 // First, check for a direct base class. 4045 DirectBaseSpec = nullptr; 4046 for (const auto &Base : ClassDecl->bases()) { 4047 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 4048 // We found a direct base of this type. That's what we're 4049 // initializing. 4050 DirectBaseSpec = &Base; 4051 break; 4052 } 4053 } 4054 4055 // Check for a virtual base class. 4056 // FIXME: We might be able to short-circuit this if we know in advance that 4057 // there are no virtual bases. 4058 VirtualBaseSpec = nullptr; 4059 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 4060 // We haven't found a base yet; search the class hierarchy for a 4061 // virtual base class. 4062 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 4063 /*DetectVirtual=*/false); 4064 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 4065 SemaRef.Context.getTypeDeclType(ClassDecl), 4066 BaseType, Paths)) { 4067 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 4068 Path != Paths.end(); ++Path) { 4069 if (Path->back().Base->isVirtual()) { 4070 VirtualBaseSpec = Path->back().Base; 4071 break; 4072 } 4073 } 4074 } 4075 } 4076 4077 return DirectBaseSpec || VirtualBaseSpec; 4078 } 4079 4080 /// Handle a C++ member initializer using braced-init-list syntax. 4081 MemInitResult 4082 Sema::ActOnMemInitializer(Decl *ConstructorD, 4083 Scope *S, 4084 CXXScopeSpec &SS, 4085 IdentifierInfo *MemberOrBase, 4086 ParsedType TemplateTypeTy, 4087 const DeclSpec &DS, 4088 SourceLocation IdLoc, 4089 Expr *InitList, 4090 SourceLocation EllipsisLoc) { 4091 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4092 DS, IdLoc, InitList, 4093 EllipsisLoc); 4094 } 4095 4096 /// Handle a C++ member initializer using parentheses syntax. 4097 MemInitResult 4098 Sema::ActOnMemInitializer(Decl *ConstructorD, 4099 Scope *S, 4100 CXXScopeSpec &SS, 4101 IdentifierInfo *MemberOrBase, 4102 ParsedType TemplateTypeTy, 4103 const DeclSpec &DS, 4104 SourceLocation IdLoc, 4105 SourceLocation LParenLoc, 4106 ArrayRef<Expr *> Args, 4107 SourceLocation RParenLoc, 4108 SourceLocation EllipsisLoc) { 4109 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4110 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4111 DS, IdLoc, List, EllipsisLoc); 4112 } 4113 4114 namespace { 4115 4116 // Callback to only accept typo corrections that can be a valid C++ member 4117 // initializer: either a non-static field member or a base class. 4118 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4119 public: 4120 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4121 : ClassDecl(ClassDecl) {} 4122 4123 bool ValidateCandidate(const TypoCorrection &candidate) override { 4124 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4125 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4126 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4127 return isa<TypeDecl>(ND); 4128 } 4129 return false; 4130 } 4131 4132 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4133 return std::make_unique<MemInitializerValidatorCCC>(*this); 4134 } 4135 4136 private: 4137 CXXRecordDecl *ClassDecl; 4138 }; 4139 4140 } 4141 4142 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4143 CXXScopeSpec &SS, 4144 ParsedType TemplateTypeTy, 4145 IdentifierInfo *MemberOrBase) { 4146 if (SS.getScopeRep() || TemplateTypeTy) 4147 return nullptr; 4148 for (auto *D : ClassDecl->lookup(MemberOrBase)) 4149 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) 4150 return cast<ValueDecl>(D); 4151 return nullptr; 4152 } 4153 4154 /// Handle a C++ member initializer. 4155 MemInitResult 4156 Sema::BuildMemInitializer(Decl *ConstructorD, 4157 Scope *S, 4158 CXXScopeSpec &SS, 4159 IdentifierInfo *MemberOrBase, 4160 ParsedType TemplateTypeTy, 4161 const DeclSpec &DS, 4162 SourceLocation IdLoc, 4163 Expr *Init, 4164 SourceLocation EllipsisLoc) { 4165 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr, 4166 /*RecoverUncorrectedTypos=*/true); 4167 if (!Res.isUsable()) 4168 return true; 4169 Init = Res.get(); 4170 4171 if (!ConstructorD) 4172 return true; 4173 4174 AdjustDeclIfTemplate(ConstructorD); 4175 4176 CXXConstructorDecl *Constructor 4177 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4178 if (!Constructor) { 4179 // The user wrote a constructor initializer on a function that is 4180 // not a C++ constructor. Ignore the error for now, because we may 4181 // have more member initializers coming; we'll diagnose it just 4182 // once in ActOnMemInitializers. 4183 return true; 4184 } 4185 4186 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4187 4188 // C++ [class.base.init]p2: 4189 // Names in a mem-initializer-id are looked up in the scope of the 4190 // constructor's class and, if not found in that scope, are looked 4191 // up in the scope containing the constructor's definition. 4192 // [Note: if the constructor's class contains a member with the 4193 // same name as a direct or virtual base class of the class, a 4194 // mem-initializer-id naming the member or base class and composed 4195 // of a single identifier refers to the class member. A 4196 // mem-initializer-id for the hidden base class may be specified 4197 // using a qualified name. ] 4198 4199 // Look for a member, first. 4200 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4201 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4202 if (EllipsisLoc.isValid()) 4203 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4204 << MemberOrBase 4205 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4206 4207 return BuildMemberInitializer(Member, Init, IdLoc); 4208 } 4209 // It didn't name a member, so see if it names a class. 4210 QualType BaseType; 4211 TypeSourceInfo *TInfo = nullptr; 4212 4213 if (TemplateTypeTy) { 4214 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4215 if (BaseType.isNull()) 4216 return true; 4217 } else if (DS.getTypeSpecType() == TST_decltype) { 4218 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4219 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4220 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4221 return true; 4222 } else { 4223 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4224 LookupParsedName(R, S, &SS); 4225 4226 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4227 if (!TyD) { 4228 if (R.isAmbiguous()) return true; 4229 4230 // We don't want access-control diagnostics here. 4231 R.suppressDiagnostics(); 4232 4233 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4234 bool NotUnknownSpecialization = false; 4235 DeclContext *DC = computeDeclContext(SS, false); 4236 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4237 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4238 4239 if (!NotUnknownSpecialization) { 4240 // When the scope specifier can refer to a member of an unknown 4241 // specialization, we take it as a type name. 4242 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4243 SS.getWithLocInContext(Context), 4244 *MemberOrBase, IdLoc); 4245 if (BaseType.isNull()) 4246 return true; 4247 4248 TInfo = Context.CreateTypeSourceInfo(BaseType); 4249 DependentNameTypeLoc TL = 4250 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4251 if (!TL.isNull()) { 4252 TL.setNameLoc(IdLoc); 4253 TL.setElaboratedKeywordLoc(SourceLocation()); 4254 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4255 } 4256 4257 R.clear(); 4258 R.setLookupName(MemberOrBase); 4259 } 4260 } 4261 4262 // If no results were found, try to correct typos. 4263 TypoCorrection Corr; 4264 MemInitializerValidatorCCC CCC(ClassDecl); 4265 if (R.empty() && BaseType.isNull() && 4266 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4267 CCC, CTK_ErrorRecovery, ClassDecl))) { 4268 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4269 // We have found a non-static data member with a similar 4270 // name to what was typed; complain and initialize that 4271 // member. 4272 diagnoseTypo(Corr, 4273 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4274 << MemberOrBase << true); 4275 return BuildMemberInitializer(Member, Init, IdLoc); 4276 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4277 const CXXBaseSpecifier *DirectBaseSpec; 4278 const CXXBaseSpecifier *VirtualBaseSpec; 4279 if (FindBaseInitializer(*this, ClassDecl, 4280 Context.getTypeDeclType(Type), 4281 DirectBaseSpec, VirtualBaseSpec)) { 4282 // We have found a direct or virtual base class with a 4283 // similar name to what was typed; complain and initialize 4284 // that base class. 4285 diagnoseTypo(Corr, 4286 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4287 << MemberOrBase << false, 4288 PDiag() /*Suppress note, we provide our own.*/); 4289 4290 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4291 : VirtualBaseSpec; 4292 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4293 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4294 4295 TyD = Type; 4296 } 4297 } 4298 } 4299 4300 if (!TyD && BaseType.isNull()) { 4301 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4302 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4303 return true; 4304 } 4305 } 4306 4307 if (BaseType.isNull()) { 4308 BaseType = Context.getTypeDeclType(TyD); 4309 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4310 if (SS.isSet()) { 4311 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4312 BaseType); 4313 TInfo = Context.CreateTypeSourceInfo(BaseType); 4314 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4315 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4316 TL.setElaboratedKeywordLoc(SourceLocation()); 4317 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4318 } 4319 } 4320 } 4321 4322 if (!TInfo) 4323 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4324 4325 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4326 } 4327 4328 MemInitResult 4329 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4330 SourceLocation IdLoc) { 4331 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4332 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4333 assert((DirectMember || IndirectMember) && 4334 "Member must be a FieldDecl or IndirectFieldDecl"); 4335 4336 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4337 return true; 4338 4339 if (Member->isInvalidDecl()) 4340 return true; 4341 4342 MultiExprArg Args; 4343 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4344 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4345 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4346 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4347 } else { 4348 // Template instantiation doesn't reconstruct ParenListExprs for us. 4349 Args = Init; 4350 } 4351 4352 SourceRange InitRange = Init->getSourceRange(); 4353 4354 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4355 // Can't check initialization for a member of dependent type or when 4356 // any of the arguments are type-dependent expressions. 4357 DiscardCleanupsInEvaluationContext(); 4358 } else { 4359 bool InitList = false; 4360 if (isa<InitListExpr>(Init)) { 4361 InitList = true; 4362 Args = Init; 4363 } 4364 4365 // Initialize the member. 4366 InitializedEntity MemberEntity = 4367 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4368 : InitializedEntity::InitializeMember(IndirectMember, 4369 nullptr); 4370 InitializationKind Kind = 4371 InitList ? InitializationKind::CreateDirectList( 4372 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4373 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4374 InitRange.getEnd()); 4375 4376 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4377 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4378 nullptr); 4379 if (!MemberInit.isInvalid()) { 4380 // C++11 [class.base.init]p7: 4381 // The initialization of each base and member constitutes a 4382 // full-expression. 4383 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4384 /*DiscardedValue*/ false); 4385 } 4386 4387 if (MemberInit.isInvalid()) { 4388 // Args were sensible expressions but we couldn't initialize the member 4389 // from them. Preserve them in a RecoveryExpr instead. 4390 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, 4391 Member->getType()) 4392 .get(); 4393 if (!Init) 4394 return true; 4395 } else { 4396 Init = MemberInit.get(); 4397 } 4398 } 4399 4400 if (DirectMember) { 4401 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4402 InitRange.getBegin(), Init, 4403 InitRange.getEnd()); 4404 } else { 4405 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4406 InitRange.getBegin(), Init, 4407 InitRange.getEnd()); 4408 } 4409 } 4410 4411 MemInitResult 4412 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4413 CXXRecordDecl *ClassDecl) { 4414 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4415 if (!LangOpts.CPlusPlus11) 4416 return Diag(NameLoc, diag::err_delegating_ctor) 4417 << TInfo->getTypeLoc().getLocalSourceRange(); 4418 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4419 4420 bool InitList = true; 4421 MultiExprArg Args = Init; 4422 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4423 InitList = false; 4424 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4425 } 4426 4427 SourceRange InitRange = Init->getSourceRange(); 4428 // Initialize the object. 4429 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4430 QualType(ClassDecl->getTypeForDecl(), 0)); 4431 InitializationKind Kind = 4432 InitList ? InitializationKind::CreateDirectList( 4433 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4434 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4435 InitRange.getEnd()); 4436 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4437 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4438 Args, nullptr); 4439 if (!DelegationInit.isInvalid()) { 4440 assert((DelegationInit.get()->containsErrors() || 4441 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) && 4442 "Delegating constructor with no target?"); 4443 4444 // C++11 [class.base.init]p7: 4445 // The initialization of each base and member constitutes a 4446 // full-expression. 4447 DelegationInit = ActOnFinishFullExpr( 4448 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4449 } 4450 4451 if (DelegationInit.isInvalid()) { 4452 DelegationInit = 4453 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, 4454 QualType(ClassDecl->getTypeForDecl(), 0)); 4455 if (DelegationInit.isInvalid()) 4456 return true; 4457 } else { 4458 // If we are in a dependent context, template instantiation will 4459 // perform this type-checking again. Just save the arguments that we 4460 // received in a ParenListExpr. 4461 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4462 // of the information that we have about the base 4463 // initializer. However, deconstructing the ASTs is a dicey process, 4464 // and this approach is far more likely to get the corner cases right. 4465 if (CurContext->isDependentContext()) 4466 DelegationInit = Init; 4467 } 4468 4469 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4470 DelegationInit.getAs<Expr>(), 4471 InitRange.getEnd()); 4472 } 4473 4474 MemInitResult 4475 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4476 Expr *Init, CXXRecordDecl *ClassDecl, 4477 SourceLocation EllipsisLoc) { 4478 SourceLocation BaseLoc 4479 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4480 4481 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4482 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4483 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4484 4485 // C++ [class.base.init]p2: 4486 // [...] Unless the mem-initializer-id names a nonstatic data 4487 // member of the constructor's class or a direct or virtual base 4488 // of that class, the mem-initializer is ill-formed. A 4489 // mem-initializer-list can initialize a base class using any 4490 // name that denotes that base class type. 4491 4492 // We can store the initializers in "as-written" form and delay analysis until 4493 // instantiation if the constructor is dependent. But not for dependent 4494 // (broken) code in a non-template! SetCtorInitializers does not expect this. 4495 bool Dependent = CurContext->isDependentContext() && 4496 (BaseType->isDependentType() || Init->isTypeDependent()); 4497 4498 SourceRange InitRange = Init->getSourceRange(); 4499 if (EllipsisLoc.isValid()) { 4500 // This is a pack expansion. 4501 if (!BaseType->containsUnexpandedParameterPack()) { 4502 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4503 << SourceRange(BaseLoc, InitRange.getEnd()); 4504 4505 EllipsisLoc = SourceLocation(); 4506 } 4507 } else { 4508 // Check for any unexpanded parameter packs. 4509 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4510 return true; 4511 4512 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4513 return true; 4514 } 4515 4516 // Check for direct and virtual base classes. 4517 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4518 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4519 if (!Dependent) { 4520 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4521 BaseType)) 4522 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4523 4524 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4525 VirtualBaseSpec); 4526 4527 // C++ [base.class.init]p2: 4528 // Unless the mem-initializer-id names a nonstatic data member of the 4529 // constructor's class or a direct or virtual base of that class, the 4530 // mem-initializer is ill-formed. 4531 if (!DirectBaseSpec && !VirtualBaseSpec) { 4532 // If the class has any dependent bases, then it's possible that 4533 // one of those types will resolve to the same type as 4534 // BaseType. Therefore, just treat this as a dependent base 4535 // class initialization. FIXME: Should we try to check the 4536 // initialization anyway? It seems odd. 4537 if (ClassDecl->hasAnyDependentBases()) 4538 Dependent = true; 4539 else 4540 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4541 << BaseType << Context.getTypeDeclType(ClassDecl) 4542 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4543 } 4544 } 4545 4546 if (Dependent) { 4547 DiscardCleanupsInEvaluationContext(); 4548 4549 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4550 /*IsVirtual=*/false, 4551 InitRange.getBegin(), Init, 4552 InitRange.getEnd(), EllipsisLoc); 4553 } 4554 4555 // C++ [base.class.init]p2: 4556 // If a mem-initializer-id is ambiguous because it designates both 4557 // a direct non-virtual base class and an inherited virtual base 4558 // class, the mem-initializer is ill-formed. 4559 if (DirectBaseSpec && VirtualBaseSpec) 4560 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4561 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4562 4563 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4564 if (!BaseSpec) 4565 BaseSpec = VirtualBaseSpec; 4566 4567 // Initialize the base. 4568 bool InitList = true; 4569 MultiExprArg Args = Init; 4570 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4571 InitList = false; 4572 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4573 } 4574 4575 InitializedEntity BaseEntity = 4576 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4577 InitializationKind Kind = 4578 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4579 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4580 InitRange.getEnd()); 4581 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4582 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4583 if (!BaseInit.isInvalid()) { 4584 // C++11 [class.base.init]p7: 4585 // The initialization of each base and member constitutes a 4586 // full-expression. 4587 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4588 /*DiscardedValue*/ false); 4589 } 4590 4591 if (BaseInit.isInvalid()) { 4592 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), 4593 Args, BaseType); 4594 if (BaseInit.isInvalid()) 4595 return true; 4596 } else { 4597 // If we are in a dependent context, template instantiation will 4598 // perform this type-checking again. Just save the arguments that we 4599 // received in a ParenListExpr. 4600 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4601 // of the information that we have about the base 4602 // initializer. However, deconstructing the ASTs is a dicey process, 4603 // and this approach is far more likely to get the corner cases right. 4604 if (CurContext->isDependentContext()) 4605 BaseInit = Init; 4606 } 4607 4608 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4609 BaseSpec->isVirtual(), 4610 InitRange.getBegin(), 4611 BaseInit.getAs<Expr>(), 4612 InitRange.getEnd(), EllipsisLoc); 4613 } 4614 4615 // Create a static_cast\<T&&>(expr). 4616 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4617 if (T.isNull()) T = E->getType(); 4618 QualType TargetType = SemaRef.BuildReferenceType( 4619 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4620 SourceLocation ExprLoc = E->getBeginLoc(); 4621 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4622 TargetType, ExprLoc); 4623 4624 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4625 SourceRange(ExprLoc, ExprLoc), 4626 E->getSourceRange()).get(); 4627 } 4628 4629 /// ImplicitInitializerKind - How an implicit base or member initializer should 4630 /// initialize its base or member. 4631 enum ImplicitInitializerKind { 4632 IIK_Default, 4633 IIK_Copy, 4634 IIK_Move, 4635 IIK_Inherit 4636 }; 4637 4638 static bool 4639 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4640 ImplicitInitializerKind ImplicitInitKind, 4641 CXXBaseSpecifier *BaseSpec, 4642 bool IsInheritedVirtualBase, 4643 CXXCtorInitializer *&CXXBaseInit) { 4644 InitializedEntity InitEntity 4645 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4646 IsInheritedVirtualBase); 4647 4648 ExprResult BaseInit; 4649 4650 switch (ImplicitInitKind) { 4651 case IIK_Inherit: 4652 case IIK_Default: { 4653 InitializationKind InitKind 4654 = InitializationKind::CreateDefault(Constructor->getLocation()); 4655 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4656 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4657 break; 4658 } 4659 4660 case IIK_Move: 4661 case IIK_Copy: { 4662 bool Moving = ImplicitInitKind == IIK_Move; 4663 ParmVarDecl *Param = Constructor->getParamDecl(0); 4664 QualType ParamType = Param->getType().getNonReferenceType(); 4665 4666 Expr *CopyCtorArg = 4667 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4668 SourceLocation(), Param, false, 4669 Constructor->getLocation(), ParamType, 4670 VK_LValue, nullptr); 4671 4672 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4673 4674 // Cast to the base class to avoid ambiguities. 4675 QualType ArgTy = 4676 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4677 ParamType.getQualifiers()); 4678 4679 if (Moving) { 4680 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4681 } 4682 4683 CXXCastPath BasePath; 4684 BasePath.push_back(BaseSpec); 4685 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4686 CK_UncheckedDerivedToBase, 4687 Moving ? VK_XValue : VK_LValue, 4688 &BasePath).get(); 4689 4690 InitializationKind InitKind 4691 = InitializationKind::CreateDirect(Constructor->getLocation(), 4692 SourceLocation(), SourceLocation()); 4693 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4694 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4695 break; 4696 } 4697 } 4698 4699 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4700 if (BaseInit.isInvalid()) 4701 return true; 4702 4703 CXXBaseInit = 4704 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4705 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4706 SourceLocation()), 4707 BaseSpec->isVirtual(), 4708 SourceLocation(), 4709 BaseInit.getAs<Expr>(), 4710 SourceLocation(), 4711 SourceLocation()); 4712 4713 return false; 4714 } 4715 4716 static bool RefersToRValueRef(Expr *MemRef) { 4717 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4718 return Referenced->getType()->isRValueReferenceType(); 4719 } 4720 4721 static bool 4722 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4723 ImplicitInitializerKind ImplicitInitKind, 4724 FieldDecl *Field, IndirectFieldDecl *Indirect, 4725 CXXCtorInitializer *&CXXMemberInit) { 4726 if (Field->isInvalidDecl()) 4727 return true; 4728 4729 SourceLocation Loc = Constructor->getLocation(); 4730 4731 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4732 bool Moving = ImplicitInitKind == IIK_Move; 4733 ParmVarDecl *Param = Constructor->getParamDecl(0); 4734 QualType ParamType = Param->getType().getNonReferenceType(); 4735 4736 // Suppress copying zero-width bitfields. 4737 if (Field->isZeroLengthBitField(SemaRef.Context)) 4738 return false; 4739 4740 Expr *MemberExprBase = 4741 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4742 SourceLocation(), Param, false, 4743 Loc, ParamType, VK_LValue, nullptr); 4744 4745 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4746 4747 if (Moving) { 4748 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4749 } 4750 4751 // Build a reference to this field within the parameter. 4752 CXXScopeSpec SS; 4753 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4754 Sema::LookupMemberName); 4755 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4756 : cast<ValueDecl>(Field), AS_public); 4757 MemberLookup.resolveKind(); 4758 ExprResult CtorArg 4759 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4760 ParamType, Loc, 4761 /*IsArrow=*/false, 4762 SS, 4763 /*TemplateKWLoc=*/SourceLocation(), 4764 /*FirstQualifierInScope=*/nullptr, 4765 MemberLookup, 4766 /*TemplateArgs=*/nullptr, 4767 /*S*/nullptr); 4768 if (CtorArg.isInvalid()) 4769 return true; 4770 4771 // C++11 [class.copy]p15: 4772 // - if a member m has rvalue reference type T&&, it is direct-initialized 4773 // with static_cast<T&&>(x.m); 4774 if (RefersToRValueRef(CtorArg.get())) { 4775 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4776 } 4777 4778 InitializedEntity Entity = 4779 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4780 /*Implicit*/ true) 4781 : InitializedEntity::InitializeMember(Field, nullptr, 4782 /*Implicit*/ true); 4783 4784 // Direct-initialize to use the copy constructor. 4785 InitializationKind InitKind = 4786 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4787 4788 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4789 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4790 ExprResult MemberInit = 4791 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4792 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4793 if (MemberInit.isInvalid()) 4794 return true; 4795 4796 if (Indirect) 4797 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4798 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4799 else 4800 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4801 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4802 return false; 4803 } 4804 4805 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4806 "Unhandled implicit init kind!"); 4807 4808 QualType FieldBaseElementType = 4809 SemaRef.Context.getBaseElementType(Field->getType()); 4810 4811 if (FieldBaseElementType->isRecordType()) { 4812 InitializedEntity InitEntity = 4813 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4814 /*Implicit*/ true) 4815 : InitializedEntity::InitializeMember(Field, nullptr, 4816 /*Implicit*/ true); 4817 InitializationKind InitKind = 4818 InitializationKind::CreateDefault(Loc); 4819 4820 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4821 ExprResult MemberInit = 4822 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4823 4824 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4825 if (MemberInit.isInvalid()) 4826 return true; 4827 4828 if (Indirect) 4829 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4830 Indirect, Loc, 4831 Loc, 4832 MemberInit.get(), 4833 Loc); 4834 else 4835 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4836 Field, Loc, Loc, 4837 MemberInit.get(), 4838 Loc); 4839 return false; 4840 } 4841 4842 if (!Field->getParent()->isUnion()) { 4843 if (FieldBaseElementType->isReferenceType()) { 4844 SemaRef.Diag(Constructor->getLocation(), 4845 diag::err_uninitialized_member_in_ctor) 4846 << (int)Constructor->isImplicit() 4847 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4848 << 0 << Field->getDeclName(); 4849 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4850 return true; 4851 } 4852 4853 if (FieldBaseElementType.isConstQualified()) { 4854 SemaRef.Diag(Constructor->getLocation(), 4855 diag::err_uninitialized_member_in_ctor) 4856 << (int)Constructor->isImplicit() 4857 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4858 << 1 << Field->getDeclName(); 4859 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4860 return true; 4861 } 4862 } 4863 4864 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4865 // ARC and Weak: 4866 // Default-initialize Objective-C pointers to NULL. 4867 CXXMemberInit 4868 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4869 Loc, Loc, 4870 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4871 Loc); 4872 return false; 4873 } 4874 4875 // Nothing to initialize. 4876 CXXMemberInit = nullptr; 4877 return false; 4878 } 4879 4880 namespace { 4881 struct BaseAndFieldInfo { 4882 Sema &S; 4883 CXXConstructorDecl *Ctor; 4884 bool AnyErrorsInInits; 4885 ImplicitInitializerKind IIK; 4886 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4887 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4888 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4889 4890 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4891 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4892 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4893 if (Ctor->getInheritedConstructor()) 4894 IIK = IIK_Inherit; 4895 else if (Generated && Ctor->isCopyConstructor()) 4896 IIK = IIK_Copy; 4897 else if (Generated && Ctor->isMoveConstructor()) 4898 IIK = IIK_Move; 4899 else 4900 IIK = IIK_Default; 4901 } 4902 4903 bool isImplicitCopyOrMove() const { 4904 switch (IIK) { 4905 case IIK_Copy: 4906 case IIK_Move: 4907 return true; 4908 4909 case IIK_Default: 4910 case IIK_Inherit: 4911 return false; 4912 } 4913 4914 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4915 } 4916 4917 bool addFieldInitializer(CXXCtorInitializer *Init) { 4918 AllToInit.push_back(Init); 4919 4920 // Check whether this initializer makes the field "used". 4921 if (Init->getInit()->HasSideEffects(S.Context)) 4922 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4923 4924 return false; 4925 } 4926 4927 bool isInactiveUnionMember(FieldDecl *Field) { 4928 RecordDecl *Record = Field->getParent(); 4929 if (!Record->isUnion()) 4930 return false; 4931 4932 if (FieldDecl *Active = 4933 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4934 return Active != Field->getCanonicalDecl(); 4935 4936 // In an implicit copy or move constructor, ignore any in-class initializer. 4937 if (isImplicitCopyOrMove()) 4938 return true; 4939 4940 // If there's no explicit initialization, the field is active only if it 4941 // has an in-class initializer... 4942 if (Field->hasInClassInitializer()) 4943 return false; 4944 // ... or it's an anonymous struct or union whose class has an in-class 4945 // initializer. 4946 if (!Field->isAnonymousStructOrUnion()) 4947 return true; 4948 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4949 return !FieldRD->hasInClassInitializer(); 4950 } 4951 4952 /// Determine whether the given field is, or is within, a union member 4953 /// that is inactive (because there was an initializer given for a different 4954 /// member of the union, or because the union was not initialized at all). 4955 bool isWithinInactiveUnionMember(FieldDecl *Field, 4956 IndirectFieldDecl *Indirect) { 4957 if (!Indirect) 4958 return isInactiveUnionMember(Field); 4959 4960 for (auto *C : Indirect->chain()) { 4961 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4962 if (Field && isInactiveUnionMember(Field)) 4963 return true; 4964 } 4965 return false; 4966 } 4967 }; 4968 } 4969 4970 /// Determine whether the given type is an incomplete or zero-lenfgth 4971 /// array type. 4972 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4973 if (T->isIncompleteArrayType()) 4974 return true; 4975 4976 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4977 if (!ArrayT->getSize()) 4978 return true; 4979 4980 T = ArrayT->getElementType(); 4981 } 4982 4983 return false; 4984 } 4985 4986 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4987 FieldDecl *Field, 4988 IndirectFieldDecl *Indirect = nullptr) { 4989 if (Field->isInvalidDecl()) 4990 return false; 4991 4992 // Overwhelmingly common case: we have a direct initializer for this field. 4993 if (CXXCtorInitializer *Init = 4994 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4995 return Info.addFieldInitializer(Init); 4996 4997 // C++11 [class.base.init]p8: 4998 // if the entity is a non-static data member that has a 4999 // brace-or-equal-initializer and either 5000 // -- the constructor's class is a union and no other variant member of that 5001 // union is designated by a mem-initializer-id or 5002 // -- the constructor's class is not a union, and, if the entity is a member 5003 // of an anonymous union, no other member of that union is designated by 5004 // a mem-initializer-id, 5005 // the entity is initialized as specified in [dcl.init]. 5006 // 5007 // We also apply the same rules to handle anonymous structs within anonymous 5008 // unions. 5009 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 5010 return false; 5011 5012 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 5013 ExprResult DIE = 5014 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 5015 if (DIE.isInvalid()) 5016 return true; 5017 5018 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 5019 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 5020 5021 CXXCtorInitializer *Init; 5022 if (Indirect) 5023 Init = new (SemaRef.Context) 5024 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 5025 SourceLocation(), DIE.get(), SourceLocation()); 5026 else 5027 Init = new (SemaRef.Context) 5028 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 5029 SourceLocation(), DIE.get(), SourceLocation()); 5030 return Info.addFieldInitializer(Init); 5031 } 5032 5033 // Don't initialize incomplete or zero-length arrays. 5034 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 5035 return false; 5036 5037 // Don't try to build an implicit initializer if there were semantic 5038 // errors in any of the initializers (and therefore we might be 5039 // missing some that the user actually wrote). 5040 if (Info.AnyErrorsInInits) 5041 return false; 5042 5043 CXXCtorInitializer *Init = nullptr; 5044 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 5045 Indirect, Init)) 5046 return true; 5047 5048 if (!Init) 5049 return false; 5050 5051 return Info.addFieldInitializer(Init); 5052 } 5053 5054 bool 5055 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 5056 CXXCtorInitializer *Initializer) { 5057 assert(Initializer->isDelegatingInitializer()); 5058 Constructor->setNumCtorInitializers(1); 5059 CXXCtorInitializer **initializer = 5060 new (Context) CXXCtorInitializer*[1]; 5061 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 5062 Constructor->setCtorInitializers(initializer); 5063 5064 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 5065 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 5066 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 5067 } 5068 5069 DelegatingCtorDecls.push_back(Constructor); 5070 5071 DiagnoseUninitializedFields(*this, Constructor); 5072 5073 return false; 5074 } 5075 5076 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 5077 ArrayRef<CXXCtorInitializer *> Initializers) { 5078 if (Constructor->isDependentContext()) { 5079 // Just store the initializers as written, they will be checked during 5080 // instantiation. 5081 if (!Initializers.empty()) { 5082 Constructor->setNumCtorInitializers(Initializers.size()); 5083 CXXCtorInitializer **baseOrMemberInitializers = 5084 new (Context) CXXCtorInitializer*[Initializers.size()]; 5085 memcpy(baseOrMemberInitializers, Initializers.data(), 5086 Initializers.size() * sizeof(CXXCtorInitializer*)); 5087 Constructor->setCtorInitializers(baseOrMemberInitializers); 5088 } 5089 5090 // Let template instantiation know whether we had errors. 5091 if (AnyErrors) 5092 Constructor->setInvalidDecl(); 5093 5094 return false; 5095 } 5096 5097 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 5098 5099 // We need to build the initializer AST according to order of construction 5100 // and not what user specified in the Initializers list. 5101 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 5102 if (!ClassDecl) 5103 return true; 5104 5105 bool HadError = false; 5106 5107 for (unsigned i = 0; i < Initializers.size(); i++) { 5108 CXXCtorInitializer *Member = Initializers[i]; 5109 5110 if (Member->isBaseInitializer()) 5111 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5112 else { 5113 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5114 5115 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5116 for (auto *C : F->chain()) { 5117 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5118 if (FD && FD->getParent()->isUnion()) 5119 Info.ActiveUnionMember.insert(std::make_pair( 5120 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5121 } 5122 } else if (FieldDecl *FD = Member->getMember()) { 5123 if (FD->getParent()->isUnion()) 5124 Info.ActiveUnionMember.insert(std::make_pair( 5125 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5126 } 5127 } 5128 } 5129 5130 // Keep track of the direct virtual bases. 5131 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5132 for (auto &I : ClassDecl->bases()) { 5133 if (I.isVirtual()) 5134 DirectVBases.insert(&I); 5135 } 5136 5137 // Push virtual bases before others. 5138 for (auto &VBase : ClassDecl->vbases()) { 5139 if (CXXCtorInitializer *Value 5140 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5141 // [class.base.init]p7, per DR257: 5142 // A mem-initializer where the mem-initializer-id names a virtual base 5143 // class is ignored during execution of a constructor of any class that 5144 // is not the most derived class. 5145 if (ClassDecl->isAbstract()) { 5146 // FIXME: Provide a fixit to remove the base specifier. This requires 5147 // tracking the location of the associated comma for a base specifier. 5148 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5149 << VBase.getType() << ClassDecl; 5150 DiagnoseAbstractType(ClassDecl); 5151 } 5152 5153 Info.AllToInit.push_back(Value); 5154 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5155 // [class.base.init]p8, per DR257: 5156 // If a given [...] base class is not named by a mem-initializer-id 5157 // [...] and the entity is not a virtual base class of an abstract 5158 // class, then [...] the entity is default-initialized. 5159 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5160 CXXCtorInitializer *CXXBaseInit; 5161 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5162 &VBase, IsInheritedVirtualBase, 5163 CXXBaseInit)) { 5164 HadError = true; 5165 continue; 5166 } 5167 5168 Info.AllToInit.push_back(CXXBaseInit); 5169 } 5170 } 5171 5172 // Non-virtual bases. 5173 for (auto &Base : ClassDecl->bases()) { 5174 // Virtuals are in the virtual base list and already constructed. 5175 if (Base.isVirtual()) 5176 continue; 5177 5178 if (CXXCtorInitializer *Value 5179 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5180 Info.AllToInit.push_back(Value); 5181 } else if (!AnyErrors) { 5182 CXXCtorInitializer *CXXBaseInit; 5183 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5184 &Base, /*IsInheritedVirtualBase=*/false, 5185 CXXBaseInit)) { 5186 HadError = true; 5187 continue; 5188 } 5189 5190 Info.AllToInit.push_back(CXXBaseInit); 5191 } 5192 } 5193 5194 // Fields. 5195 for (auto *Mem : ClassDecl->decls()) { 5196 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5197 // C++ [class.bit]p2: 5198 // A declaration for a bit-field that omits the identifier declares an 5199 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5200 // initialized. 5201 if (F->isUnnamedBitfield()) 5202 continue; 5203 5204 // If we're not generating the implicit copy/move constructor, then we'll 5205 // handle anonymous struct/union fields based on their individual 5206 // indirect fields. 5207 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5208 continue; 5209 5210 if (CollectFieldInitializer(*this, Info, F)) 5211 HadError = true; 5212 continue; 5213 } 5214 5215 // Beyond this point, we only consider default initialization. 5216 if (Info.isImplicitCopyOrMove()) 5217 continue; 5218 5219 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5220 if (F->getType()->isIncompleteArrayType()) { 5221 assert(ClassDecl->hasFlexibleArrayMember() && 5222 "Incomplete array type is not valid"); 5223 continue; 5224 } 5225 5226 // Initialize each field of an anonymous struct individually. 5227 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5228 HadError = true; 5229 5230 continue; 5231 } 5232 } 5233 5234 unsigned NumInitializers = Info.AllToInit.size(); 5235 if (NumInitializers > 0) { 5236 Constructor->setNumCtorInitializers(NumInitializers); 5237 CXXCtorInitializer **baseOrMemberInitializers = 5238 new (Context) CXXCtorInitializer*[NumInitializers]; 5239 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5240 NumInitializers * sizeof(CXXCtorInitializer*)); 5241 Constructor->setCtorInitializers(baseOrMemberInitializers); 5242 5243 // Constructors implicitly reference the base and member 5244 // destructors. 5245 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5246 Constructor->getParent()); 5247 } 5248 5249 return HadError; 5250 } 5251 5252 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5253 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5254 const RecordDecl *RD = RT->getDecl(); 5255 if (RD->isAnonymousStructOrUnion()) { 5256 for (auto *Field : RD->fields()) 5257 PopulateKeysForFields(Field, IdealInits); 5258 return; 5259 } 5260 } 5261 IdealInits.push_back(Field->getCanonicalDecl()); 5262 } 5263 5264 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5265 return Context.getCanonicalType(BaseType).getTypePtr(); 5266 } 5267 5268 static const void *GetKeyForMember(ASTContext &Context, 5269 CXXCtorInitializer *Member) { 5270 if (!Member->isAnyMemberInitializer()) 5271 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5272 5273 return Member->getAnyMember()->getCanonicalDecl(); 5274 } 5275 5276 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, 5277 const CXXCtorInitializer *Previous, 5278 const CXXCtorInitializer *Current) { 5279 if (Previous->isAnyMemberInitializer()) 5280 Diag << 0 << Previous->getAnyMember(); 5281 else 5282 Diag << 1 << Previous->getTypeSourceInfo()->getType(); 5283 5284 if (Current->isAnyMemberInitializer()) 5285 Diag << 0 << Current->getAnyMember(); 5286 else 5287 Diag << 1 << Current->getTypeSourceInfo()->getType(); 5288 } 5289 5290 static void DiagnoseBaseOrMemInitializerOrder( 5291 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5292 ArrayRef<CXXCtorInitializer *> Inits) { 5293 if (Constructor->getDeclContext()->isDependentContext()) 5294 return; 5295 5296 // Don't check initializers order unless the warning is enabled at the 5297 // location of at least one initializer. 5298 bool ShouldCheckOrder = false; 5299 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5300 CXXCtorInitializer *Init = Inits[InitIndex]; 5301 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5302 Init->getSourceLocation())) { 5303 ShouldCheckOrder = true; 5304 break; 5305 } 5306 } 5307 if (!ShouldCheckOrder) 5308 return; 5309 5310 // Build the list of bases and members in the order that they'll 5311 // actually be initialized. The explicit initializers should be in 5312 // this same order but may be missing things. 5313 SmallVector<const void*, 32> IdealInitKeys; 5314 5315 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5316 5317 // 1. Virtual bases. 5318 for (const auto &VBase : ClassDecl->vbases()) 5319 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5320 5321 // 2. Non-virtual bases. 5322 for (const auto &Base : ClassDecl->bases()) { 5323 if (Base.isVirtual()) 5324 continue; 5325 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5326 } 5327 5328 // 3. Direct fields. 5329 for (auto *Field : ClassDecl->fields()) { 5330 if (Field->isUnnamedBitfield()) 5331 continue; 5332 5333 PopulateKeysForFields(Field, IdealInitKeys); 5334 } 5335 5336 unsigned NumIdealInits = IdealInitKeys.size(); 5337 unsigned IdealIndex = 0; 5338 5339 // Track initializers that are in an incorrect order for either a warning or 5340 // note if multiple ones occur. 5341 SmallVector<unsigned> WarnIndexes; 5342 // Correlates the index of an initializer in the init-list to the index of 5343 // the field/base in the class. 5344 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder; 5345 5346 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5347 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]); 5348 5349 // Scan forward to try to find this initializer in the idealized 5350 // initializers list. 5351 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5352 if (InitKey == IdealInitKeys[IdealIndex]) 5353 break; 5354 5355 // If we didn't find this initializer, it must be because we 5356 // scanned past it on a previous iteration. That can only 5357 // happen if we're out of order; emit a warning. 5358 if (IdealIndex == NumIdealInits && InitIndex) { 5359 WarnIndexes.push_back(InitIndex); 5360 5361 // Move back to the initializer's location in the ideal list. 5362 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5363 if (InitKey == IdealInitKeys[IdealIndex]) 5364 break; 5365 5366 assert(IdealIndex < NumIdealInits && 5367 "initializer not found in initializer list"); 5368 } 5369 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex); 5370 } 5371 5372 if (WarnIndexes.empty()) 5373 return; 5374 5375 // Sort based on the ideal order, first in the pair. 5376 llvm::sort(CorrelatedInitOrder, 5377 [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; }); 5378 5379 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to 5380 // emit the diagnostic before we can try adding notes. 5381 { 5382 Sema::SemaDiagnosticBuilder D = SemaRef.Diag( 5383 Inits[WarnIndexes.front() - 1]->getSourceLocation(), 5384 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order 5385 : diag::warn_some_initializers_out_of_order); 5386 5387 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) { 5388 if (CorrelatedInitOrder[I].second == I) 5389 continue; 5390 // Ideally we would be using InsertFromRange here, but clang doesn't 5391 // appear to handle InsertFromRange correctly when the source range is 5392 // modified by another fix-it. 5393 D << FixItHint::CreateReplacement( 5394 Inits[I]->getSourceRange(), 5395 Lexer::getSourceText( 5396 CharSourceRange::getTokenRange( 5397 Inits[CorrelatedInitOrder[I].second]->getSourceRange()), 5398 SemaRef.getSourceManager(), SemaRef.getLangOpts())); 5399 } 5400 5401 // If there is only 1 item out of order, the warning expects the name and 5402 // type of each being added to it. 5403 if (WarnIndexes.size() == 1) { 5404 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1], 5405 Inits[WarnIndexes.front()]); 5406 return; 5407 } 5408 } 5409 // More than 1 item to warn, create notes letting the user know which ones 5410 // are bad. 5411 for (unsigned WarnIndex : WarnIndexes) { 5412 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1]; 5413 auto D = SemaRef.Diag(PrevInit->getSourceLocation(), 5414 diag::note_initializer_out_of_order); 5415 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]); 5416 D << PrevInit->getSourceRange(); 5417 } 5418 } 5419 5420 namespace { 5421 bool CheckRedundantInit(Sema &S, 5422 CXXCtorInitializer *Init, 5423 CXXCtorInitializer *&PrevInit) { 5424 if (!PrevInit) { 5425 PrevInit = Init; 5426 return false; 5427 } 5428 5429 if (FieldDecl *Field = Init->getAnyMember()) 5430 S.Diag(Init->getSourceLocation(), 5431 diag::err_multiple_mem_initialization) 5432 << Field->getDeclName() 5433 << Init->getSourceRange(); 5434 else { 5435 const Type *BaseClass = Init->getBaseClass(); 5436 assert(BaseClass && "neither field nor base"); 5437 S.Diag(Init->getSourceLocation(), 5438 diag::err_multiple_base_initialization) 5439 << QualType(BaseClass, 0) 5440 << Init->getSourceRange(); 5441 } 5442 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5443 << 0 << PrevInit->getSourceRange(); 5444 5445 return true; 5446 } 5447 5448 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5449 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5450 5451 bool CheckRedundantUnionInit(Sema &S, 5452 CXXCtorInitializer *Init, 5453 RedundantUnionMap &Unions) { 5454 FieldDecl *Field = Init->getAnyMember(); 5455 RecordDecl *Parent = Field->getParent(); 5456 NamedDecl *Child = Field; 5457 5458 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5459 if (Parent->isUnion()) { 5460 UnionEntry &En = Unions[Parent]; 5461 if (En.first && En.first != Child) { 5462 S.Diag(Init->getSourceLocation(), 5463 diag::err_multiple_mem_union_initialization) 5464 << Field->getDeclName() 5465 << Init->getSourceRange(); 5466 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5467 << 0 << En.second->getSourceRange(); 5468 return true; 5469 } 5470 if (!En.first) { 5471 En.first = Child; 5472 En.second = Init; 5473 } 5474 if (!Parent->isAnonymousStructOrUnion()) 5475 return false; 5476 } 5477 5478 Child = Parent; 5479 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5480 } 5481 5482 return false; 5483 } 5484 } // namespace 5485 5486 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5487 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5488 SourceLocation ColonLoc, 5489 ArrayRef<CXXCtorInitializer*> MemInits, 5490 bool AnyErrors) { 5491 if (!ConstructorDecl) 5492 return; 5493 5494 AdjustDeclIfTemplate(ConstructorDecl); 5495 5496 CXXConstructorDecl *Constructor 5497 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5498 5499 if (!Constructor) { 5500 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5501 return; 5502 } 5503 5504 // Mapping for the duplicate initializers check. 5505 // For member initializers, this is keyed with a FieldDecl*. 5506 // For base initializers, this is keyed with a Type*. 5507 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5508 5509 // Mapping for the inconsistent anonymous-union initializers check. 5510 RedundantUnionMap MemberUnions; 5511 5512 bool HadError = false; 5513 for (unsigned i = 0; i < MemInits.size(); i++) { 5514 CXXCtorInitializer *Init = MemInits[i]; 5515 5516 // Set the source order index. 5517 Init->setSourceOrder(i); 5518 5519 if (Init->isAnyMemberInitializer()) { 5520 const void *Key = GetKeyForMember(Context, Init); 5521 if (CheckRedundantInit(*this, Init, Members[Key]) || 5522 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5523 HadError = true; 5524 } else if (Init->isBaseInitializer()) { 5525 const void *Key = GetKeyForMember(Context, Init); 5526 if (CheckRedundantInit(*this, Init, Members[Key])) 5527 HadError = true; 5528 } else { 5529 assert(Init->isDelegatingInitializer()); 5530 // This must be the only initializer 5531 if (MemInits.size() != 1) { 5532 Diag(Init->getSourceLocation(), 5533 diag::err_delegating_initializer_alone) 5534 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5535 // We will treat this as being the only initializer. 5536 } 5537 SetDelegatingInitializer(Constructor, MemInits[i]); 5538 // Return immediately as the initializer is set. 5539 return; 5540 } 5541 } 5542 5543 if (HadError) 5544 return; 5545 5546 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5547 5548 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5549 5550 DiagnoseUninitializedFields(*this, Constructor); 5551 } 5552 5553 void 5554 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5555 CXXRecordDecl *ClassDecl) { 5556 // Ignore dependent contexts. Also ignore unions, since their members never 5557 // have destructors implicitly called. 5558 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5559 return; 5560 5561 // FIXME: all the access-control diagnostics are positioned on the 5562 // field/base declaration. That's probably good; that said, the 5563 // user might reasonably want to know why the destructor is being 5564 // emitted, and we currently don't say. 5565 5566 // Non-static data members. 5567 for (auto *Field : ClassDecl->fields()) { 5568 if (Field->isInvalidDecl()) 5569 continue; 5570 5571 // Don't destroy incomplete or zero-length arrays. 5572 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5573 continue; 5574 5575 QualType FieldType = Context.getBaseElementType(Field->getType()); 5576 5577 const RecordType* RT = FieldType->getAs<RecordType>(); 5578 if (!RT) 5579 continue; 5580 5581 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5582 if (FieldClassDecl->isInvalidDecl()) 5583 continue; 5584 if (FieldClassDecl->hasIrrelevantDestructor()) 5585 continue; 5586 // The destructor for an implicit anonymous union member is never invoked. 5587 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5588 continue; 5589 5590 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5591 assert(Dtor && "No dtor found for FieldClassDecl!"); 5592 CheckDestructorAccess(Field->getLocation(), Dtor, 5593 PDiag(diag::err_access_dtor_field) 5594 << Field->getDeclName() 5595 << FieldType); 5596 5597 MarkFunctionReferenced(Location, Dtor); 5598 DiagnoseUseOfDecl(Dtor, Location); 5599 } 5600 5601 // We only potentially invoke the destructors of potentially constructed 5602 // subobjects. 5603 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5604 5605 // If the destructor exists and has already been marked used in the MS ABI, 5606 // then virtual base destructors have already been checked and marked used. 5607 // Skip checking them again to avoid duplicate diagnostics. 5608 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5609 CXXDestructorDecl *Dtor = ClassDecl->getDestructor(); 5610 if (Dtor && Dtor->isUsed()) 5611 VisitVirtualBases = false; 5612 } 5613 5614 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5615 5616 // Bases. 5617 for (const auto &Base : ClassDecl->bases()) { 5618 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5619 if (!RT) 5620 continue; 5621 5622 // Remember direct virtual bases. 5623 if (Base.isVirtual()) { 5624 if (!VisitVirtualBases) 5625 continue; 5626 DirectVirtualBases.insert(RT); 5627 } 5628 5629 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5630 // If our base class is invalid, we probably can't get its dtor anyway. 5631 if (BaseClassDecl->isInvalidDecl()) 5632 continue; 5633 if (BaseClassDecl->hasIrrelevantDestructor()) 5634 continue; 5635 5636 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5637 assert(Dtor && "No dtor found for BaseClassDecl!"); 5638 5639 // FIXME: caret should be on the start of the class name 5640 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5641 PDiag(diag::err_access_dtor_base) 5642 << Base.getType() << Base.getSourceRange(), 5643 Context.getTypeDeclType(ClassDecl)); 5644 5645 MarkFunctionReferenced(Location, Dtor); 5646 DiagnoseUseOfDecl(Dtor, Location); 5647 } 5648 5649 if (VisitVirtualBases) 5650 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl, 5651 &DirectVirtualBases); 5652 } 5653 5654 void Sema::MarkVirtualBaseDestructorsReferenced( 5655 SourceLocation Location, CXXRecordDecl *ClassDecl, 5656 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) { 5657 // Virtual bases. 5658 for (const auto &VBase : ClassDecl->vbases()) { 5659 // Bases are always records in a well-formed non-dependent class. 5660 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5661 5662 // Ignore already visited direct virtual bases. 5663 if (DirectVirtualBases && DirectVirtualBases->count(RT)) 5664 continue; 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 if (CheckDestructorAccess( 5676 ClassDecl->getLocation(), Dtor, 5677 PDiag(diag::err_access_dtor_vbase) 5678 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5679 Context.getTypeDeclType(ClassDecl)) == 5680 AR_accessible) { 5681 CheckDerivedToBaseConversion( 5682 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5683 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5684 SourceRange(), DeclarationName(), nullptr); 5685 } 5686 5687 MarkFunctionReferenced(Location, Dtor); 5688 DiagnoseUseOfDecl(Dtor, Location); 5689 } 5690 } 5691 5692 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5693 if (!CDtorDecl) 5694 return; 5695 5696 if (CXXConstructorDecl *Constructor 5697 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5698 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5699 DiagnoseUninitializedFields(*this, Constructor); 5700 } 5701 } 5702 5703 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5704 if (!getLangOpts().CPlusPlus) 5705 return false; 5706 5707 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5708 if (!RD) 5709 return false; 5710 5711 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5712 // class template specialization here, but doing so breaks a lot of code. 5713 5714 // We can't answer whether something is abstract until it has a 5715 // definition. If it's currently being defined, we'll walk back 5716 // over all the declarations when we have a full definition. 5717 const CXXRecordDecl *Def = RD->getDefinition(); 5718 if (!Def || Def->isBeingDefined()) 5719 return false; 5720 5721 return RD->isAbstract(); 5722 } 5723 5724 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5725 TypeDiagnoser &Diagnoser) { 5726 if (!isAbstractType(Loc, T)) 5727 return false; 5728 5729 T = Context.getBaseElementType(T); 5730 Diagnoser.diagnose(*this, Loc, T); 5731 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5732 return true; 5733 } 5734 5735 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5736 // Check if we've already emitted the list of pure virtual functions 5737 // for this class. 5738 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5739 return; 5740 5741 // If the diagnostic is suppressed, don't emit the notes. We're only 5742 // going to emit them once, so try to attach them to a diagnostic we're 5743 // actually going to show. 5744 if (Diags.isLastDiagnosticIgnored()) 5745 return; 5746 5747 CXXFinalOverriderMap FinalOverriders; 5748 RD->getFinalOverriders(FinalOverriders); 5749 5750 // Keep a set of seen pure methods so we won't diagnose the same method 5751 // more than once. 5752 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5753 5754 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5755 MEnd = FinalOverriders.end(); 5756 M != MEnd; 5757 ++M) { 5758 for (OverridingMethods::iterator SO = M->second.begin(), 5759 SOEnd = M->second.end(); 5760 SO != SOEnd; ++SO) { 5761 // C++ [class.abstract]p4: 5762 // A class is abstract if it contains or inherits at least one 5763 // pure virtual function for which the final overrider is pure 5764 // virtual. 5765 5766 // 5767 if (SO->second.size() != 1) 5768 continue; 5769 5770 if (!SO->second.front().Method->isPure()) 5771 continue; 5772 5773 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5774 continue; 5775 5776 Diag(SO->second.front().Method->getLocation(), 5777 diag::note_pure_virtual_function) 5778 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5779 } 5780 } 5781 5782 if (!PureVirtualClassDiagSet) 5783 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5784 PureVirtualClassDiagSet->insert(RD); 5785 } 5786 5787 namespace { 5788 struct AbstractUsageInfo { 5789 Sema &S; 5790 CXXRecordDecl *Record; 5791 CanQualType AbstractType; 5792 bool Invalid; 5793 5794 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5795 : S(S), Record(Record), 5796 AbstractType(S.Context.getCanonicalType( 5797 S.Context.getTypeDeclType(Record))), 5798 Invalid(false) {} 5799 5800 void DiagnoseAbstractType() { 5801 if (Invalid) return; 5802 S.DiagnoseAbstractType(Record); 5803 Invalid = true; 5804 } 5805 5806 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5807 }; 5808 5809 struct CheckAbstractUsage { 5810 AbstractUsageInfo &Info; 5811 const NamedDecl *Ctx; 5812 5813 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5814 : Info(Info), Ctx(Ctx) {} 5815 5816 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5817 switch (TL.getTypeLocClass()) { 5818 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5819 #define TYPELOC(CLASS, PARENT) \ 5820 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5821 #include "clang/AST/TypeLocNodes.def" 5822 } 5823 } 5824 5825 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5826 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5827 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5828 if (!TL.getParam(I)) 5829 continue; 5830 5831 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5832 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5833 } 5834 } 5835 5836 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5837 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5838 } 5839 5840 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5841 // Visit the type parameters from a permissive context. 5842 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5843 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5844 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5845 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5846 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5847 // TODO: other template argument types? 5848 } 5849 } 5850 5851 // Visit pointee types from a permissive context. 5852 #define CheckPolymorphic(Type) \ 5853 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5854 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5855 } 5856 CheckPolymorphic(PointerTypeLoc) 5857 CheckPolymorphic(ReferenceTypeLoc) 5858 CheckPolymorphic(MemberPointerTypeLoc) 5859 CheckPolymorphic(BlockPointerTypeLoc) 5860 CheckPolymorphic(AtomicTypeLoc) 5861 5862 /// Handle all the types we haven't given a more specific 5863 /// implementation for above. 5864 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5865 // Every other kind of type that we haven't called out already 5866 // that has an inner type is either (1) sugar or (2) contains that 5867 // inner type in some way as a subobject. 5868 if (TypeLoc Next = TL.getNextTypeLoc()) 5869 return Visit(Next, Sel); 5870 5871 // If there's no inner type and we're in a permissive context, 5872 // don't diagnose. 5873 if (Sel == Sema::AbstractNone) return; 5874 5875 // Check whether the type matches the abstract type. 5876 QualType T = TL.getType(); 5877 if (T->isArrayType()) { 5878 Sel = Sema::AbstractArrayType; 5879 T = Info.S.Context.getBaseElementType(T); 5880 } 5881 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5882 if (CT != Info.AbstractType) return; 5883 5884 // It matched; do some magic. 5885 if (Sel == Sema::AbstractArrayType) { 5886 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5887 << T << TL.getSourceRange(); 5888 } else { 5889 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5890 << Sel << T << TL.getSourceRange(); 5891 } 5892 Info.DiagnoseAbstractType(); 5893 } 5894 }; 5895 5896 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5897 Sema::AbstractDiagSelID Sel) { 5898 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5899 } 5900 5901 } 5902 5903 /// Check for invalid uses of an abstract type in a method declaration. 5904 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5905 CXXMethodDecl *MD) { 5906 // No need to do the check on definitions, which require that 5907 // the return/param types be complete. 5908 if (MD->doesThisDeclarationHaveABody()) 5909 return; 5910 5911 // For safety's sake, just ignore it if we don't have type source 5912 // information. This should never happen for non-implicit methods, 5913 // but... 5914 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5915 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5916 } 5917 5918 /// Check for invalid uses of an abstract type within a class definition. 5919 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5920 CXXRecordDecl *RD) { 5921 for (auto *D : RD->decls()) { 5922 if (D->isImplicit()) continue; 5923 5924 // Methods and method templates. 5925 if (isa<CXXMethodDecl>(D)) { 5926 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5927 } else if (isa<FunctionTemplateDecl>(D)) { 5928 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5929 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5930 5931 // Fields and static variables. 5932 } else if (isa<FieldDecl>(D)) { 5933 FieldDecl *FD = cast<FieldDecl>(D); 5934 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5935 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5936 } else if (isa<VarDecl>(D)) { 5937 VarDecl *VD = cast<VarDecl>(D); 5938 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5939 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5940 5941 // Nested classes and class templates. 5942 } else if (isa<CXXRecordDecl>(D)) { 5943 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5944 } else if (isa<ClassTemplateDecl>(D)) { 5945 CheckAbstractClassUsage(Info, 5946 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5947 } 5948 } 5949 } 5950 5951 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5952 Attr *ClassAttr = getDLLAttr(Class); 5953 if (!ClassAttr) 5954 return; 5955 5956 assert(ClassAttr->getKind() == attr::DLLExport); 5957 5958 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5959 5960 if (TSK == TSK_ExplicitInstantiationDeclaration) 5961 // Don't go any further if this is just an explicit instantiation 5962 // declaration. 5963 return; 5964 5965 // Add a context note to explain how we got to any diagnostics produced below. 5966 struct MarkingClassDllexported { 5967 Sema &S; 5968 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class, 5969 SourceLocation AttrLoc) 5970 : S(S) { 5971 Sema::CodeSynthesisContext Ctx; 5972 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported; 5973 Ctx.PointOfInstantiation = AttrLoc; 5974 Ctx.Entity = Class; 5975 S.pushCodeSynthesisContext(Ctx); 5976 } 5977 ~MarkingClassDllexported() { 5978 S.popCodeSynthesisContext(); 5979 } 5980 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); 5981 5982 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5983 S.MarkVTableUsed(Class->getLocation(), Class, true); 5984 5985 for (Decl *Member : Class->decls()) { 5986 // Skip members that were not marked exported. 5987 if (!Member->hasAttr<DLLExportAttr>()) 5988 continue; 5989 5990 // Defined static variables that are members of an exported base 5991 // class must be marked export too. 5992 auto *VD = dyn_cast<VarDecl>(Member); 5993 if (VD && VD->getStorageClass() == SC_Static && 5994 TSK == TSK_ImplicitInstantiation) 5995 S.MarkVariableReferenced(VD->getLocation(), VD); 5996 5997 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5998 if (!MD) 5999 continue; 6000 6001 if (MD->isUserProvided()) { 6002 // Instantiate non-default class member functions ... 6003 6004 // .. except for certain kinds of template specializations. 6005 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 6006 continue; 6007 6008 // If this is an MS ABI dllexport default constructor, instantiate any 6009 // default arguments. 6010 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 6011 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6012 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) { 6013 S.InstantiateDefaultCtorDefaultArgs(CD); 6014 } 6015 } 6016 6017 S.MarkFunctionReferenced(Class->getLocation(), MD); 6018 6019 // The function will be passed to the consumer when its definition is 6020 // encountered. 6021 } else if (MD->isExplicitlyDefaulted()) { 6022 // Synthesize and instantiate explicitly defaulted methods. 6023 S.MarkFunctionReferenced(Class->getLocation(), MD); 6024 6025 if (TSK != TSK_ExplicitInstantiationDefinition) { 6026 // Except for explicit instantiation defs, we will not see the 6027 // definition again later, so pass it to the consumer now. 6028 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 6029 } 6030 } else if (!MD->isTrivial() || 6031 MD->isCopyAssignmentOperator() || 6032 MD->isMoveAssignmentOperator()) { 6033 // Synthesize and instantiate non-trivial implicit methods, and the copy 6034 // and move assignment operators. The latter are exported even if they 6035 // are trivial, because the address of an operator can be taken and 6036 // should compare equal across libraries. 6037 S.MarkFunctionReferenced(Class->getLocation(), MD); 6038 6039 // There is no later point when we will see the definition of this 6040 // function, so pass it to the consumer now. 6041 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 6042 } 6043 } 6044 } 6045 6046 static void checkForMultipleExportedDefaultConstructors(Sema &S, 6047 CXXRecordDecl *Class) { 6048 // Only the MS ABI has default constructor closures, so we don't need to do 6049 // this semantic checking anywhere else. 6050 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 6051 return; 6052 6053 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 6054 for (Decl *Member : Class->decls()) { 6055 // Look for exported default constructors. 6056 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 6057 if (!CD || !CD->isDefaultConstructor()) 6058 continue; 6059 auto *Attr = CD->getAttr<DLLExportAttr>(); 6060 if (!Attr) 6061 continue; 6062 6063 // If the class is non-dependent, mark the default arguments as ODR-used so 6064 // that we can properly codegen the constructor closure. 6065 if (!Class->isDependentContext()) { 6066 for (ParmVarDecl *PD : CD->parameters()) { 6067 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 6068 S.DiscardCleanupsInEvaluationContext(); 6069 } 6070 } 6071 6072 if (LastExportedDefaultCtor) { 6073 S.Diag(LastExportedDefaultCtor->getLocation(), 6074 diag::err_attribute_dll_ambiguous_default_ctor) 6075 << Class; 6076 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 6077 << CD->getDeclName(); 6078 return; 6079 } 6080 LastExportedDefaultCtor = CD; 6081 } 6082 } 6083 6084 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, 6085 CXXRecordDecl *Class) { 6086 bool ErrorReported = false; 6087 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6088 ClassTemplateDecl *TD) { 6089 if (ErrorReported) 6090 return; 6091 S.Diag(TD->getLocation(), 6092 diag::err_cuda_device_builtin_surftex_cls_template) 6093 << /*surface*/ 0 << TD; 6094 ErrorReported = true; 6095 }; 6096 6097 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6098 if (!TD) { 6099 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6100 if (!SD) { 6101 S.Diag(Class->getLocation(), 6102 diag::err_cuda_device_builtin_surftex_ref_decl) 6103 << /*surface*/ 0 << Class; 6104 S.Diag(Class->getLocation(), 6105 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6106 << Class; 6107 return; 6108 } 6109 TD = SD->getSpecializedTemplate(); 6110 } 6111 6112 TemplateParameterList *Params = TD->getTemplateParameters(); 6113 unsigned N = Params->size(); 6114 6115 if (N != 2) { 6116 reportIllegalClassTemplate(S, TD); 6117 S.Diag(TD->getLocation(), 6118 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6119 << TD << 2; 6120 } 6121 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6122 reportIllegalClassTemplate(S, TD); 6123 S.Diag(TD->getLocation(), 6124 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6125 << TD << /*1st*/ 0 << /*type*/ 0; 6126 } 6127 if (N > 1) { 6128 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6129 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6130 reportIllegalClassTemplate(S, TD); 6131 S.Diag(TD->getLocation(), 6132 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6133 << TD << /*2nd*/ 1 << /*integer*/ 1; 6134 } 6135 } 6136 } 6137 6138 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, 6139 CXXRecordDecl *Class) { 6140 bool ErrorReported = false; 6141 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6142 ClassTemplateDecl *TD) { 6143 if (ErrorReported) 6144 return; 6145 S.Diag(TD->getLocation(), 6146 diag::err_cuda_device_builtin_surftex_cls_template) 6147 << /*texture*/ 1 << TD; 6148 ErrorReported = true; 6149 }; 6150 6151 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6152 if (!TD) { 6153 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6154 if (!SD) { 6155 S.Diag(Class->getLocation(), 6156 diag::err_cuda_device_builtin_surftex_ref_decl) 6157 << /*texture*/ 1 << Class; 6158 S.Diag(Class->getLocation(), 6159 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6160 << Class; 6161 return; 6162 } 6163 TD = SD->getSpecializedTemplate(); 6164 } 6165 6166 TemplateParameterList *Params = TD->getTemplateParameters(); 6167 unsigned N = Params->size(); 6168 6169 if (N != 3) { 6170 reportIllegalClassTemplate(S, TD); 6171 S.Diag(TD->getLocation(), 6172 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6173 << TD << 3; 6174 } 6175 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6176 reportIllegalClassTemplate(S, TD); 6177 S.Diag(TD->getLocation(), 6178 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6179 << TD << /*1st*/ 0 << /*type*/ 0; 6180 } 6181 if (N > 1) { 6182 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6183 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6184 reportIllegalClassTemplate(S, TD); 6185 S.Diag(TD->getLocation(), 6186 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6187 << TD << /*2nd*/ 1 << /*integer*/ 1; 6188 } 6189 } 6190 if (N > 2) { 6191 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2)); 6192 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6193 reportIllegalClassTemplate(S, TD); 6194 S.Diag(TD->getLocation(), 6195 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6196 << TD << /*3rd*/ 2 << /*integer*/ 1; 6197 } 6198 } 6199 } 6200 6201 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 6202 // Mark any compiler-generated routines with the implicit code_seg attribute. 6203 for (auto *Method : Class->methods()) { 6204 if (Method->isUserProvided()) 6205 continue; 6206 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 6207 Method->addAttr(A); 6208 } 6209 } 6210 6211 /// Check class-level dllimport/dllexport attribute. 6212 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 6213 Attr *ClassAttr = getDLLAttr(Class); 6214 6215 // MSVC inherits DLL attributes to partial class template specializations. 6216 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) { 6217 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 6218 if (Attr *TemplateAttr = 6219 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 6220 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 6221 A->setInherited(true); 6222 ClassAttr = A; 6223 } 6224 } 6225 } 6226 6227 if (!ClassAttr) 6228 return; 6229 6230 if (!Class->isExternallyVisible()) { 6231 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 6232 << Class << ClassAttr; 6233 return; 6234 } 6235 6236 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6237 !ClassAttr->isInherited()) { 6238 // Diagnose dll attributes on members of class with dll attribute. 6239 for (Decl *Member : Class->decls()) { 6240 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 6241 continue; 6242 InheritableAttr *MemberAttr = getDLLAttr(Member); 6243 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 6244 continue; 6245 6246 Diag(MemberAttr->getLocation(), 6247 diag::err_attribute_dll_member_of_dll_class) 6248 << MemberAttr << ClassAttr; 6249 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 6250 Member->setInvalidDecl(); 6251 } 6252 } 6253 6254 if (Class->getDescribedClassTemplate()) 6255 // Don't inherit dll attribute until the template is instantiated. 6256 return; 6257 6258 // The class is either imported or exported. 6259 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 6260 6261 // Check if this was a dllimport attribute propagated from a derived class to 6262 // a base class template specialization. We don't apply these attributes to 6263 // static data members. 6264 const bool PropagatedImport = 6265 !ClassExported && 6266 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 6267 6268 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6269 6270 // Ignore explicit dllexport on explicit class template instantiation 6271 // declarations, except in MinGW mode. 6272 if (ClassExported && !ClassAttr->isInherited() && 6273 TSK == TSK_ExplicitInstantiationDeclaration && 6274 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 6275 Class->dropAttr<DLLExportAttr>(); 6276 return; 6277 } 6278 6279 // Force declaration of implicit members so they can inherit the attribute. 6280 ForceDeclarationOfImplicitMembers(Class); 6281 6282 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 6283 // seem to be true in practice? 6284 6285 for (Decl *Member : Class->decls()) { 6286 VarDecl *VD = dyn_cast<VarDecl>(Member); 6287 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 6288 6289 // Only methods and static fields inherit the attributes. 6290 if (!VD && !MD) 6291 continue; 6292 6293 if (MD) { 6294 // Don't process deleted methods. 6295 if (MD->isDeleted()) 6296 continue; 6297 6298 if (MD->isInlined()) { 6299 // MinGW does not import or export inline methods. But do it for 6300 // template instantiations. 6301 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6302 TSK != TSK_ExplicitInstantiationDeclaration && 6303 TSK != TSK_ExplicitInstantiationDefinition) 6304 continue; 6305 6306 // MSVC versions before 2015 don't export the move assignment operators 6307 // and move constructor, so don't attempt to import/export them if 6308 // we have a definition. 6309 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 6310 if ((MD->isMoveAssignmentOperator() || 6311 (Ctor && Ctor->isMoveConstructor())) && 6312 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 6313 continue; 6314 6315 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 6316 // operator is exported anyway. 6317 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6318 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 6319 continue; 6320 } 6321 } 6322 6323 // Don't apply dllimport attributes to static data members of class template 6324 // instantiations when the attribute is propagated from a derived class. 6325 if (VD && PropagatedImport) 6326 continue; 6327 6328 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6329 continue; 6330 6331 if (!getDLLAttr(Member)) { 6332 InheritableAttr *NewAttr = nullptr; 6333 6334 // Do not export/import inline function when -fno-dllexport-inlines is 6335 // passed. But add attribute for later local static var check. 6336 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6337 TSK != TSK_ExplicitInstantiationDeclaration && 6338 TSK != TSK_ExplicitInstantiationDefinition) { 6339 if (ClassExported) { 6340 NewAttr = ::new (getASTContext()) 6341 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6342 } else { 6343 NewAttr = ::new (getASTContext()) 6344 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6345 } 6346 } else { 6347 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6348 } 6349 6350 NewAttr->setInherited(true); 6351 Member->addAttr(NewAttr); 6352 6353 if (MD) { 6354 // Propagate DLLAttr to friend re-declarations of MD that have already 6355 // been constructed. 6356 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6357 FD = FD->getPreviousDecl()) { 6358 if (FD->getFriendObjectKind() == Decl::FOK_None) 6359 continue; 6360 assert(!getDLLAttr(FD) && 6361 "friend re-decl should not already have a DLLAttr"); 6362 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6363 NewAttr->setInherited(true); 6364 FD->addAttr(NewAttr); 6365 } 6366 } 6367 } 6368 } 6369 6370 if (ClassExported) 6371 DelayedDllExportClasses.push_back(Class); 6372 } 6373 6374 /// Perform propagation of DLL attributes from a derived class to a 6375 /// templated base class for MS compatibility. 6376 void Sema::propagateDLLAttrToBaseClassTemplate( 6377 CXXRecordDecl *Class, Attr *ClassAttr, 6378 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6379 if (getDLLAttr( 6380 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6381 // If the base class template has a DLL attribute, don't try to change it. 6382 return; 6383 } 6384 6385 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6386 if (!getDLLAttr(BaseTemplateSpec) && 6387 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6388 TSK == TSK_ImplicitInstantiation)) { 6389 // The template hasn't been instantiated yet (or it has, but only as an 6390 // explicit instantiation declaration or implicit instantiation, which means 6391 // we haven't codegenned any members yet), so propagate the attribute. 6392 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6393 NewAttr->setInherited(true); 6394 BaseTemplateSpec->addAttr(NewAttr); 6395 6396 // If this was an import, mark that we propagated it from a derived class to 6397 // a base class template specialization. 6398 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6399 ImportAttr->setPropagatedToBaseTemplate(); 6400 6401 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6402 // needs to be run again to work see the new attribute. Otherwise this will 6403 // get run whenever the template is instantiated. 6404 if (TSK != TSK_Undeclared) 6405 checkClassLevelDLLAttribute(BaseTemplateSpec); 6406 6407 return; 6408 } 6409 6410 if (getDLLAttr(BaseTemplateSpec)) { 6411 // The template has already been specialized or instantiated with an 6412 // attribute, explicitly or through propagation. We should not try to change 6413 // it. 6414 return; 6415 } 6416 6417 // The template was previously instantiated or explicitly specialized without 6418 // a dll attribute, It's too late for us to add an attribute, so warn that 6419 // this is unsupported. 6420 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6421 << BaseTemplateSpec->isExplicitSpecialization(); 6422 Diag(ClassAttr->getLocation(), diag::note_attribute); 6423 if (BaseTemplateSpec->isExplicitSpecialization()) { 6424 Diag(BaseTemplateSpec->getLocation(), 6425 diag::note_template_class_explicit_specialization_was_here) 6426 << BaseTemplateSpec; 6427 } else { 6428 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6429 diag::note_template_class_instantiation_was_here) 6430 << BaseTemplateSpec; 6431 } 6432 } 6433 6434 /// Determine the kind of defaulting that would be done for a given function. 6435 /// 6436 /// If the function is both a default constructor and a copy / move constructor 6437 /// (due to having a default argument for the first parameter), this picks 6438 /// CXXDefaultConstructor. 6439 /// 6440 /// FIXME: Check that case is properly handled by all callers. 6441 Sema::DefaultedFunctionKind 6442 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6443 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6444 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6445 if (Ctor->isDefaultConstructor()) 6446 return Sema::CXXDefaultConstructor; 6447 6448 if (Ctor->isCopyConstructor()) 6449 return Sema::CXXCopyConstructor; 6450 6451 if (Ctor->isMoveConstructor()) 6452 return Sema::CXXMoveConstructor; 6453 } 6454 6455 if (MD->isCopyAssignmentOperator()) 6456 return Sema::CXXCopyAssignment; 6457 6458 if (MD->isMoveAssignmentOperator()) 6459 return Sema::CXXMoveAssignment; 6460 6461 if (isa<CXXDestructorDecl>(FD)) 6462 return Sema::CXXDestructor; 6463 } 6464 6465 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6466 case OO_EqualEqual: 6467 return DefaultedComparisonKind::Equal; 6468 6469 case OO_ExclaimEqual: 6470 return DefaultedComparisonKind::NotEqual; 6471 6472 case OO_Spaceship: 6473 // No point allowing this if <=> doesn't exist in the current language mode. 6474 if (!getLangOpts().CPlusPlus20) 6475 break; 6476 return DefaultedComparisonKind::ThreeWay; 6477 6478 case OO_Less: 6479 case OO_LessEqual: 6480 case OO_Greater: 6481 case OO_GreaterEqual: 6482 // No point allowing this if <=> doesn't exist in the current language mode. 6483 if (!getLangOpts().CPlusPlus20) 6484 break; 6485 return DefaultedComparisonKind::Relational; 6486 6487 default: 6488 break; 6489 } 6490 6491 // Not defaultable. 6492 return DefaultedFunctionKind(); 6493 } 6494 6495 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, 6496 SourceLocation DefaultLoc) { 6497 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD); 6498 if (DFK.isComparison()) 6499 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison()); 6500 6501 switch (DFK.asSpecialMember()) { 6502 case Sema::CXXDefaultConstructor: 6503 S.DefineImplicitDefaultConstructor(DefaultLoc, 6504 cast<CXXConstructorDecl>(FD)); 6505 break; 6506 case Sema::CXXCopyConstructor: 6507 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6508 break; 6509 case Sema::CXXCopyAssignment: 6510 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6511 break; 6512 case Sema::CXXDestructor: 6513 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD)); 6514 break; 6515 case Sema::CXXMoveConstructor: 6516 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6517 break; 6518 case Sema::CXXMoveAssignment: 6519 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6520 break; 6521 case Sema::CXXInvalid: 6522 llvm_unreachable("Invalid special member."); 6523 } 6524 } 6525 6526 /// Determine whether a type is permitted to be passed or returned in 6527 /// registers, per C++ [class.temporary]p3. 6528 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6529 TargetInfo::CallingConvKind CCK) { 6530 if (D->isDependentType() || D->isInvalidDecl()) 6531 return false; 6532 6533 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6534 // The PS4 platform ABI follows the behavior of Clang 3.2. 6535 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6536 return !D->hasNonTrivialDestructorForCall() && 6537 !D->hasNonTrivialCopyConstructorForCall(); 6538 6539 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6540 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6541 bool DtorIsTrivialForCall = false; 6542 6543 // If a class has at least one non-deleted, trivial copy constructor, it 6544 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6545 // 6546 // Note: This permits classes with non-trivial copy or move ctors to be 6547 // passed in registers, so long as they *also* have a trivial copy ctor, 6548 // which is non-conforming. 6549 if (D->needsImplicitCopyConstructor()) { 6550 if (!D->defaultedCopyConstructorIsDeleted()) { 6551 if (D->hasTrivialCopyConstructor()) 6552 CopyCtorIsTrivial = true; 6553 if (D->hasTrivialCopyConstructorForCall()) 6554 CopyCtorIsTrivialForCall = true; 6555 } 6556 } else { 6557 for (const CXXConstructorDecl *CD : D->ctors()) { 6558 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6559 if (CD->isTrivial()) 6560 CopyCtorIsTrivial = true; 6561 if (CD->isTrivialForCall()) 6562 CopyCtorIsTrivialForCall = true; 6563 } 6564 } 6565 } 6566 6567 if (D->needsImplicitDestructor()) { 6568 if (!D->defaultedDestructorIsDeleted() && 6569 D->hasTrivialDestructorForCall()) 6570 DtorIsTrivialForCall = true; 6571 } else if (const auto *DD = D->getDestructor()) { 6572 if (!DD->isDeleted() && DD->isTrivialForCall()) 6573 DtorIsTrivialForCall = true; 6574 } 6575 6576 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6577 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6578 return true; 6579 6580 // If a class has a destructor, we'd really like to pass it indirectly 6581 // because it allows us to elide copies. Unfortunately, MSVC makes that 6582 // impossible for small types, which it will pass in a single register or 6583 // stack slot. Most objects with dtors are large-ish, so handle that early. 6584 // We can't call out all large objects as being indirect because there are 6585 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6586 // how we pass large POD types. 6587 6588 // Note: This permits small classes with nontrivial destructors to be 6589 // passed in registers, which is non-conforming. 6590 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6591 uint64_t TypeSize = isAArch64 ? 128 : 64; 6592 6593 if (CopyCtorIsTrivial && 6594 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6595 return true; 6596 return false; 6597 } 6598 6599 // Per C++ [class.temporary]p3, the relevant condition is: 6600 // each copy constructor, move constructor, and destructor of X is 6601 // either trivial or deleted, and X has at least one non-deleted copy 6602 // or move constructor 6603 bool HasNonDeletedCopyOrMove = false; 6604 6605 if (D->needsImplicitCopyConstructor() && 6606 !D->defaultedCopyConstructorIsDeleted()) { 6607 if (!D->hasTrivialCopyConstructorForCall()) 6608 return false; 6609 HasNonDeletedCopyOrMove = true; 6610 } 6611 6612 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6613 !D->defaultedMoveConstructorIsDeleted()) { 6614 if (!D->hasTrivialMoveConstructorForCall()) 6615 return false; 6616 HasNonDeletedCopyOrMove = true; 6617 } 6618 6619 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6620 !D->hasTrivialDestructorForCall()) 6621 return false; 6622 6623 for (const CXXMethodDecl *MD : D->methods()) { 6624 if (MD->isDeleted()) 6625 continue; 6626 6627 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6628 if (CD && CD->isCopyOrMoveConstructor()) 6629 HasNonDeletedCopyOrMove = true; 6630 else if (!isa<CXXDestructorDecl>(MD)) 6631 continue; 6632 6633 if (!MD->isTrivialForCall()) 6634 return false; 6635 } 6636 6637 return HasNonDeletedCopyOrMove; 6638 } 6639 6640 /// Report an error regarding overriding, along with any relevant 6641 /// overridden methods. 6642 /// 6643 /// \param DiagID the primary error to report. 6644 /// \param MD the overriding method. 6645 static bool 6646 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, 6647 llvm::function_ref<bool(const CXXMethodDecl *)> Report) { 6648 bool IssuedDiagnostic = false; 6649 for (const CXXMethodDecl *O : MD->overridden_methods()) { 6650 if (Report(O)) { 6651 if (!IssuedDiagnostic) { 6652 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6653 IssuedDiagnostic = true; 6654 } 6655 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 6656 } 6657 } 6658 return IssuedDiagnostic; 6659 } 6660 6661 /// Perform semantic checks on a class definition that has been 6662 /// completing, introducing implicitly-declared members, checking for 6663 /// abstract types, etc. 6664 /// 6665 /// \param S The scope in which the class was parsed. Null if we didn't just 6666 /// parse a class definition. 6667 /// \param Record The completed class. 6668 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6669 if (!Record) 6670 return; 6671 6672 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6673 AbstractUsageInfo Info(*this, Record); 6674 CheckAbstractClassUsage(Info, Record); 6675 } 6676 6677 // If this is not an aggregate type and has no user-declared constructor, 6678 // complain about any non-static data members of reference or const scalar 6679 // type, since they will never get initializers. 6680 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6681 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6682 !Record->isLambda()) { 6683 bool Complained = false; 6684 for (const auto *F : Record->fields()) { 6685 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6686 continue; 6687 6688 if (F->getType()->isReferenceType() || 6689 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6690 if (!Complained) { 6691 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6692 << Record->getTagKind() << Record; 6693 Complained = true; 6694 } 6695 6696 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6697 << F->getType()->isReferenceType() 6698 << F->getDeclName(); 6699 } 6700 } 6701 } 6702 6703 if (Record->getIdentifier()) { 6704 // C++ [class.mem]p13: 6705 // If T is the name of a class, then each of the following shall have a 6706 // name different from T: 6707 // - every member of every anonymous union that is a member of class T. 6708 // 6709 // C++ [class.mem]p14: 6710 // In addition, if class T has a user-declared constructor (12.1), every 6711 // non-static data member of class T shall have a name different from T. 6712 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6713 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6714 ++I) { 6715 NamedDecl *D = (*I)->getUnderlyingDecl(); 6716 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6717 Record->hasUserDeclaredConstructor()) || 6718 isa<IndirectFieldDecl>(D)) { 6719 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6720 << D->getDeclName(); 6721 break; 6722 } 6723 } 6724 } 6725 6726 // Warn if the class has virtual methods but non-virtual public destructor. 6727 if (Record->isPolymorphic() && !Record->isDependentType()) { 6728 CXXDestructorDecl *dtor = Record->getDestructor(); 6729 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6730 !Record->hasAttr<FinalAttr>()) 6731 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6732 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6733 } 6734 6735 if (Record->isAbstract()) { 6736 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6737 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6738 << FA->isSpelledAsSealed(); 6739 DiagnoseAbstractType(Record); 6740 } 6741 } 6742 6743 // Warn if the class has a final destructor but is not itself marked final. 6744 if (!Record->hasAttr<FinalAttr>()) { 6745 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6746 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6747 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6748 << FA->isSpelledAsSealed() 6749 << FixItHint::CreateInsertion( 6750 getLocForEndOfToken(Record->getLocation()), 6751 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6752 Diag(Record->getLocation(), 6753 diag::note_final_dtor_non_final_class_silence) 6754 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6755 } 6756 } 6757 } 6758 6759 // See if trivial_abi has to be dropped. 6760 if (Record->hasAttr<TrivialABIAttr>()) 6761 checkIllFormedTrivialABIStruct(*Record); 6762 6763 // Set HasTrivialSpecialMemberForCall if the record has attribute 6764 // "trivial_abi". 6765 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6766 6767 if (HasTrivialABI) 6768 Record->setHasTrivialSpecialMemberForCall(); 6769 6770 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6771 // We check these last because they can depend on the properties of the 6772 // primary comparison functions (==, <=>). 6773 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6774 6775 // Perform checks that can't be done until we know all the properties of a 6776 // member function (whether it's defaulted, deleted, virtual, overriding, 6777 // ...). 6778 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) { 6779 // A static function cannot override anything. 6780 if (MD->getStorageClass() == SC_Static) { 6781 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD, 6782 [](const CXXMethodDecl *) { return true; })) 6783 return; 6784 } 6785 6786 // A deleted function cannot override a non-deleted function and vice 6787 // versa. 6788 if (ReportOverrides(*this, 6789 MD->isDeleted() ? diag::err_deleted_override 6790 : diag::err_non_deleted_override, 6791 MD, [&](const CXXMethodDecl *V) { 6792 return MD->isDeleted() != V->isDeleted(); 6793 })) { 6794 if (MD->isDefaulted() && MD->isDeleted()) 6795 // Explain why this defaulted function was deleted. 6796 DiagnoseDeletedDefaultedFunction(MD); 6797 return; 6798 } 6799 6800 // A consteval function cannot override a non-consteval function and vice 6801 // versa. 6802 if (ReportOverrides(*this, 6803 MD->isConsteval() ? diag::err_consteval_override 6804 : diag::err_non_consteval_override, 6805 MD, [&](const CXXMethodDecl *V) { 6806 return MD->isConsteval() != V->isConsteval(); 6807 })) { 6808 if (MD->isDefaulted() && MD->isDeleted()) 6809 // Explain why this defaulted function was deleted. 6810 DiagnoseDeletedDefaultedFunction(MD); 6811 return; 6812 } 6813 }; 6814 6815 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool { 6816 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6817 return false; 6818 6819 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6820 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6821 DFK.asComparison() == DefaultedComparisonKind::Relational) { 6822 DefaultedSecondaryComparisons.push_back(FD); 6823 return true; 6824 } 6825 6826 CheckExplicitlyDefaultedFunction(S, FD); 6827 return false; 6828 }; 6829 6830 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6831 // Check whether the explicitly-defaulted members are valid. 6832 bool Incomplete = CheckForDefaultedFunction(M); 6833 6834 // Skip the rest of the checks for a member of a dependent class. 6835 if (Record->isDependentType()) 6836 return; 6837 6838 // For an explicitly defaulted or deleted special member, we defer 6839 // determining triviality until the class is complete. That time is now! 6840 CXXSpecialMember CSM = getSpecialMember(M); 6841 if (!M->isImplicit() && !M->isUserProvided()) { 6842 if (CSM != CXXInvalid) { 6843 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6844 // Inform the class that we've finished declaring this member. 6845 Record->finishedDefaultedOrDeletedMember(M); 6846 M->setTrivialForCall( 6847 HasTrivialABI || 6848 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6849 Record->setTrivialForCallFlags(M); 6850 } 6851 } 6852 6853 // Set triviality for the purpose of calls if this is a user-provided 6854 // copy/move constructor or destructor. 6855 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6856 CSM == CXXDestructor) && M->isUserProvided()) { 6857 M->setTrivialForCall(HasTrivialABI); 6858 Record->setTrivialForCallFlags(M); 6859 } 6860 6861 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6862 M->hasAttr<DLLExportAttr>()) { 6863 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6864 M->isTrivial() && 6865 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6866 CSM == CXXDestructor)) 6867 M->dropAttr<DLLExportAttr>(); 6868 6869 if (M->hasAttr<DLLExportAttr>()) { 6870 // Define after any fields with in-class initializers have been parsed. 6871 DelayedDllExportMemberFunctions.push_back(M); 6872 } 6873 } 6874 6875 // Define defaulted constexpr virtual functions that override a base class 6876 // function right away. 6877 // FIXME: We can defer doing this until the vtable is marked as used. 6878 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6879 DefineDefaultedFunction(*this, M, M->getLocation()); 6880 6881 if (!Incomplete) 6882 CheckCompletedMemberFunction(M); 6883 }; 6884 6885 // Check the destructor before any other member function. We need to 6886 // determine whether it's trivial in order to determine whether the claas 6887 // type is a literal type, which is a prerequisite for determining whether 6888 // other special member functions are valid and whether they're implicitly 6889 // 'constexpr'. 6890 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6891 CompleteMemberFunction(Dtor); 6892 6893 bool HasMethodWithOverrideControl = false, 6894 HasOverridingMethodWithoutOverrideControl = false; 6895 for (auto *D : Record->decls()) { 6896 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 6897 // FIXME: We could do this check for dependent types with non-dependent 6898 // bases. 6899 if (!Record->isDependentType()) { 6900 // See if a method overloads virtual methods in a base 6901 // class without overriding any. 6902 if (!M->isStatic()) 6903 DiagnoseHiddenVirtualMethods(M); 6904 if (M->hasAttr<OverrideAttr>()) 6905 HasMethodWithOverrideControl = true; 6906 else if (M->size_overridden_methods() > 0) 6907 HasOverridingMethodWithoutOverrideControl = true; 6908 } 6909 6910 if (!isa<CXXDestructorDecl>(M)) 6911 CompleteMemberFunction(M); 6912 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 6913 CheckForDefaultedFunction( 6914 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 6915 } 6916 } 6917 6918 if (HasOverridingMethodWithoutOverrideControl) { 6919 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl; 6920 for (auto *M : Record->methods()) 6921 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl); 6922 } 6923 6924 // Check the defaulted secondary comparisons after any other member functions. 6925 for (FunctionDecl *FD : DefaultedSecondaryComparisons) { 6926 CheckExplicitlyDefaultedFunction(S, FD); 6927 6928 // If this is a member function, we deferred checking it until now. 6929 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) 6930 CheckCompletedMemberFunction(MD); 6931 } 6932 6933 // ms_struct is a request to use the same ABI rules as MSVC. Check 6934 // whether this class uses any C++ features that are implemented 6935 // completely differently in MSVC, and if so, emit a diagnostic. 6936 // That diagnostic defaults to an error, but we allow projects to 6937 // map it down to a warning (or ignore it). It's a fairly common 6938 // practice among users of the ms_struct pragma to mass-annotate 6939 // headers, sweeping up a bunch of types that the project doesn't 6940 // really rely on MSVC-compatible layout for. We must therefore 6941 // support "ms_struct except for C++ stuff" as a secondary ABI. 6942 // Don't emit this diagnostic if the feature was enabled as a 6943 // language option (as opposed to via a pragma or attribute), as 6944 // the option -mms-bitfields otherwise essentially makes it impossible 6945 // to build C++ code, unless this diagnostic is turned off. 6946 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields && 6947 (Record->isPolymorphic() || Record->getNumBases())) { 6948 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6949 } 6950 6951 checkClassLevelDLLAttribute(Record); 6952 checkClassLevelCodeSegAttribute(Record); 6953 6954 bool ClangABICompat4 = 6955 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6956 TargetInfo::CallingConvKind CCK = 6957 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6958 bool CanPass = canPassInRegisters(*this, Record, CCK); 6959 6960 // Do not change ArgPassingRestrictions if it has already been set to 6961 // APK_CanNeverPassInRegs. 6962 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6963 Record->setArgPassingRestrictions(CanPass 6964 ? RecordDecl::APK_CanPassInRegs 6965 : RecordDecl::APK_CannotPassInRegs); 6966 6967 // If canPassInRegisters returns true despite the record having a non-trivial 6968 // destructor, the record is destructed in the callee. This happens only when 6969 // the record or one of its subobjects has a field annotated with trivial_abi 6970 // or a field qualified with ObjC __strong/__weak. 6971 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6972 Record->setParamDestroyedInCallee(true); 6973 else if (Record->hasNonTrivialDestructor()) 6974 Record->setParamDestroyedInCallee(CanPass); 6975 6976 if (getLangOpts().ForceEmitVTables) { 6977 // If we want to emit all the vtables, we need to mark it as used. This 6978 // is especially required for cases like vtable assumption loads. 6979 MarkVTableUsed(Record->getInnerLocStart(), Record); 6980 } 6981 6982 if (getLangOpts().CUDA) { 6983 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) 6984 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record); 6985 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>()) 6986 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record); 6987 } 6988 } 6989 6990 /// Look up the special member function that would be called by a special 6991 /// member function for a subobject of class type. 6992 /// 6993 /// \param Class The class type of the subobject. 6994 /// \param CSM The kind of special member function. 6995 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6996 /// \param ConstRHS True if this is a copy operation with a const object 6997 /// on its RHS, that is, if the argument to the outer special member 6998 /// function is 'const' and this is not a field marked 'mutable'. 6999 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 7000 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 7001 unsigned FieldQuals, bool ConstRHS) { 7002 unsigned LHSQuals = 0; 7003 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 7004 LHSQuals = FieldQuals; 7005 7006 unsigned RHSQuals = FieldQuals; 7007 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 7008 RHSQuals = 0; 7009 else if (ConstRHS) 7010 RHSQuals |= Qualifiers::Const; 7011 7012 return S.LookupSpecialMember(Class, CSM, 7013 RHSQuals & Qualifiers::Const, 7014 RHSQuals & Qualifiers::Volatile, 7015 false, 7016 LHSQuals & Qualifiers::Const, 7017 LHSQuals & Qualifiers::Volatile); 7018 } 7019 7020 class Sema::InheritedConstructorInfo { 7021 Sema &S; 7022 SourceLocation UseLoc; 7023 7024 /// A mapping from the base classes through which the constructor was 7025 /// inherited to the using shadow declaration in that base class (or a null 7026 /// pointer if the constructor was declared in that base class). 7027 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 7028 InheritedFromBases; 7029 7030 public: 7031 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 7032 ConstructorUsingShadowDecl *Shadow) 7033 : S(S), UseLoc(UseLoc) { 7034 bool DiagnosedMultipleConstructedBases = false; 7035 CXXRecordDecl *ConstructedBase = nullptr; 7036 BaseUsingDecl *ConstructedBaseIntroducer = nullptr; 7037 7038 // Find the set of such base class subobjects and check that there's a 7039 // unique constructed subobject. 7040 for (auto *D : Shadow->redecls()) { 7041 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 7042 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 7043 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 7044 7045 InheritedFromBases.insert( 7046 std::make_pair(DNominatedBase->getCanonicalDecl(), 7047 DShadow->getNominatedBaseClassShadowDecl())); 7048 if (DShadow->constructsVirtualBase()) 7049 InheritedFromBases.insert( 7050 std::make_pair(DConstructedBase->getCanonicalDecl(), 7051 DShadow->getConstructedBaseClassShadowDecl())); 7052 else 7053 assert(DNominatedBase == DConstructedBase); 7054 7055 // [class.inhctor.init]p2: 7056 // If the constructor was inherited from multiple base class subobjects 7057 // of type B, the program is ill-formed. 7058 if (!ConstructedBase) { 7059 ConstructedBase = DConstructedBase; 7060 ConstructedBaseIntroducer = D->getIntroducer(); 7061 } else if (ConstructedBase != DConstructedBase && 7062 !Shadow->isInvalidDecl()) { 7063 if (!DiagnosedMultipleConstructedBases) { 7064 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 7065 << Shadow->getTargetDecl(); 7066 S.Diag(ConstructedBaseIntroducer->getLocation(), 7067 diag::note_ambiguous_inherited_constructor_using) 7068 << ConstructedBase; 7069 DiagnosedMultipleConstructedBases = true; 7070 } 7071 S.Diag(D->getIntroducer()->getLocation(), 7072 diag::note_ambiguous_inherited_constructor_using) 7073 << DConstructedBase; 7074 } 7075 } 7076 7077 if (DiagnosedMultipleConstructedBases) 7078 Shadow->setInvalidDecl(); 7079 } 7080 7081 /// Find the constructor to use for inherited construction of a base class, 7082 /// and whether that base class constructor inherits the constructor from a 7083 /// virtual base class (in which case it won't actually invoke it). 7084 std::pair<CXXConstructorDecl *, bool> 7085 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 7086 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 7087 if (It == InheritedFromBases.end()) 7088 return std::make_pair(nullptr, false); 7089 7090 // This is an intermediary class. 7091 if (It->second) 7092 return std::make_pair( 7093 S.findInheritingConstructor(UseLoc, Ctor, It->second), 7094 It->second->constructsVirtualBase()); 7095 7096 // This is the base class from which the constructor was inherited. 7097 return std::make_pair(Ctor, false); 7098 } 7099 }; 7100 7101 /// Is the special member function which would be selected to perform the 7102 /// specified operation on the specified class type a constexpr constructor? 7103 static bool 7104 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 7105 Sema::CXXSpecialMember CSM, unsigned Quals, 7106 bool ConstRHS, 7107 CXXConstructorDecl *InheritedCtor = nullptr, 7108 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7109 // If we're inheriting a constructor, see if we need to call it for this base 7110 // class. 7111 if (InheritedCtor) { 7112 assert(CSM == Sema::CXXDefaultConstructor); 7113 auto BaseCtor = 7114 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 7115 if (BaseCtor) 7116 return BaseCtor->isConstexpr(); 7117 } 7118 7119 if (CSM == Sema::CXXDefaultConstructor) 7120 return ClassDecl->hasConstexprDefaultConstructor(); 7121 if (CSM == Sema::CXXDestructor) 7122 return ClassDecl->hasConstexprDestructor(); 7123 7124 Sema::SpecialMemberOverloadResult SMOR = 7125 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 7126 if (!SMOR.getMethod()) 7127 // A constructor we wouldn't select can't be "involved in initializing" 7128 // anything. 7129 return true; 7130 return SMOR.getMethod()->isConstexpr(); 7131 } 7132 7133 /// Determine whether the specified special member function would be constexpr 7134 /// if it were implicitly defined. 7135 static bool defaultedSpecialMemberIsConstexpr( 7136 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 7137 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 7138 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7139 if (!S.getLangOpts().CPlusPlus11) 7140 return false; 7141 7142 // C++11 [dcl.constexpr]p4: 7143 // In the definition of a constexpr constructor [...] 7144 bool Ctor = true; 7145 switch (CSM) { 7146 case Sema::CXXDefaultConstructor: 7147 if (Inherited) 7148 break; 7149 // Since default constructor lookup is essentially trivial (and cannot 7150 // involve, for instance, template instantiation), we compute whether a 7151 // defaulted default constructor is constexpr directly within CXXRecordDecl. 7152 // 7153 // This is important for performance; we need to know whether the default 7154 // constructor is constexpr to determine whether the type is a literal type. 7155 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 7156 7157 case Sema::CXXCopyConstructor: 7158 case Sema::CXXMoveConstructor: 7159 // For copy or move constructors, we need to perform overload resolution. 7160 break; 7161 7162 case Sema::CXXCopyAssignment: 7163 case Sema::CXXMoveAssignment: 7164 if (!S.getLangOpts().CPlusPlus14) 7165 return false; 7166 // In C++1y, we need to perform overload resolution. 7167 Ctor = false; 7168 break; 7169 7170 case Sema::CXXDestructor: 7171 return ClassDecl->defaultedDestructorIsConstexpr(); 7172 7173 case Sema::CXXInvalid: 7174 return false; 7175 } 7176 7177 // -- if the class is a non-empty union, or for each non-empty anonymous 7178 // union member of a non-union class, exactly one non-static data member 7179 // shall be initialized; [DR1359] 7180 // 7181 // If we squint, this is guaranteed, since exactly one non-static data member 7182 // will be initialized (if the constructor isn't deleted), we just don't know 7183 // which one. 7184 if (Ctor && ClassDecl->isUnion()) 7185 return CSM == Sema::CXXDefaultConstructor 7186 ? ClassDecl->hasInClassInitializer() || 7187 !ClassDecl->hasVariantMembers() 7188 : true; 7189 7190 // -- the class shall not have any virtual base classes; 7191 if (Ctor && ClassDecl->getNumVBases()) 7192 return false; 7193 7194 // C++1y [class.copy]p26: 7195 // -- [the class] is a literal type, and 7196 if (!Ctor && !ClassDecl->isLiteral()) 7197 return false; 7198 7199 // -- every constructor involved in initializing [...] base class 7200 // sub-objects shall be a constexpr constructor; 7201 // -- the assignment operator selected to copy/move each direct base 7202 // class is a constexpr function, and 7203 for (const auto &B : ClassDecl->bases()) { 7204 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 7205 if (!BaseType) continue; 7206 7207 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7208 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 7209 InheritedCtor, Inherited)) 7210 return false; 7211 } 7212 7213 // -- every constructor involved in initializing non-static data members 7214 // [...] shall be a constexpr constructor; 7215 // -- every non-static data member and base class sub-object shall be 7216 // initialized 7217 // -- for each non-static data member of X that is of class type (or array 7218 // thereof), the assignment operator selected to copy/move that member is 7219 // a constexpr function 7220 for (const auto *F : ClassDecl->fields()) { 7221 if (F->isInvalidDecl()) 7222 continue; 7223 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 7224 continue; 7225 QualType BaseType = S.Context.getBaseElementType(F->getType()); 7226 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 7227 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7228 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 7229 BaseType.getCVRQualifiers(), 7230 ConstArg && !F->isMutable())) 7231 return false; 7232 } else if (CSM == Sema::CXXDefaultConstructor) { 7233 return false; 7234 } 7235 } 7236 7237 // All OK, it's constexpr! 7238 return true; 7239 } 7240 7241 namespace { 7242 /// RAII object to register a defaulted function as having its exception 7243 /// specification computed. 7244 struct ComputingExceptionSpec { 7245 Sema &S; 7246 7247 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 7248 : S(S) { 7249 Sema::CodeSynthesisContext Ctx; 7250 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 7251 Ctx.PointOfInstantiation = Loc; 7252 Ctx.Entity = FD; 7253 S.pushCodeSynthesisContext(Ctx); 7254 } 7255 ~ComputingExceptionSpec() { 7256 S.popCodeSynthesisContext(); 7257 } 7258 }; 7259 } 7260 7261 static Sema::ImplicitExceptionSpecification 7262 ComputeDefaultedSpecialMemberExceptionSpec( 7263 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 7264 Sema::InheritedConstructorInfo *ICI); 7265 7266 static Sema::ImplicitExceptionSpecification 7267 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 7268 FunctionDecl *FD, 7269 Sema::DefaultedComparisonKind DCK); 7270 7271 static Sema::ImplicitExceptionSpecification 7272 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 7273 auto DFK = S.getDefaultedFunctionKind(FD); 7274 if (DFK.isSpecialMember()) 7275 return ComputeDefaultedSpecialMemberExceptionSpec( 7276 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 7277 if (DFK.isComparison()) 7278 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 7279 DFK.asComparison()); 7280 7281 auto *CD = cast<CXXConstructorDecl>(FD); 7282 assert(CD->getInheritedConstructor() && 7283 "only defaulted functions and inherited constructors have implicit " 7284 "exception specs"); 7285 Sema::InheritedConstructorInfo ICI( 7286 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 7287 return ComputeDefaultedSpecialMemberExceptionSpec( 7288 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 7289 } 7290 7291 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 7292 CXXMethodDecl *MD) { 7293 FunctionProtoType::ExtProtoInfo EPI; 7294 7295 // Build an exception specification pointing back at this member. 7296 EPI.ExceptionSpec.Type = EST_Unevaluated; 7297 EPI.ExceptionSpec.SourceDecl = MD; 7298 7299 // Set the calling convention to the default for C++ instance methods. 7300 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 7301 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 7302 /*IsCXXMethod=*/true)); 7303 return EPI; 7304 } 7305 7306 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 7307 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 7308 if (FPT->getExceptionSpecType() != EST_Unevaluated) 7309 return; 7310 7311 // Evaluate the exception specification. 7312 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 7313 auto ESI = IES.getExceptionSpec(); 7314 7315 // Update the type of the special member to use it. 7316 UpdateExceptionSpec(FD, ESI); 7317 } 7318 7319 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 7320 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted"); 7321 7322 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 7323 if (!DefKind) { 7324 assert(FD->getDeclContext()->isDependentContext()); 7325 return; 7326 } 7327 7328 if (DefKind.isComparison()) 7329 UnusedPrivateFields.clear(); 7330 7331 if (DefKind.isSpecialMember() 7332 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 7333 DefKind.asSpecialMember()) 7334 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 7335 FD->setInvalidDecl(); 7336 } 7337 7338 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7339 CXXSpecialMember CSM) { 7340 CXXRecordDecl *RD = MD->getParent(); 7341 7342 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 7343 "not an explicitly-defaulted special member"); 7344 7345 // Defer all checking for special members of a dependent type. 7346 if (RD->isDependentType()) 7347 return false; 7348 7349 // Whether this was the first-declared instance of the constructor. 7350 // This affects whether we implicitly add an exception spec and constexpr. 7351 bool First = MD == MD->getCanonicalDecl(); 7352 7353 bool HadError = false; 7354 7355 // C++11 [dcl.fct.def.default]p1: 7356 // A function that is explicitly defaulted shall 7357 // -- be a special member function [...] (checked elsewhere), 7358 // -- have the same type (except for ref-qualifiers, and except that a 7359 // copy operation can take a non-const reference) as an implicit 7360 // declaration, and 7361 // -- not have default arguments. 7362 // C++2a changes the second bullet to instead delete the function if it's 7363 // defaulted on its first declaration, unless it's "an assignment operator, 7364 // and its return type differs or its parameter type is not a reference". 7365 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First; 7366 bool ShouldDeleteForTypeMismatch = false; 7367 unsigned ExpectedParams = 1; 7368 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 7369 ExpectedParams = 0; 7370 if (MD->getNumParams() != ExpectedParams) { 7371 // This checks for default arguments: a copy or move constructor with a 7372 // default argument is classified as a default constructor, and assignment 7373 // operations and destructors can't have default arguments. 7374 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 7375 << CSM << MD->getSourceRange(); 7376 HadError = true; 7377 } else if (MD->isVariadic()) { 7378 if (DeleteOnTypeMismatch) 7379 ShouldDeleteForTypeMismatch = true; 7380 else { 7381 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 7382 << CSM << MD->getSourceRange(); 7383 HadError = true; 7384 } 7385 } 7386 7387 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 7388 7389 bool CanHaveConstParam = false; 7390 if (CSM == CXXCopyConstructor) 7391 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 7392 else if (CSM == CXXCopyAssignment) 7393 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 7394 7395 QualType ReturnType = Context.VoidTy; 7396 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 7397 // Check for return type matching. 7398 ReturnType = Type->getReturnType(); 7399 7400 QualType DeclType = Context.getTypeDeclType(RD); 7401 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 7402 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 7403 7404 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 7405 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 7406 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 7407 HadError = true; 7408 } 7409 7410 // A defaulted special member cannot have cv-qualifiers. 7411 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 7412 if (DeleteOnTypeMismatch) 7413 ShouldDeleteForTypeMismatch = true; 7414 else { 7415 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 7416 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 7417 HadError = true; 7418 } 7419 } 7420 } 7421 7422 // Check for parameter type matching. 7423 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 7424 bool HasConstParam = false; 7425 if (ExpectedParams && ArgType->isReferenceType()) { 7426 // Argument must be reference to possibly-const T. 7427 QualType ReferentType = ArgType->getPointeeType(); 7428 HasConstParam = ReferentType.isConstQualified(); 7429 7430 if (ReferentType.isVolatileQualified()) { 7431 if (DeleteOnTypeMismatch) 7432 ShouldDeleteForTypeMismatch = true; 7433 else { 7434 Diag(MD->getLocation(), 7435 diag::err_defaulted_special_member_volatile_param) << CSM; 7436 HadError = true; 7437 } 7438 } 7439 7440 if (HasConstParam && !CanHaveConstParam) { 7441 if (DeleteOnTypeMismatch) 7442 ShouldDeleteForTypeMismatch = true; 7443 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7444 Diag(MD->getLocation(), 7445 diag::err_defaulted_special_member_copy_const_param) 7446 << (CSM == CXXCopyAssignment); 7447 // FIXME: Explain why this special member can't be const. 7448 HadError = true; 7449 } else { 7450 Diag(MD->getLocation(), 7451 diag::err_defaulted_special_member_move_const_param) 7452 << (CSM == CXXMoveAssignment); 7453 HadError = true; 7454 } 7455 } 7456 } else if (ExpectedParams) { 7457 // A copy assignment operator can take its argument by value, but a 7458 // defaulted one cannot. 7459 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 7460 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7461 HadError = true; 7462 } 7463 7464 // C++11 [dcl.fct.def.default]p2: 7465 // An explicitly-defaulted function may be declared constexpr only if it 7466 // would have been implicitly declared as constexpr, 7467 // Do not apply this rule to members of class templates, since core issue 1358 7468 // makes such functions always instantiate to constexpr functions. For 7469 // functions which cannot be constexpr (for non-constructors in C++11 and for 7470 // destructors in C++14 and C++17), this is checked elsewhere. 7471 // 7472 // FIXME: This should not apply if the member is deleted. 7473 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7474 HasConstParam); 7475 if ((getLangOpts().CPlusPlus20 || 7476 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7477 : isa<CXXConstructorDecl>(MD))) && 7478 MD->isConstexpr() && !Constexpr && 7479 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7480 Diag(MD->getBeginLoc(), MD->isConsteval() 7481 ? diag::err_incorrect_defaulted_consteval 7482 : diag::err_incorrect_defaulted_constexpr) 7483 << CSM; 7484 // FIXME: Explain why the special member can't be constexpr. 7485 HadError = true; 7486 } 7487 7488 if (First) { 7489 // C++2a [dcl.fct.def.default]p3: 7490 // If a function is explicitly defaulted on its first declaration, it is 7491 // implicitly considered to be constexpr if the implicit declaration 7492 // would be. 7493 MD->setConstexprKind(Constexpr ? (MD->isConsteval() 7494 ? ConstexprSpecKind::Consteval 7495 : ConstexprSpecKind::Constexpr) 7496 : ConstexprSpecKind::Unspecified); 7497 7498 if (!Type->hasExceptionSpec()) { 7499 // C++2a [except.spec]p3: 7500 // If a declaration of a function does not have a noexcept-specifier 7501 // [and] is defaulted on its first declaration, [...] the exception 7502 // specification is as specified below 7503 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7504 EPI.ExceptionSpec.Type = EST_Unevaluated; 7505 EPI.ExceptionSpec.SourceDecl = MD; 7506 MD->setType(Context.getFunctionType(ReturnType, 7507 llvm::makeArrayRef(&ArgType, 7508 ExpectedParams), 7509 EPI)); 7510 } 7511 } 7512 7513 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7514 if (First) { 7515 SetDeclDeleted(MD, MD->getLocation()); 7516 if (!inTemplateInstantiation() && !HadError) { 7517 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7518 if (ShouldDeleteForTypeMismatch) { 7519 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7520 } else { 7521 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7522 } 7523 } 7524 if (ShouldDeleteForTypeMismatch && !HadError) { 7525 Diag(MD->getLocation(), 7526 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7527 } 7528 } else { 7529 // C++11 [dcl.fct.def.default]p4: 7530 // [For a] user-provided explicitly-defaulted function [...] if such a 7531 // function is implicitly defined as deleted, the program is ill-formed. 7532 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7533 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 7534 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7535 HadError = true; 7536 } 7537 } 7538 7539 return HadError; 7540 } 7541 7542 namespace { 7543 /// Helper class for building and checking a defaulted comparison. 7544 /// 7545 /// Defaulted functions are built in two phases: 7546 /// 7547 /// * First, the set of operations that the function will perform are 7548 /// identified, and some of them are checked. If any of the checked 7549 /// operations is invalid in certain ways, the comparison function is 7550 /// defined as deleted and no body is built. 7551 /// * Then, if the function is not defined as deleted, the body is built. 7552 /// 7553 /// This is accomplished by performing two visitation steps over the eventual 7554 /// body of the function. 7555 template<typename Derived, typename ResultList, typename Result, 7556 typename Subobject> 7557 class DefaultedComparisonVisitor { 7558 public: 7559 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7560 7561 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7562 DefaultedComparisonKind DCK) 7563 : S(S), RD(RD), FD(FD), DCK(DCK) { 7564 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7565 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7566 // UnresolvedSet to avoid this copy. 7567 Fns.assign(Info->getUnqualifiedLookups().begin(), 7568 Info->getUnqualifiedLookups().end()); 7569 } 7570 } 7571 7572 ResultList visit() { 7573 // The type of an lvalue naming a parameter of this function. 7574 QualType ParamLvalType = 7575 FD->getParamDecl(0)->getType().getNonReferenceType(); 7576 7577 ResultList Results; 7578 7579 switch (DCK) { 7580 case DefaultedComparisonKind::None: 7581 llvm_unreachable("not a defaulted comparison"); 7582 7583 case DefaultedComparisonKind::Equal: 7584 case DefaultedComparisonKind::ThreeWay: 7585 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7586 return Results; 7587 7588 case DefaultedComparisonKind::NotEqual: 7589 case DefaultedComparisonKind::Relational: 7590 Results.add(getDerived().visitExpandedSubobject( 7591 ParamLvalType, getDerived().getCompleteObject())); 7592 return Results; 7593 } 7594 llvm_unreachable(""); 7595 } 7596 7597 protected: 7598 Derived &getDerived() { return static_cast<Derived&>(*this); } 7599 7600 /// Visit the expanded list of subobjects of the given type, as specified in 7601 /// C++2a [class.compare.default]. 7602 /// 7603 /// \return \c true if the ResultList object said we're done, \c false if not. 7604 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7605 Qualifiers Quals) { 7606 // C++2a [class.compare.default]p4: 7607 // The direct base class subobjects of C 7608 for (CXXBaseSpecifier &Base : Record->bases()) 7609 if (Results.add(getDerived().visitSubobject( 7610 S.Context.getQualifiedType(Base.getType(), Quals), 7611 getDerived().getBase(&Base)))) 7612 return true; 7613 7614 // followed by the non-static data members of C 7615 for (FieldDecl *Field : Record->fields()) { 7616 // Recursively expand anonymous structs. 7617 if (Field->isAnonymousStructOrUnion()) { 7618 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7619 Quals)) 7620 return true; 7621 continue; 7622 } 7623 7624 // Figure out the type of an lvalue denoting this field. 7625 Qualifiers FieldQuals = Quals; 7626 if (Field->isMutable()) 7627 FieldQuals.removeConst(); 7628 QualType FieldType = 7629 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7630 7631 if (Results.add(getDerived().visitSubobject( 7632 FieldType, getDerived().getField(Field)))) 7633 return true; 7634 } 7635 7636 // form a list of subobjects. 7637 return false; 7638 } 7639 7640 Result visitSubobject(QualType Type, Subobject Subobj) { 7641 // In that list, any subobject of array type is recursively expanded 7642 const ArrayType *AT = S.Context.getAsArrayType(Type); 7643 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7644 return getDerived().visitSubobjectArray(CAT->getElementType(), 7645 CAT->getSize(), Subobj); 7646 return getDerived().visitExpandedSubobject(Type, Subobj); 7647 } 7648 7649 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7650 Subobject Subobj) { 7651 return getDerived().visitSubobject(Type, Subobj); 7652 } 7653 7654 protected: 7655 Sema &S; 7656 CXXRecordDecl *RD; 7657 FunctionDecl *FD; 7658 DefaultedComparisonKind DCK; 7659 UnresolvedSet<16> Fns; 7660 }; 7661 7662 /// Information about a defaulted comparison, as determined by 7663 /// DefaultedComparisonAnalyzer. 7664 struct DefaultedComparisonInfo { 7665 bool Deleted = false; 7666 bool Constexpr = true; 7667 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7668 7669 static DefaultedComparisonInfo deleted() { 7670 DefaultedComparisonInfo Deleted; 7671 Deleted.Deleted = true; 7672 return Deleted; 7673 } 7674 7675 bool add(const DefaultedComparisonInfo &R) { 7676 Deleted |= R.Deleted; 7677 Constexpr &= R.Constexpr; 7678 Category = commonComparisonType(Category, R.Category); 7679 return Deleted; 7680 } 7681 }; 7682 7683 /// An element in the expanded list of subobjects of a defaulted comparison, as 7684 /// specified in C++2a [class.compare.default]p4. 7685 struct DefaultedComparisonSubobject { 7686 enum { CompleteObject, Member, Base } Kind; 7687 NamedDecl *Decl; 7688 SourceLocation Loc; 7689 }; 7690 7691 /// A visitor over the notional body of a defaulted comparison that determines 7692 /// whether that body would be deleted or constexpr. 7693 class DefaultedComparisonAnalyzer 7694 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7695 DefaultedComparisonInfo, 7696 DefaultedComparisonInfo, 7697 DefaultedComparisonSubobject> { 7698 public: 7699 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7700 7701 private: 7702 DiagnosticKind Diagnose; 7703 7704 public: 7705 using Base = DefaultedComparisonVisitor; 7706 using Result = DefaultedComparisonInfo; 7707 using Subobject = DefaultedComparisonSubobject; 7708 7709 friend Base; 7710 7711 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7712 DefaultedComparisonKind DCK, 7713 DiagnosticKind Diagnose = NoDiagnostics) 7714 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7715 7716 Result visit() { 7717 if ((DCK == DefaultedComparisonKind::Equal || 7718 DCK == DefaultedComparisonKind::ThreeWay) && 7719 RD->hasVariantMembers()) { 7720 // C++2a [class.compare.default]p2 [P2002R0]: 7721 // A defaulted comparison operator function for class C is defined as 7722 // deleted if [...] C has variant members. 7723 if (Diagnose == ExplainDeleted) { 7724 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7725 << FD << RD->isUnion() << RD; 7726 } 7727 return Result::deleted(); 7728 } 7729 7730 return Base::visit(); 7731 } 7732 7733 private: 7734 Subobject getCompleteObject() { 7735 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()}; 7736 } 7737 7738 Subobject getBase(CXXBaseSpecifier *Base) { 7739 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7740 Base->getBaseTypeLoc()}; 7741 } 7742 7743 Subobject getField(FieldDecl *Field) { 7744 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7745 } 7746 7747 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7748 // C++2a [class.compare.default]p2 [P2002R0]: 7749 // A defaulted <=> or == operator function for class C is defined as 7750 // deleted if any non-static data member of C is of reference type 7751 if (Type->isReferenceType()) { 7752 if (Diagnose == ExplainDeleted) { 7753 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7754 << FD << RD; 7755 } 7756 return Result::deleted(); 7757 } 7758 7759 // [...] Let xi be an lvalue denoting the ith element [...] 7760 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7761 Expr *Args[] = {&Xi, &Xi}; 7762 7763 // All operators start by trying to apply that same operator recursively. 7764 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7765 assert(OO != OO_None && "not an overloaded operator!"); 7766 return visitBinaryOperator(OO, Args, Subobj); 7767 } 7768 7769 Result 7770 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7771 Subobject Subobj, 7772 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7773 // Note that there is no need to consider rewritten candidates here if 7774 // we've already found there is no viable 'operator<=>' candidate (and are 7775 // considering synthesizing a '<=>' from '==' and '<'). 7776 OverloadCandidateSet CandidateSet( 7777 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7778 OverloadCandidateSet::OperatorRewriteInfo( 7779 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7780 7781 /// C++2a [class.compare.default]p1 [P2002R0]: 7782 /// [...] the defaulted function itself is never a candidate for overload 7783 /// resolution [...] 7784 CandidateSet.exclude(FD); 7785 7786 if (Args[0]->getType()->isOverloadableType()) 7787 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7788 else 7789 // FIXME: We determine whether this is a valid expression by checking to 7790 // see if there's a viable builtin operator candidate for it. That isn't 7791 // really what the rules ask us to do, but should give the right results. 7792 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet); 7793 7794 Result R; 7795 7796 OverloadCandidateSet::iterator Best; 7797 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7798 case OR_Success: { 7799 // C++2a [class.compare.secondary]p2 [P2002R0]: 7800 // The operator function [...] is defined as deleted if [...] the 7801 // candidate selected by overload resolution is not a rewritten 7802 // candidate. 7803 if ((DCK == DefaultedComparisonKind::NotEqual || 7804 DCK == DefaultedComparisonKind::Relational) && 7805 !Best->RewriteKind) { 7806 if (Diagnose == ExplainDeleted) { 7807 if (Best->Function) { 7808 S.Diag(Best->Function->getLocation(), 7809 diag::note_defaulted_comparison_not_rewritten_callee) 7810 << FD; 7811 } else { 7812 assert(Best->Conversions.size() == 2 && 7813 Best->Conversions[0].isUserDefined() && 7814 "non-user-defined conversion from class to built-in " 7815 "comparison"); 7816 S.Diag(Best->Conversions[0] 7817 .UserDefined.FoundConversionFunction.getDecl() 7818 ->getLocation(), 7819 diag::note_defaulted_comparison_not_rewritten_conversion) 7820 << FD; 7821 } 7822 } 7823 return Result::deleted(); 7824 } 7825 7826 // Throughout C++2a [class.compare]: if overload resolution does not 7827 // result in a usable function, the candidate function is defined as 7828 // deleted. This requires that we selected an accessible function. 7829 // 7830 // Note that this only considers the access of the function when named 7831 // within the type of the subobject, and not the access path for any 7832 // derived-to-base conversion. 7833 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7834 if (ArgClass && Best->FoundDecl.getDecl() && 7835 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7836 QualType ObjectType = Subobj.Kind == Subobject::Member 7837 ? Args[0]->getType() 7838 : S.Context.getRecordType(RD); 7839 if (!S.isMemberAccessibleForDeletion( 7840 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7841 Diagnose == ExplainDeleted 7842 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7843 << FD << Subobj.Kind << Subobj.Decl 7844 : S.PDiag())) 7845 return Result::deleted(); 7846 } 7847 7848 bool NeedsDeducing = 7849 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType(); 7850 7851 if (FunctionDecl *BestFD = Best->Function) { 7852 // C++2a [class.compare.default]p3 [P2002R0]: 7853 // A defaulted comparison function is constexpr-compatible if 7854 // [...] no overlod resolution performed [...] results in a 7855 // non-constexpr function. 7856 assert(!BestFD->isDeleted() && "wrong overload resolution result"); 7857 // If it's not constexpr, explain why not. 7858 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 7859 if (Subobj.Kind != Subobject::CompleteObject) 7860 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7861 << Subobj.Kind << Subobj.Decl; 7862 S.Diag(BestFD->getLocation(), 7863 diag::note_defaulted_comparison_not_constexpr_here); 7864 // Bail out after explaining; we don't want any more notes. 7865 return Result::deleted(); 7866 } 7867 R.Constexpr &= BestFD->isConstexpr(); 7868 7869 if (NeedsDeducing) { 7870 // If any callee has an undeduced return type, deduce it now. 7871 // FIXME: It's not clear how a failure here should be handled. For 7872 // now, we produce an eager diagnostic, because that is forward 7873 // compatible with most (all?) other reasonable options. 7874 if (BestFD->getReturnType()->isUndeducedType() && 7875 S.DeduceReturnType(BestFD, FD->getLocation(), 7876 /*Diagnose=*/false)) { 7877 // Don't produce a duplicate error when asked to explain why the 7878 // comparison is deleted: we diagnosed that when initially checking 7879 // the defaulted operator. 7880 if (Diagnose == NoDiagnostics) { 7881 S.Diag( 7882 FD->getLocation(), 7883 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) 7884 << Subobj.Kind << Subobj.Decl; 7885 S.Diag( 7886 Subobj.Loc, 7887 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) 7888 << Subobj.Kind << Subobj.Decl; 7889 S.Diag(BestFD->getLocation(), 7890 diag::note_defaulted_comparison_cannot_deduce_callee) 7891 << Subobj.Kind << Subobj.Decl; 7892 } 7893 return Result::deleted(); 7894 } 7895 auto *Info = S.Context.CompCategories.lookupInfoForType( 7896 BestFD->getCallResultType()); 7897 if (!Info) { 7898 if (Diagnose == ExplainDeleted) { 7899 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 7900 << Subobj.Kind << Subobj.Decl 7901 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 7902 S.Diag(BestFD->getLocation(), 7903 diag::note_defaulted_comparison_cannot_deduce_callee) 7904 << Subobj.Kind << Subobj.Decl; 7905 } 7906 return Result::deleted(); 7907 } 7908 R.Category = Info->Kind; 7909 } 7910 } else { 7911 QualType T = Best->BuiltinParamTypes[0]; 7912 assert(T == Best->BuiltinParamTypes[1] && 7913 "builtin comparison for different types?"); 7914 assert(Best->BuiltinParamTypes[2].isNull() && 7915 "invalid builtin comparison"); 7916 7917 if (NeedsDeducing) { 7918 Optional<ComparisonCategoryType> Cat = 7919 getComparisonCategoryForBuiltinCmp(T); 7920 assert(Cat && "no category for builtin comparison?"); 7921 R.Category = *Cat; 7922 } 7923 } 7924 7925 // Note that we might be rewriting to a different operator. That call is 7926 // not considered until we come to actually build the comparison function. 7927 break; 7928 } 7929 7930 case OR_Ambiguous: 7931 if (Diagnose == ExplainDeleted) { 7932 unsigned Kind = 0; 7933 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 7934 Kind = OO == OO_EqualEqual ? 1 : 2; 7935 CandidateSet.NoteCandidates( 7936 PartialDiagnosticAt( 7937 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 7938 << FD << Kind << Subobj.Kind << Subobj.Decl), 7939 S, OCD_AmbiguousCandidates, Args); 7940 } 7941 R = Result::deleted(); 7942 break; 7943 7944 case OR_Deleted: 7945 if (Diagnose == ExplainDeleted) { 7946 if ((DCK == DefaultedComparisonKind::NotEqual || 7947 DCK == DefaultedComparisonKind::Relational) && 7948 !Best->RewriteKind) { 7949 S.Diag(Best->Function->getLocation(), 7950 diag::note_defaulted_comparison_not_rewritten_callee) 7951 << FD; 7952 } else { 7953 S.Diag(Subobj.Loc, 7954 diag::note_defaulted_comparison_calls_deleted) 7955 << FD << Subobj.Kind << Subobj.Decl; 7956 S.NoteDeletedFunction(Best->Function); 7957 } 7958 } 7959 R = Result::deleted(); 7960 break; 7961 7962 case OR_No_Viable_Function: 7963 // If there's no usable candidate, we're done unless we can rewrite a 7964 // '<=>' in terms of '==' and '<'. 7965 if (OO == OO_Spaceship && 7966 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 7967 // For any kind of comparison category return type, we need a usable 7968 // '==' and a usable '<'. 7969 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 7970 &CandidateSet))) 7971 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 7972 break; 7973 } 7974 7975 if (Diagnose == ExplainDeleted) { 7976 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 7977 << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl; 7978 7979 // For a three-way comparison, list both the candidates for the 7980 // original operator and the candidates for the synthesized operator. 7981 if (SpaceshipCandidates) { 7982 SpaceshipCandidates->NoteCandidates( 7983 S, Args, 7984 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 7985 Args, FD->getLocation())); 7986 S.Diag(Subobj.Loc, 7987 diag::note_defaulted_comparison_no_viable_function_synthesized) 7988 << (OO == OO_EqualEqual ? 0 : 1); 7989 } 7990 7991 CandidateSet.NoteCandidates( 7992 S, Args, 7993 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 7994 FD->getLocation())); 7995 } 7996 R = Result::deleted(); 7997 break; 7998 } 7999 8000 return R; 8001 } 8002 }; 8003 8004 /// A list of statements. 8005 struct StmtListResult { 8006 bool IsInvalid = false; 8007 llvm::SmallVector<Stmt*, 16> Stmts; 8008 8009 bool add(const StmtResult &S) { 8010 IsInvalid |= S.isInvalid(); 8011 if (IsInvalid) 8012 return true; 8013 Stmts.push_back(S.get()); 8014 return false; 8015 } 8016 }; 8017 8018 /// A visitor over the notional body of a defaulted comparison that synthesizes 8019 /// the actual body. 8020 class DefaultedComparisonSynthesizer 8021 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 8022 StmtListResult, StmtResult, 8023 std::pair<ExprResult, ExprResult>> { 8024 SourceLocation Loc; 8025 unsigned ArrayDepth = 0; 8026 8027 public: 8028 using Base = DefaultedComparisonVisitor; 8029 using ExprPair = std::pair<ExprResult, ExprResult>; 8030 8031 friend Base; 8032 8033 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 8034 DefaultedComparisonKind DCK, 8035 SourceLocation BodyLoc) 8036 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 8037 8038 /// Build a suitable function body for this defaulted comparison operator. 8039 StmtResult build() { 8040 Sema::CompoundScopeRAII CompoundScope(S); 8041 8042 StmtListResult Stmts = visit(); 8043 if (Stmts.IsInvalid) 8044 return StmtError(); 8045 8046 ExprResult RetVal; 8047 switch (DCK) { 8048 case DefaultedComparisonKind::None: 8049 llvm_unreachable("not a defaulted comparison"); 8050 8051 case DefaultedComparisonKind::Equal: { 8052 // C++2a [class.eq]p3: 8053 // [...] compar[e] the corresponding elements [...] until the first 8054 // index i where xi == yi yields [...] false. If no such index exists, 8055 // V is true. Otherwise, V is false. 8056 // 8057 // Join the comparisons with '&&'s and return the result. Use a right 8058 // fold (traversing the conditions right-to-left), because that 8059 // short-circuits more naturally. 8060 auto OldStmts = std::move(Stmts.Stmts); 8061 Stmts.Stmts.clear(); 8062 ExprResult CmpSoFar; 8063 // Finish a particular comparison chain. 8064 auto FinishCmp = [&] { 8065 if (Expr *Prior = CmpSoFar.get()) { 8066 // Convert the last expression to 'return ...;' 8067 if (RetVal.isUnset() && Stmts.Stmts.empty()) 8068 RetVal = CmpSoFar; 8069 // Convert any prior comparison to 'if (!(...)) return false;' 8070 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 8071 return true; 8072 CmpSoFar = ExprResult(); 8073 } 8074 return false; 8075 }; 8076 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 8077 Expr *E = dyn_cast<Expr>(EAsStmt); 8078 if (!E) { 8079 // Found an array comparison. 8080 if (FinishCmp() || Stmts.add(EAsStmt)) 8081 return StmtError(); 8082 continue; 8083 } 8084 8085 if (CmpSoFar.isUnset()) { 8086 CmpSoFar = E; 8087 continue; 8088 } 8089 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 8090 if (CmpSoFar.isInvalid()) 8091 return StmtError(); 8092 } 8093 if (FinishCmp()) 8094 return StmtError(); 8095 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 8096 // If no such index exists, V is true. 8097 if (RetVal.isUnset()) 8098 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 8099 break; 8100 } 8101 8102 case DefaultedComparisonKind::ThreeWay: { 8103 // Per C++2a [class.spaceship]p3, as a fallback add: 8104 // return static_cast<R>(std::strong_ordering::equal); 8105 QualType StrongOrdering = S.CheckComparisonCategoryType( 8106 ComparisonCategoryType::StrongOrdering, Loc, 8107 Sema::ComparisonCategoryUsage::DefaultedOperator); 8108 if (StrongOrdering.isNull()) 8109 return StmtError(); 8110 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 8111 .getValueInfo(ComparisonCategoryResult::Equal) 8112 ->VD; 8113 RetVal = getDecl(EqualVD); 8114 if (RetVal.isInvalid()) 8115 return StmtError(); 8116 RetVal = buildStaticCastToR(RetVal.get()); 8117 break; 8118 } 8119 8120 case DefaultedComparisonKind::NotEqual: 8121 case DefaultedComparisonKind::Relational: 8122 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 8123 break; 8124 } 8125 8126 // Build the final return statement. 8127 if (RetVal.isInvalid()) 8128 return StmtError(); 8129 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 8130 if (ReturnStmt.isInvalid()) 8131 return StmtError(); 8132 Stmts.Stmts.push_back(ReturnStmt.get()); 8133 8134 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 8135 } 8136 8137 private: 8138 ExprResult getDecl(ValueDecl *VD) { 8139 return S.BuildDeclarationNameExpr( 8140 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 8141 } 8142 8143 ExprResult getParam(unsigned I) { 8144 ParmVarDecl *PD = FD->getParamDecl(I); 8145 return getDecl(PD); 8146 } 8147 8148 ExprPair getCompleteObject() { 8149 unsigned Param = 0; 8150 ExprResult LHS; 8151 if (isa<CXXMethodDecl>(FD)) { 8152 // LHS is '*this'. 8153 LHS = S.ActOnCXXThis(Loc); 8154 if (!LHS.isInvalid()) 8155 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 8156 } else { 8157 LHS = getParam(Param++); 8158 } 8159 ExprResult RHS = getParam(Param++); 8160 assert(Param == FD->getNumParams()); 8161 return {LHS, RHS}; 8162 } 8163 8164 ExprPair getBase(CXXBaseSpecifier *Base) { 8165 ExprPair Obj = getCompleteObject(); 8166 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8167 return {ExprError(), ExprError()}; 8168 CXXCastPath Path = {Base}; 8169 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 8170 CK_DerivedToBase, VK_LValue, &Path), 8171 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 8172 CK_DerivedToBase, VK_LValue, &Path)}; 8173 } 8174 8175 ExprPair getField(FieldDecl *Field) { 8176 ExprPair Obj = getCompleteObject(); 8177 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8178 return {ExprError(), ExprError()}; 8179 8180 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 8181 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 8182 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 8183 CXXScopeSpec(), Field, Found, NameInfo), 8184 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 8185 CXXScopeSpec(), Field, Found, NameInfo)}; 8186 } 8187 8188 // FIXME: When expanding a subobject, register a note in the code synthesis 8189 // stack to say which subobject we're comparing. 8190 8191 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 8192 if (Cond.isInvalid()) 8193 return StmtError(); 8194 8195 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 8196 if (NotCond.isInvalid()) 8197 return StmtError(); 8198 8199 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 8200 assert(!False.isInvalid() && "should never fail"); 8201 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 8202 if (ReturnFalse.isInvalid()) 8203 return StmtError(); 8204 8205 return S.ActOnIfStmt(Loc, false, Loc, nullptr, 8206 S.ActOnCondition(nullptr, Loc, NotCond.get(), 8207 Sema::ConditionKind::Boolean), 8208 Loc, ReturnFalse.get(), SourceLocation(), nullptr); 8209 } 8210 8211 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 8212 ExprPair Subobj) { 8213 QualType SizeType = S.Context.getSizeType(); 8214 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 8215 8216 // Build 'size_t i$n = 0'. 8217 IdentifierInfo *IterationVarName = nullptr; 8218 { 8219 SmallString<8> Str; 8220 llvm::raw_svector_ostream OS(Str); 8221 OS << "i" << ArrayDepth; 8222 IterationVarName = &S.Context.Idents.get(OS.str()); 8223 } 8224 VarDecl *IterationVar = VarDecl::Create( 8225 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 8226 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 8227 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8228 IterationVar->setInit( 8229 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8230 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 8231 8232 auto IterRef = [&] { 8233 ExprResult Ref = S.BuildDeclarationNameExpr( 8234 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 8235 IterationVar); 8236 assert(!Ref.isInvalid() && "can't reference our own variable?"); 8237 return Ref.get(); 8238 }; 8239 8240 // Build 'i$n != Size'. 8241 ExprResult Cond = S.CreateBuiltinBinOp( 8242 Loc, BO_NE, IterRef(), 8243 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 8244 assert(!Cond.isInvalid() && "should never fail"); 8245 8246 // Build '++i$n'. 8247 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 8248 assert(!Inc.isInvalid() && "should never fail"); 8249 8250 // Build 'a[i$n]' and 'b[i$n]'. 8251 auto Index = [&](ExprResult E) { 8252 if (E.isInvalid()) 8253 return ExprError(); 8254 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 8255 }; 8256 Subobj.first = Index(Subobj.first); 8257 Subobj.second = Index(Subobj.second); 8258 8259 // Compare the array elements. 8260 ++ArrayDepth; 8261 StmtResult Substmt = visitSubobject(Type, Subobj); 8262 --ArrayDepth; 8263 8264 if (Substmt.isInvalid()) 8265 return StmtError(); 8266 8267 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 8268 // For outer levels or for an 'operator<=>' we already have a suitable 8269 // statement that returns as necessary. 8270 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 8271 assert(DCK == DefaultedComparisonKind::Equal && 8272 "should have non-expression statement"); 8273 Substmt = buildIfNotCondReturnFalse(ElemCmp); 8274 if (Substmt.isInvalid()) 8275 return StmtError(); 8276 } 8277 8278 // Build 'for (...) ...' 8279 return S.ActOnForStmt(Loc, Loc, Init, 8280 S.ActOnCondition(nullptr, Loc, Cond.get(), 8281 Sema::ConditionKind::Boolean), 8282 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 8283 Substmt.get()); 8284 } 8285 8286 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 8287 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8288 return StmtError(); 8289 8290 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 8291 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); 8292 ExprResult Op; 8293 if (Type->isOverloadableType()) 8294 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(), 8295 Obj.second.get(), /*PerformADL=*/true, 8296 /*AllowRewrittenCandidates=*/true, FD); 8297 else 8298 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get()); 8299 if (Op.isInvalid()) 8300 return StmtError(); 8301 8302 switch (DCK) { 8303 case DefaultedComparisonKind::None: 8304 llvm_unreachable("not a defaulted comparison"); 8305 8306 case DefaultedComparisonKind::Equal: 8307 // Per C++2a [class.eq]p2, each comparison is individually contextually 8308 // converted to bool. 8309 Op = S.PerformContextuallyConvertToBool(Op.get()); 8310 if (Op.isInvalid()) 8311 return StmtError(); 8312 return Op.get(); 8313 8314 case DefaultedComparisonKind::ThreeWay: { 8315 // Per C++2a [class.spaceship]p3, form: 8316 // if (R cmp = static_cast<R>(op); cmp != 0) 8317 // return cmp; 8318 QualType R = FD->getReturnType(); 8319 Op = buildStaticCastToR(Op.get()); 8320 if (Op.isInvalid()) 8321 return StmtError(); 8322 8323 // R cmp = ...; 8324 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 8325 VarDecl *VD = 8326 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 8327 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 8328 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 8329 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 8330 8331 // cmp != 0 8332 ExprResult VDRef = getDecl(VD); 8333 if (VDRef.isInvalid()) 8334 return StmtError(); 8335 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 8336 Expr *Zero = 8337 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 8338 ExprResult Comp; 8339 if (VDRef.get()->getType()->isOverloadableType()) 8340 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true, 8341 true, FD); 8342 else 8343 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero); 8344 if (Comp.isInvalid()) 8345 return StmtError(); 8346 Sema::ConditionResult Cond = S.ActOnCondition( 8347 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 8348 if (Cond.isInvalid()) 8349 return StmtError(); 8350 8351 // return cmp; 8352 VDRef = getDecl(VD); 8353 if (VDRef.isInvalid()) 8354 return StmtError(); 8355 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 8356 if (ReturnStmt.isInvalid()) 8357 return StmtError(); 8358 8359 // if (...) 8360 return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc, 8361 ReturnStmt.get(), 8362 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr); 8363 } 8364 8365 case DefaultedComparisonKind::NotEqual: 8366 case DefaultedComparisonKind::Relational: 8367 // C++2a [class.compare.secondary]p2: 8368 // Otherwise, the operator function yields x @ y. 8369 return Op.get(); 8370 } 8371 llvm_unreachable(""); 8372 } 8373 8374 /// Build "static_cast<R>(E)". 8375 ExprResult buildStaticCastToR(Expr *E) { 8376 QualType R = FD->getReturnType(); 8377 assert(!R->isUndeducedType() && "type should have been deduced already"); 8378 8379 // Don't bother forming a no-op cast in the common case. 8380 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R)) 8381 return E; 8382 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 8383 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 8384 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 8385 } 8386 }; 8387 } 8388 8389 /// Perform the unqualified lookups that might be needed to form a defaulted 8390 /// comparison function for the given operator. 8391 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 8392 UnresolvedSetImpl &Operators, 8393 OverloadedOperatorKind Op) { 8394 auto Lookup = [&](OverloadedOperatorKind OO) { 8395 Self.LookupOverloadedOperatorName(OO, S, Operators); 8396 }; 8397 8398 // Every defaulted operator looks up itself. 8399 Lookup(Op); 8400 // ... and the rewritten form of itself, if any. 8401 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 8402 Lookup(ExtraOp); 8403 8404 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 8405 // synthesize a three-way comparison from '<' and '=='. In a dependent 8406 // context, we also need to look up '==' in case we implicitly declare a 8407 // defaulted 'operator=='. 8408 if (Op == OO_Spaceship) { 8409 Lookup(OO_ExclaimEqual); 8410 Lookup(OO_Less); 8411 Lookup(OO_EqualEqual); 8412 } 8413 } 8414 8415 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 8416 DefaultedComparisonKind DCK) { 8417 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison"); 8418 8419 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 8420 assert(RD && "defaulted comparison is not defaulted in a class"); 8421 8422 // Perform any unqualified lookups we're going to need to default this 8423 // function. 8424 if (S) { 8425 UnresolvedSet<32> Operators; 8426 lookupOperatorsForDefaultedComparison(*this, S, Operators, 8427 FD->getOverloadedOperator()); 8428 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 8429 Context, Operators.pairs())); 8430 } 8431 8432 // C++2a [class.compare.default]p1: 8433 // A defaulted comparison operator function for some class C shall be a 8434 // non-template function declared in the member-specification of C that is 8435 // -- a non-static const member of C having one parameter of type 8436 // const C&, or 8437 // -- a friend of C having two parameters of type const C& or two 8438 // parameters of type C. 8439 QualType ExpectedParmType1 = Context.getRecordType(RD); 8440 QualType ExpectedParmType2 = 8441 Context.getLValueReferenceType(ExpectedParmType1.withConst()); 8442 if (isa<CXXMethodDecl>(FD)) 8443 ExpectedParmType1 = ExpectedParmType2; 8444 for (const ParmVarDecl *Param : FD->parameters()) { 8445 if (!Param->getType()->isDependentType() && 8446 !Context.hasSameType(Param->getType(), ExpectedParmType1) && 8447 !Context.hasSameType(Param->getType(), ExpectedParmType2)) { 8448 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8449 // corresponding defaulted 'operator<=>' already. 8450 if (!FD->isImplicit()) { 8451 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 8452 << (int)DCK << Param->getType() << ExpectedParmType1 8453 << !isa<CXXMethodDecl>(FD) 8454 << ExpectedParmType2 << Param->getSourceRange(); 8455 } 8456 return true; 8457 } 8458 } 8459 if (FD->getNumParams() == 2 && 8460 !Context.hasSameType(FD->getParamDecl(0)->getType(), 8461 FD->getParamDecl(1)->getType())) { 8462 if (!FD->isImplicit()) { 8463 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 8464 << (int)DCK 8465 << FD->getParamDecl(0)->getType() 8466 << FD->getParamDecl(0)->getSourceRange() 8467 << FD->getParamDecl(1)->getType() 8468 << FD->getParamDecl(1)->getSourceRange(); 8469 } 8470 return true; 8471 } 8472 8473 // ... non-static const member ... 8474 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 8475 assert(!MD->isStatic() && "comparison function cannot be a static member"); 8476 if (!MD->isConst()) { 8477 SourceLocation InsertLoc; 8478 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 8479 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 8480 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8481 // corresponding defaulted 'operator<=>' already. 8482 if (!MD->isImplicit()) { 8483 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 8484 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 8485 } 8486 8487 // Add the 'const' to the type to recover. 8488 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 8489 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8490 EPI.TypeQuals.addConst(); 8491 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8492 FPT->getParamTypes(), EPI)); 8493 } 8494 } else { 8495 // A non-member function declared in a class must be a friend. 8496 assert(FD->getFriendObjectKind() && "expected a friend declaration"); 8497 } 8498 8499 // C++2a [class.eq]p1, [class.rel]p1: 8500 // A [defaulted comparison other than <=>] shall have a declared return 8501 // type bool. 8502 if (DCK != DefaultedComparisonKind::ThreeWay && 8503 !FD->getDeclaredReturnType()->isDependentType() && 8504 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8505 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8506 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8507 << FD->getReturnTypeSourceRange(); 8508 return true; 8509 } 8510 // C++2a [class.spaceship]p2 [P2002R0]: 8511 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8512 // R shall not contain a placeholder type. 8513 if (DCK == DefaultedComparisonKind::ThreeWay && 8514 FD->getDeclaredReturnType()->getContainedDeducedType() && 8515 !Context.hasSameType(FD->getDeclaredReturnType(), 8516 Context.getAutoDeductType())) { 8517 Diag(FD->getLocation(), 8518 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8519 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8520 << FD->getReturnTypeSourceRange(); 8521 return true; 8522 } 8523 8524 // For a defaulted function in a dependent class, defer all remaining checks 8525 // until instantiation. 8526 if (RD->isDependentType()) 8527 return false; 8528 8529 // Determine whether the function should be defined as deleted. 8530 DefaultedComparisonInfo Info = 8531 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8532 8533 bool First = FD == FD->getCanonicalDecl(); 8534 8535 // If we want to delete the function, then do so; there's nothing else to 8536 // check in that case. 8537 if (Info.Deleted) { 8538 if (!First) { 8539 // C++11 [dcl.fct.def.default]p4: 8540 // [For a] user-provided explicitly-defaulted function [...] if such a 8541 // function is implicitly defined as deleted, the program is ill-formed. 8542 // 8543 // This is really just a consequence of the general rule that you can 8544 // only delete a function on its first declaration. 8545 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8546 << FD->isImplicit() << (int)DCK; 8547 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8548 DefaultedComparisonAnalyzer::ExplainDeleted) 8549 .visit(); 8550 return true; 8551 } 8552 8553 SetDeclDeleted(FD, FD->getLocation()); 8554 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8555 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8556 << (int)DCK; 8557 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8558 DefaultedComparisonAnalyzer::ExplainDeleted) 8559 .visit(); 8560 } 8561 return false; 8562 } 8563 8564 // C++2a [class.spaceship]p2: 8565 // The return type is deduced as the common comparison type of R0, R1, ... 8566 if (DCK == DefaultedComparisonKind::ThreeWay && 8567 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8568 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8569 if (RetLoc.isInvalid()) 8570 RetLoc = FD->getBeginLoc(); 8571 // FIXME: Should we really care whether we have the complete type and the 8572 // 'enumerator' constants here? A forward declaration seems sufficient. 8573 QualType Cat = CheckComparisonCategoryType( 8574 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8575 if (Cat.isNull()) 8576 return true; 8577 Context.adjustDeducedFunctionResultType( 8578 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8579 } 8580 8581 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8582 // An explicitly-defaulted function that is not defined as deleted may be 8583 // declared constexpr or consteval only if it is constexpr-compatible. 8584 // C++2a [class.compare.default]p3 [P2002R0]: 8585 // A defaulted comparison function is constexpr-compatible if it satisfies 8586 // the requirements for a constexpr function [...] 8587 // The only relevant requirements are that the parameter and return types are 8588 // literal types. The remaining conditions are checked by the analyzer. 8589 if (FD->isConstexpr()) { 8590 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8591 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8592 !Info.Constexpr) { 8593 Diag(FD->getBeginLoc(), 8594 diag::err_incorrect_defaulted_comparison_constexpr) 8595 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8596 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8597 DefaultedComparisonAnalyzer::ExplainConstexpr) 8598 .visit(); 8599 } 8600 } 8601 8602 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8603 // If a constexpr-compatible function is explicitly defaulted on its first 8604 // declaration, it is implicitly considered to be constexpr. 8605 // FIXME: Only applying this to the first declaration seems problematic, as 8606 // simple reorderings can affect the meaning of the program. 8607 if (First && !FD->isConstexpr() && Info.Constexpr) 8608 FD->setConstexprKind(ConstexprSpecKind::Constexpr); 8609 8610 // C++2a [except.spec]p3: 8611 // If a declaration of a function does not have a noexcept-specifier 8612 // [and] is defaulted on its first declaration, [...] the exception 8613 // specification is as specified below 8614 if (FD->getExceptionSpecType() == EST_None) { 8615 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8616 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8617 EPI.ExceptionSpec.Type = EST_Unevaluated; 8618 EPI.ExceptionSpec.SourceDecl = FD; 8619 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8620 FPT->getParamTypes(), EPI)); 8621 } 8622 8623 return false; 8624 } 8625 8626 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8627 FunctionDecl *Spaceship) { 8628 Sema::CodeSynthesisContext Ctx; 8629 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8630 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8631 Ctx.Entity = Spaceship; 8632 pushCodeSynthesisContext(Ctx); 8633 8634 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8635 EqualEqual->setImplicit(); 8636 8637 popCodeSynthesisContext(); 8638 } 8639 8640 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8641 DefaultedComparisonKind DCK) { 8642 assert(FD->isDefaulted() && !FD->isDeleted() && 8643 !FD->doesThisDeclarationHaveABody()); 8644 if (FD->willHaveBody() || FD->isInvalidDecl()) 8645 return; 8646 8647 SynthesizedFunctionScope Scope(*this, FD); 8648 8649 // Add a context note for diagnostics produced after this point. 8650 Scope.addContextNote(UseLoc); 8651 8652 { 8653 // Build and set up the function body. 8654 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8655 SourceLocation BodyLoc = 8656 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8657 StmtResult Body = 8658 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8659 if (Body.isInvalid()) { 8660 FD->setInvalidDecl(); 8661 return; 8662 } 8663 FD->setBody(Body.get()); 8664 FD->markUsed(Context); 8665 } 8666 8667 // The exception specification is needed because we are defining the 8668 // function. Note that this will reuse the body we just built. 8669 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8670 8671 if (ASTMutationListener *L = getASTMutationListener()) 8672 L->CompletedImplicitDefinition(FD); 8673 } 8674 8675 static Sema::ImplicitExceptionSpecification 8676 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8677 FunctionDecl *FD, 8678 Sema::DefaultedComparisonKind DCK) { 8679 ComputingExceptionSpec CES(S, FD, Loc); 8680 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8681 8682 if (FD->isInvalidDecl()) 8683 return ExceptSpec; 8684 8685 // The common case is that we just defined the comparison function. In that 8686 // case, just look at whether the body can throw. 8687 if (FD->hasBody()) { 8688 ExceptSpec.CalledStmt(FD->getBody()); 8689 } else { 8690 // Otherwise, build a body so we can check it. This should ideally only 8691 // happen when we're not actually marking the function referenced. (This is 8692 // only really important for efficiency: we don't want to build and throw 8693 // away bodies for comparison functions more than we strictly need to.) 8694 8695 // Pretend to synthesize the function body in an unevaluated context. 8696 // Note that we can't actually just go ahead and define the function here: 8697 // we are not permitted to mark its callees as referenced. 8698 Sema::SynthesizedFunctionScope Scope(S, FD); 8699 EnterExpressionEvaluationContext Context( 8700 S, Sema::ExpressionEvaluationContext::Unevaluated); 8701 8702 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8703 SourceLocation BodyLoc = 8704 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8705 StmtResult Body = 8706 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8707 if (!Body.isInvalid()) 8708 ExceptSpec.CalledStmt(Body.get()); 8709 8710 // FIXME: Can we hold onto this body and just transform it to potentially 8711 // evaluated when we're asked to define the function rather than rebuilding 8712 // it? Either that, or we should only build the bits of the body that we 8713 // need (the expressions, not the statements). 8714 } 8715 8716 return ExceptSpec; 8717 } 8718 8719 void Sema::CheckDelayedMemberExceptionSpecs() { 8720 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8721 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8722 8723 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8724 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8725 8726 // Perform any deferred checking of exception specifications for virtual 8727 // destructors. 8728 for (auto &Check : Overriding) 8729 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8730 8731 // Perform any deferred checking of exception specifications for befriended 8732 // special members. 8733 for (auto &Check : Equivalent) 8734 CheckEquivalentExceptionSpec(Check.second, Check.first); 8735 } 8736 8737 namespace { 8738 /// CRTP base class for visiting operations performed by a special member 8739 /// function (or inherited constructor). 8740 template<typename Derived> 8741 struct SpecialMemberVisitor { 8742 Sema &S; 8743 CXXMethodDecl *MD; 8744 Sema::CXXSpecialMember CSM; 8745 Sema::InheritedConstructorInfo *ICI; 8746 8747 // Properties of the special member, computed for convenience. 8748 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8749 8750 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8751 Sema::InheritedConstructorInfo *ICI) 8752 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8753 switch (CSM) { 8754 case Sema::CXXDefaultConstructor: 8755 case Sema::CXXCopyConstructor: 8756 case Sema::CXXMoveConstructor: 8757 IsConstructor = true; 8758 break; 8759 case Sema::CXXCopyAssignment: 8760 case Sema::CXXMoveAssignment: 8761 IsAssignment = true; 8762 break; 8763 case Sema::CXXDestructor: 8764 break; 8765 case Sema::CXXInvalid: 8766 llvm_unreachable("invalid special member kind"); 8767 } 8768 8769 if (MD->getNumParams()) { 8770 if (const ReferenceType *RT = 8771 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8772 ConstArg = RT->getPointeeType().isConstQualified(); 8773 } 8774 } 8775 8776 Derived &getDerived() { return static_cast<Derived&>(*this); } 8777 8778 /// Is this a "move" special member? 8779 bool isMove() const { 8780 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8781 } 8782 8783 /// Look up the corresponding special member in the given class. 8784 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8785 unsigned Quals, bool IsMutable) { 8786 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8787 ConstArg && !IsMutable); 8788 } 8789 8790 /// Look up the constructor for the specified base class to see if it's 8791 /// overridden due to this being an inherited constructor. 8792 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8793 if (!ICI) 8794 return {}; 8795 assert(CSM == Sema::CXXDefaultConstructor); 8796 auto *BaseCtor = 8797 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8798 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8799 return MD; 8800 return {}; 8801 } 8802 8803 /// A base or member subobject. 8804 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8805 8806 /// Get the location to use for a subobject in diagnostics. 8807 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8808 // FIXME: For an indirect virtual base, the direct base leading to 8809 // the indirect virtual base would be a more useful choice. 8810 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8811 return B->getBaseTypeLoc(); 8812 else 8813 return Subobj.get<FieldDecl*>()->getLocation(); 8814 } 8815 8816 enum BasesToVisit { 8817 /// Visit all non-virtual (direct) bases. 8818 VisitNonVirtualBases, 8819 /// Visit all direct bases, virtual or not. 8820 VisitDirectBases, 8821 /// Visit all non-virtual bases, and all virtual bases if the class 8822 /// is not abstract. 8823 VisitPotentiallyConstructedBases, 8824 /// Visit all direct or virtual bases. 8825 VisitAllBases 8826 }; 8827 8828 // Visit the bases and members of the class. 8829 bool visit(BasesToVisit Bases) { 8830 CXXRecordDecl *RD = MD->getParent(); 8831 8832 if (Bases == VisitPotentiallyConstructedBases) 8833 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8834 8835 for (auto &B : RD->bases()) 8836 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8837 getDerived().visitBase(&B)) 8838 return true; 8839 8840 if (Bases == VisitAllBases) 8841 for (auto &B : RD->vbases()) 8842 if (getDerived().visitBase(&B)) 8843 return true; 8844 8845 for (auto *F : RD->fields()) 8846 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8847 getDerived().visitField(F)) 8848 return true; 8849 8850 return false; 8851 } 8852 }; 8853 } 8854 8855 namespace { 8856 struct SpecialMemberDeletionInfo 8857 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8858 bool Diagnose; 8859 8860 SourceLocation Loc; 8861 8862 bool AllFieldsAreConst; 8863 8864 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 8865 Sema::CXXSpecialMember CSM, 8866 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 8867 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 8868 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 8869 8870 bool inUnion() const { return MD->getParent()->isUnion(); } 8871 8872 Sema::CXXSpecialMember getEffectiveCSM() { 8873 return ICI ? Sema::CXXInvalid : CSM; 8874 } 8875 8876 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 8877 8878 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 8879 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 8880 8881 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 8882 bool shouldDeleteForField(FieldDecl *FD); 8883 bool shouldDeleteForAllConstMembers(); 8884 8885 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 8886 unsigned Quals); 8887 bool shouldDeleteForSubobjectCall(Subobject Subobj, 8888 Sema::SpecialMemberOverloadResult SMOR, 8889 bool IsDtorCallInCtor); 8890 8891 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 8892 }; 8893 } 8894 8895 /// Is the given special member inaccessible when used on the given 8896 /// sub-object. 8897 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 8898 CXXMethodDecl *target) { 8899 /// If we're operating on a base class, the object type is the 8900 /// type of this special member. 8901 QualType objectTy; 8902 AccessSpecifier access = target->getAccess(); 8903 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 8904 objectTy = S.Context.getTypeDeclType(MD->getParent()); 8905 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 8906 8907 // If we're operating on a field, the object type is the type of the field. 8908 } else { 8909 objectTy = S.Context.getTypeDeclType(target->getParent()); 8910 } 8911 8912 return S.isMemberAccessibleForDeletion( 8913 target->getParent(), DeclAccessPair::make(target, access), objectTy); 8914 } 8915 8916 /// Check whether we should delete a special member due to the implicit 8917 /// definition containing a call to a special member of a subobject. 8918 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 8919 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 8920 bool IsDtorCallInCtor) { 8921 CXXMethodDecl *Decl = SMOR.getMethod(); 8922 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8923 8924 int DiagKind = -1; 8925 8926 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 8927 DiagKind = !Decl ? 0 : 1; 8928 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 8929 DiagKind = 2; 8930 else if (!isAccessible(Subobj, Decl)) 8931 DiagKind = 3; 8932 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 8933 !Decl->isTrivial()) { 8934 // A member of a union must have a trivial corresponding special member. 8935 // As a weird special case, a destructor call from a union's constructor 8936 // must be accessible and non-deleted, but need not be trivial. Such a 8937 // destructor is never actually called, but is semantically checked as 8938 // if it were. 8939 DiagKind = 4; 8940 } 8941 8942 if (DiagKind == -1) 8943 return false; 8944 8945 if (Diagnose) { 8946 if (Field) { 8947 S.Diag(Field->getLocation(), 8948 diag::note_deleted_special_member_class_subobject) 8949 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 8950 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 8951 } else { 8952 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 8953 S.Diag(Base->getBeginLoc(), 8954 diag::note_deleted_special_member_class_subobject) 8955 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8956 << Base->getType() << DiagKind << IsDtorCallInCtor 8957 << /*IsObjCPtr*/false; 8958 } 8959 8960 if (DiagKind == 1) 8961 S.NoteDeletedFunction(Decl); 8962 // FIXME: Explain inaccessibility if DiagKind == 3. 8963 } 8964 8965 return true; 8966 } 8967 8968 /// Check whether we should delete a special member function due to having a 8969 /// direct or virtual base class or non-static data member of class type M. 8970 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 8971 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 8972 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8973 bool IsMutable = Field && Field->isMutable(); 8974 8975 // C++11 [class.ctor]p5: 8976 // -- any direct or virtual base class, or non-static data member with no 8977 // brace-or-equal-initializer, has class type M (or array thereof) and 8978 // either M has no default constructor or overload resolution as applied 8979 // to M's default constructor results in an ambiguity or in a function 8980 // that is deleted or inaccessible 8981 // C++11 [class.copy]p11, C++11 [class.copy]p23: 8982 // -- a direct or virtual base class B that cannot be copied/moved because 8983 // overload resolution, as applied to B's corresponding special member, 8984 // results in an ambiguity or a function that is deleted or inaccessible 8985 // from the defaulted special member 8986 // C++11 [class.dtor]p5: 8987 // -- any direct or virtual base class [...] has a type with a destructor 8988 // that is deleted or inaccessible 8989 if (!(CSM == Sema::CXXDefaultConstructor && 8990 Field && Field->hasInClassInitializer()) && 8991 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 8992 false)) 8993 return true; 8994 8995 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 8996 // -- any direct or virtual base class or non-static data member has a 8997 // type with a destructor that is deleted or inaccessible 8998 if (IsConstructor) { 8999 Sema::SpecialMemberOverloadResult SMOR = 9000 S.LookupSpecialMember(Class, Sema::CXXDestructor, 9001 false, false, false, false, false); 9002 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 9003 return true; 9004 } 9005 9006 return false; 9007 } 9008 9009 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 9010 FieldDecl *FD, QualType FieldType) { 9011 // The defaulted special functions are defined as deleted if this is a variant 9012 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 9013 // type under ARC. 9014 if (!FieldType.hasNonTrivialObjCLifetime()) 9015 return false; 9016 9017 // Don't make the defaulted default constructor defined as deleted if the 9018 // member has an in-class initializer. 9019 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 9020 return false; 9021 9022 if (Diagnose) { 9023 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 9024 S.Diag(FD->getLocation(), 9025 diag::note_deleted_special_member_class_subobject) 9026 << getEffectiveCSM() << ParentClass << /*IsField*/true 9027 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 9028 } 9029 9030 return true; 9031 } 9032 9033 /// Check whether we should delete a special member function due to the class 9034 /// having a particular direct or virtual base class. 9035 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 9036 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 9037 // If program is correct, BaseClass cannot be null, but if it is, the error 9038 // must be reported elsewhere. 9039 if (!BaseClass) 9040 return false; 9041 // If we have an inheriting constructor, check whether we're calling an 9042 // inherited constructor instead of a default constructor. 9043 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 9044 if (auto *BaseCtor = SMOR.getMethod()) { 9045 // Note that we do not check access along this path; other than that, 9046 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 9047 // FIXME: Check that the base has a usable destructor! Sink this into 9048 // shouldDeleteForClassSubobject. 9049 if (BaseCtor->isDeleted() && Diagnose) { 9050 S.Diag(Base->getBeginLoc(), 9051 diag::note_deleted_special_member_class_subobject) 9052 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 9053 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 9054 << /*IsObjCPtr*/false; 9055 S.NoteDeletedFunction(BaseCtor); 9056 } 9057 return BaseCtor->isDeleted(); 9058 } 9059 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 9060 } 9061 9062 /// Check whether we should delete a special member function due to the class 9063 /// having a particular non-static data member. 9064 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 9065 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 9066 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 9067 9068 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 9069 return true; 9070 9071 if (CSM == Sema::CXXDefaultConstructor) { 9072 // For a default constructor, all references must be initialized in-class 9073 // and, if a union, it must have a non-const member. 9074 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 9075 if (Diagnose) 9076 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9077 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 9078 return true; 9079 } 9080 // C++11 [class.ctor]p5: any non-variant non-static data member of 9081 // const-qualified type (or array thereof) with no 9082 // brace-or-equal-initializer does not have a user-provided default 9083 // constructor. 9084 if (!inUnion() && FieldType.isConstQualified() && 9085 !FD->hasInClassInitializer() && 9086 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 9087 if (Diagnose) 9088 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9089 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 9090 return true; 9091 } 9092 9093 if (inUnion() && !FieldType.isConstQualified()) 9094 AllFieldsAreConst = false; 9095 } else if (CSM == Sema::CXXCopyConstructor) { 9096 // For a copy constructor, data members must not be of rvalue reference 9097 // type. 9098 if (FieldType->isRValueReferenceType()) { 9099 if (Diagnose) 9100 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 9101 << MD->getParent() << FD << FieldType; 9102 return true; 9103 } 9104 } else if (IsAssignment) { 9105 // For an assignment operator, data members must not be of reference type. 9106 if (FieldType->isReferenceType()) { 9107 if (Diagnose) 9108 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9109 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 9110 return true; 9111 } 9112 if (!FieldRecord && FieldType.isConstQualified()) { 9113 // C++11 [class.copy]p23: 9114 // -- a non-static data member of const non-class type (or array thereof) 9115 if (Diagnose) 9116 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9117 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 9118 return true; 9119 } 9120 } 9121 9122 if (FieldRecord) { 9123 // Some additional restrictions exist on the variant members. 9124 if (!inUnion() && FieldRecord->isUnion() && 9125 FieldRecord->isAnonymousStructOrUnion()) { 9126 bool AllVariantFieldsAreConst = true; 9127 9128 // FIXME: Handle anonymous unions declared within anonymous unions. 9129 for (auto *UI : FieldRecord->fields()) { 9130 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 9131 9132 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 9133 return true; 9134 9135 if (!UnionFieldType.isConstQualified()) 9136 AllVariantFieldsAreConst = false; 9137 9138 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 9139 if (UnionFieldRecord && 9140 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 9141 UnionFieldType.getCVRQualifiers())) 9142 return true; 9143 } 9144 9145 // At least one member in each anonymous union must be non-const 9146 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 9147 !FieldRecord->field_empty()) { 9148 if (Diagnose) 9149 S.Diag(FieldRecord->getLocation(), 9150 diag::note_deleted_default_ctor_all_const) 9151 << !!ICI << MD->getParent() << /*anonymous union*/1; 9152 return true; 9153 } 9154 9155 // Don't check the implicit member of the anonymous union type. 9156 // This is technically non-conformant, but sanity demands it. 9157 return false; 9158 } 9159 9160 if (shouldDeleteForClassSubobject(FieldRecord, FD, 9161 FieldType.getCVRQualifiers())) 9162 return true; 9163 } 9164 9165 return false; 9166 } 9167 9168 /// C++11 [class.ctor] p5: 9169 /// A defaulted default constructor for a class X is defined as deleted if 9170 /// X is a union and all of its variant members are of const-qualified type. 9171 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 9172 // This is a silly definition, because it gives an empty union a deleted 9173 // default constructor. Don't do that. 9174 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 9175 bool AnyFields = false; 9176 for (auto *F : MD->getParent()->fields()) 9177 if ((AnyFields = !F->isUnnamedBitfield())) 9178 break; 9179 if (!AnyFields) 9180 return false; 9181 if (Diagnose) 9182 S.Diag(MD->getParent()->getLocation(), 9183 diag::note_deleted_default_ctor_all_const) 9184 << !!ICI << MD->getParent() << /*not anonymous union*/0; 9185 return true; 9186 } 9187 return false; 9188 } 9189 9190 /// Determine whether a defaulted special member function should be defined as 9191 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 9192 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 9193 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 9194 InheritedConstructorInfo *ICI, 9195 bool Diagnose) { 9196 if (MD->isInvalidDecl()) 9197 return false; 9198 CXXRecordDecl *RD = MD->getParent(); 9199 assert(!RD->isDependentType() && "do deletion after instantiation"); 9200 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 9201 return false; 9202 9203 // C++11 [expr.lambda.prim]p19: 9204 // The closure type associated with a lambda-expression has a 9205 // deleted (8.4.3) default constructor and a deleted copy 9206 // assignment operator. 9207 // C++2a adds back these operators if the lambda has no lambda-capture. 9208 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 9209 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 9210 if (Diagnose) 9211 Diag(RD->getLocation(), diag::note_lambda_decl); 9212 return true; 9213 } 9214 9215 // For an anonymous struct or union, the copy and assignment special members 9216 // will never be used, so skip the check. For an anonymous union declared at 9217 // namespace scope, the constructor and destructor are used. 9218 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 9219 RD->isAnonymousStructOrUnion()) 9220 return false; 9221 9222 // C++11 [class.copy]p7, p18: 9223 // If the class definition declares a move constructor or move assignment 9224 // operator, an implicitly declared copy constructor or copy assignment 9225 // operator is defined as deleted. 9226 if (MD->isImplicit() && 9227 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 9228 CXXMethodDecl *UserDeclaredMove = nullptr; 9229 9230 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 9231 // deletion of the corresponding copy operation, not both copy operations. 9232 // MSVC 2015 has adopted the standards conforming behavior. 9233 bool DeletesOnlyMatchingCopy = 9234 getLangOpts().MSVCCompat && 9235 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 9236 9237 if (RD->hasUserDeclaredMoveConstructor() && 9238 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 9239 if (!Diagnose) return true; 9240 9241 // Find any user-declared move constructor. 9242 for (auto *I : RD->ctors()) { 9243 if (I->isMoveConstructor()) { 9244 UserDeclaredMove = I; 9245 break; 9246 } 9247 } 9248 assert(UserDeclaredMove); 9249 } else if (RD->hasUserDeclaredMoveAssignment() && 9250 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 9251 if (!Diagnose) return true; 9252 9253 // Find any user-declared move assignment operator. 9254 for (auto *I : RD->methods()) { 9255 if (I->isMoveAssignmentOperator()) { 9256 UserDeclaredMove = I; 9257 break; 9258 } 9259 } 9260 assert(UserDeclaredMove); 9261 } 9262 9263 if (UserDeclaredMove) { 9264 Diag(UserDeclaredMove->getLocation(), 9265 diag::note_deleted_copy_user_declared_move) 9266 << (CSM == CXXCopyAssignment) << RD 9267 << UserDeclaredMove->isMoveAssignmentOperator(); 9268 return true; 9269 } 9270 } 9271 9272 // Do access control from the special member function 9273 ContextRAII MethodContext(*this, MD); 9274 9275 // C++11 [class.dtor]p5: 9276 // -- for a virtual destructor, lookup of the non-array deallocation function 9277 // results in an ambiguity or in a function that is deleted or inaccessible 9278 if (CSM == CXXDestructor && MD->isVirtual()) { 9279 FunctionDecl *OperatorDelete = nullptr; 9280 DeclarationName Name = 9281 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 9282 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 9283 OperatorDelete, /*Diagnose*/false)) { 9284 if (Diagnose) 9285 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 9286 return true; 9287 } 9288 } 9289 9290 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 9291 9292 // Per DR1611, do not consider virtual bases of constructors of abstract 9293 // classes, since we are not going to construct them. 9294 // Per DR1658, do not consider virtual bases of destructors of abstract 9295 // classes either. 9296 // Per DR2180, for assignment operators we only assign (and thus only 9297 // consider) direct bases. 9298 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 9299 : SMI.VisitPotentiallyConstructedBases)) 9300 return true; 9301 9302 if (SMI.shouldDeleteForAllConstMembers()) 9303 return true; 9304 9305 if (getLangOpts().CUDA) { 9306 // We should delete the special member in CUDA mode if target inference 9307 // failed. 9308 // For inherited constructors (non-null ICI), CSM may be passed so that MD 9309 // is treated as certain special member, which may not reflect what special 9310 // member MD really is. However inferCUDATargetForImplicitSpecialMember 9311 // expects CSM to match MD, therefore recalculate CSM. 9312 assert(ICI || CSM == getSpecialMember(MD)); 9313 auto RealCSM = CSM; 9314 if (ICI) 9315 RealCSM = getSpecialMember(MD); 9316 9317 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 9318 SMI.ConstArg, Diagnose); 9319 } 9320 9321 return false; 9322 } 9323 9324 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 9325 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 9326 assert(DFK && "not a defaultable function"); 9327 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted"); 9328 9329 if (DFK.isSpecialMember()) { 9330 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 9331 nullptr, /*Diagnose=*/true); 9332 } else { 9333 DefaultedComparisonAnalyzer( 9334 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 9335 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 9336 .visit(); 9337 } 9338 } 9339 9340 /// Perform lookup for a special member of the specified kind, and determine 9341 /// whether it is trivial. If the triviality can be determined without the 9342 /// lookup, skip it. This is intended for use when determining whether a 9343 /// special member of a containing object is trivial, and thus does not ever 9344 /// perform overload resolution for default constructors. 9345 /// 9346 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 9347 /// member that was most likely to be intended to be trivial, if any. 9348 /// 9349 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 9350 /// determine whether the special member is trivial. 9351 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 9352 Sema::CXXSpecialMember CSM, unsigned Quals, 9353 bool ConstRHS, 9354 Sema::TrivialABIHandling TAH, 9355 CXXMethodDecl **Selected) { 9356 if (Selected) 9357 *Selected = nullptr; 9358 9359 switch (CSM) { 9360 case Sema::CXXInvalid: 9361 llvm_unreachable("not a special member"); 9362 9363 case Sema::CXXDefaultConstructor: 9364 // C++11 [class.ctor]p5: 9365 // A default constructor is trivial if: 9366 // - all the [direct subobjects] have trivial default constructors 9367 // 9368 // Note, no overload resolution is performed in this case. 9369 if (RD->hasTrivialDefaultConstructor()) 9370 return true; 9371 9372 if (Selected) { 9373 // If there's a default constructor which could have been trivial, dig it 9374 // out. Otherwise, if there's any user-provided default constructor, point 9375 // to that as an example of why there's not a trivial one. 9376 CXXConstructorDecl *DefCtor = nullptr; 9377 if (RD->needsImplicitDefaultConstructor()) 9378 S.DeclareImplicitDefaultConstructor(RD); 9379 for (auto *CI : RD->ctors()) { 9380 if (!CI->isDefaultConstructor()) 9381 continue; 9382 DefCtor = CI; 9383 if (!DefCtor->isUserProvided()) 9384 break; 9385 } 9386 9387 *Selected = DefCtor; 9388 } 9389 9390 return false; 9391 9392 case Sema::CXXDestructor: 9393 // C++11 [class.dtor]p5: 9394 // A destructor is trivial if: 9395 // - all the direct [subobjects] have trivial destructors 9396 if (RD->hasTrivialDestructor() || 9397 (TAH == Sema::TAH_ConsiderTrivialABI && 9398 RD->hasTrivialDestructorForCall())) 9399 return true; 9400 9401 if (Selected) { 9402 if (RD->needsImplicitDestructor()) 9403 S.DeclareImplicitDestructor(RD); 9404 *Selected = RD->getDestructor(); 9405 } 9406 9407 return false; 9408 9409 case Sema::CXXCopyConstructor: 9410 // C++11 [class.copy]p12: 9411 // A copy constructor is trivial if: 9412 // - the constructor selected to copy each direct [subobject] is trivial 9413 if (RD->hasTrivialCopyConstructor() || 9414 (TAH == Sema::TAH_ConsiderTrivialABI && 9415 RD->hasTrivialCopyConstructorForCall())) { 9416 if (Quals == Qualifiers::Const) 9417 // We must either select the trivial copy constructor or reach an 9418 // ambiguity; no need to actually perform overload resolution. 9419 return true; 9420 } else if (!Selected) { 9421 return false; 9422 } 9423 // In C++98, we are not supposed to perform overload resolution here, but we 9424 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 9425 // cases like B as having a non-trivial copy constructor: 9426 // struct A { template<typename T> A(T&); }; 9427 // struct B { mutable A a; }; 9428 goto NeedOverloadResolution; 9429 9430 case Sema::CXXCopyAssignment: 9431 // C++11 [class.copy]p25: 9432 // A copy assignment operator is trivial if: 9433 // - the assignment operator selected to copy each direct [subobject] is 9434 // trivial 9435 if (RD->hasTrivialCopyAssignment()) { 9436 if (Quals == Qualifiers::Const) 9437 return true; 9438 } else if (!Selected) { 9439 return false; 9440 } 9441 // In C++98, we are not supposed to perform overload resolution here, but we 9442 // treat that as a language defect. 9443 goto NeedOverloadResolution; 9444 9445 case Sema::CXXMoveConstructor: 9446 case Sema::CXXMoveAssignment: 9447 NeedOverloadResolution: 9448 Sema::SpecialMemberOverloadResult SMOR = 9449 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 9450 9451 // The standard doesn't describe how to behave if the lookup is ambiguous. 9452 // We treat it as not making the member non-trivial, just like the standard 9453 // mandates for the default constructor. This should rarely matter, because 9454 // the member will also be deleted. 9455 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9456 return true; 9457 9458 if (!SMOR.getMethod()) { 9459 assert(SMOR.getKind() == 9460 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 9461 return false; 9462 } 9463 9464 // We deliberately don't check if we found a deleted special member. We're 9465 // not supposed to! 9466 if (Selected) 9467 *Selected = SMOR.getMethod(); 9468 9469 if (TAH == Sema::TAH_ConsiderTrivialABI && 9470 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 9471 return SMOR.getMethod()->isTrivialForCall(); 9472 return SMOR.getMethod()->isTrivial(); 9473 } 9474 9475 llvm_unreachable("unknown special method kind"); 9476 } 9477 9478 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 9479 for (auto *CI : RD->ctors()) 9480 if (!CI->isImplicit()) 9481 return CI; 9482 9483 // Look for constructor templates. 9484 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 9485 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 9486 if (CXXConstructorDecl *CD = 9487 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 9488 return CD; 9489 } 9490 9491 return nullptr; 9492 } 9493 9494 /// The kind of subobject we are checking for triviality. The values of this 9495 /// enumeration are used in diagnostics. 9496 enum TrivialSubobjectKind { 9497 /// The subobject is a base class. 9498 TSK_BaseClass, 9499 /// The subobject is a non-static data member. 9500 TSK_Field, 9501 /// The object is actually the complete object. 9502 TSK_CompleteObject 9503 }; 9504 9505 /// Check whether the special member selected for a given type would be trivial. 9506 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9507 QualType SubType, bool ConstRHS, 9508 Sema::CXXSpecialMember CSM, 9509 TrivialSubobjectKind Kind, 9510 Sema::TrivialABIHandling TAH, bool Diagnose) { 9511 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9512 if (!SubRD) 9513 return true; 9514 9515 CXXMethodDecl *Selected; 9516 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9517 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9518 return true; 9519 9520 if (Diagnose) { 9521 if (ConstRHS) 9522 SubType.addConst(); 9523 9524 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9525 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9526 << Kind << SubType.getUnqualifiedType(); 9527 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9528 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9529 } else if (!Selected) 9530 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9531 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9532 else if (Selected->isUserProvided()) { 9533 if (Kind == TSK_CompleteObject) 9534 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9535 << Kind << SubType.getUnqualifiedType() << CSM; 9536 else { 9537 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9538 << Kind << SubType.getUnqualifiedType() << CSM; 9539 S.Diag(Selected->getLocation(), diag::note_declared_at); 9540 } 9541 } else { 9542 if (Kind != TSK_CompleteObject) 9543 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9544 << Kind << SubType.getUnqualifiedType() << CSM; 9545 9546 // Explain why the defaulted or deleted special member isn't trivial. 9547 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9548 Diagnose); 9549 } 9550 } 9551 9552 return false; 9553 } 9554 9555 /// Check whether the members of a class type allow a special member to be 9556 /// trivial. 9557 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9558 Sema::CXXSpecialMember CSM, 9559 bool ConstArg, 9560 Sema::TrivialABIHandling TAH, 9561 bool Diagnose) { 9562 for (const auto *FI : RD->fields()) { 9563 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9564 continue; 9565 9566 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9567 9568 // Pretend anonymous struct or union members are members of this class. 9569 if (FI->isAnonymousStructOrUnion()) { 9570 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9571 CSM, ConstArg, TAH, Diagnose)) 9572 return false; 9573 continue; 9574 } 9575 9576 // C++11 [class.ctor]p5: 9577 // A default constructor is trivial if [...] 9578 // -- no non-static data member of its class has a 9579 // brace-or-equal-initializer 9580 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9581 if (Diagnose) 9582 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init) 9583 << FI; 9584 return false; 9585 } 9586 9587 // Objective C ARC 4.3.5: 9588 // [...] nontrivally ownership-qualified types are [...] not trivially 9589 // default constructible, copy constructible, move constructible, copy 9590 // assignable, move assignable, or destructible [...] 9591 if (FieldType.hasNonTrivialObjCLifetime()) { 9592 if (Diagnose) 9593 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9594 << RD << FieldType.getObjCLifetime(); 9595 return false; 9596 } 9597 9598 bool ConstRHS = ConstArg && !FI->isMutable(); 9599 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9600 CSM, TSK_Field, TAH, Diagnose)) 9601 return false; 9602 } 9603 9604 return true; 9605 } 9606 9607 /// Diagnose why the specified class does not have a trivial special member of 9608 /// the given kind. 9609 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9610 QualType Ty = Context.getRecordType(RD); 9611 9612 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9613 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9614 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9615 /*Diagnose*/true); 9616 } 9617 9618 /// Determine whether a defaulted or deleted special member function is trivial, 9619 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9620 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9621 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9622 TrivialABIHandling TAH, bool Diagnose) { 9623 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 9624 9625 CXXRecordDecl *RD = MD->getParent(); 9626 9627 bool ConstArg = false; 9628 9629 // C++11 [class.copy]p12, p25: [DR1593] 9630 // A [special member] is trivial if [...] its parameter-type-list is 9631 // equivalent to the parameter-type-list of an implicit declaration [...] 9632 switch (CSM) { 9633 case CXXDefaultConstructor: 9634 case CXXDestructor: 9635 // Trivial default constructors and destructors cannot have parameters. 9636 break; 9637 9638 case CXXCopyConstructor: 9639 case CXXCopyAssignment: { 9640 // Trivial copy operations always have const, non-volatile parameter types. 9641 ConstArg = true; 9642 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9643 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9644 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 9645 if (Diagnose) 9646 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9647 << Param0->getSourceRange() << Param0->getType() 9648 << Context.getLValueReferenceType( 9649 Context.getRecordType(RD).withConst()); 9650 return false; 9651 } 9652 break; 9653 } 9654 9655 case CXXMoveConstructor: 9656 case CXXMoveAssignment: { 9657 // Trivial move operations always have non-cv-qualified parameters. 9658 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9659 const RValueReferenceType *RT = 9660 Param0->getType()->getAs<RValueReferenceType>(); 9661 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9662 if (Diagnose) 9663 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9664 << Param0->getSourceRange() << Param0->getType() 9665 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9666 return false; 9667 } 9668 break; 9669 } 9670 9671 case CXXInvalid: 9672 llvm_unreachable("not a special member"); 9673 } 9674 9675 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9676 if (Diagnose) 9677 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9678 diag::note_nontrivial_default_arg) 9679 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9680 return false; 9681 } 9682 if (MD->isVariadic()) { 9683 if (Diagnose) 9684 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9685 return false; 9686 } 9687 9688 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9689 // A copy/move [constructor or assignment operator] is trivial if 9690 // -- the [member] selected to copy/move each direct base class subobject 9691 // is trivial 9692 // 9693 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9694 // A [default constructor or destructor] is trivial if 9695 // -- all the direct base classes have trivial [default constructors or 9696 // destructors] 9697 for (const auto &BI : RD->bases()) 9698 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9699 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9700 return false; 9701 9702 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9703 // A copy/move [constructor or assignment operator] for a class X is 9704 // trivial if 9705 // -- for each non-static data member of X that is of class type (or array 9706 // thereof), the constructor selected to copy/move that member is 9707 // trivial 9708 // 9709 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9710 // A [default constructor or destructor] is trivial if 9711 // -- for all of the non-static data members of its class that are of class 9712 // type (or array thereof), each such class has a trivial [default 9713 // constructor or destructor] 9714 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9715 return false; 9716 9717 // C++11 [class.dtor]p5: 9718 // A destructor is trivial if [...] 9719 // -- the destructor is not virtual 9720 if (CSM == CXXDestructor && MD->isVirtual()) { 9721 if (Diagnose) 9722 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9723 return false; 9724 } 9725 9726 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9727 // A [special member] for class X is trivial if [...] 9728 // -- class X has no virtual functions and no virtual base classes 9729 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9730 if (!Diagnose) 9731 return false; 9732 9733 if (RD->getNumVBases()) { 9734 // Check for virtual bases. We already know that the corresponding 9735 // member in all bases is trivial, so vbases must all be direct. 9736 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9737 assert(BS.isVirtual()); 9738 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9739 return false; 9740 } 9741 9742 // Must have a virtual method. 9743 for (const auto *MI : RD->methods()) { 9744 if (MI->isVirtual()) { 9745 SourceLocation MLoc = MI->getBeginLoc(); 9746 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9747 return false; 9748 } 9749 } 9750 9751 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 9752 } 9753 9754 // Looks like it's trivial! 9755 return true; 9756 } 9757 9758 namespace { 9759 struct FindHiddenVirtualMethod { 9760 Sema *S; 9761 CXXMethodDecl *Method; 9762 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9763 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9764 9765 private: 9766 /// Check whether any most overridden method from MD in Methods 9767 static bool CheckMostOverridenMethods( 9768 const CXXMethodDecl *MD, 9769 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9770 if (MD->size_overridden_methods() == 0) 9771 return Methods.count(MD->getCanonicalDecl()); 9772 for (const CXXMethodDecl *O : MD->overridden_methods()) 9773 if (CheckMostOverridenMethods(O, Methods)) 9774 return true; 9775 return false; 9776 } 9777 9778 public: 9779 /// Member lookup function that determines whether a given C++ 9780 /// method overloads virtual methods in a base class without overriding any, 9781 /// to be used with CXXRecordDecl::lookupInBases(). 9782 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9783 RecordDecl *BaseRecord = 9784 Specifier->getType()->castAs<RecordType>()->getDecl(); 9785 9786 DeclarationName Name = Method->getDeclName(); 9787 assert(Name.getNameKind() == DeclarationName::Identifier); 9788 9789 bool foundSameNameMethod = false; 9790 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9791 for (Path.Decls = BaseRecord->lookup(Name).begin(); 9792 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) { 9793 NamedDecl *D = *Path.Decls; 9794 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9795 MD = MD->getCanonicalDecl(); 9796 foundSameNameMethod = true; 9797 // Interested only in hidden virtual methods. 9798 if (!MD->isVirtual()) 9799 continue; 9800 // If the method we are checking overrides a method from its base 9801 // don't warn about the other overloaded methods. Clang deviates from 9802 // GCC by only diagnosing overloads of inherited virtual functions that 9803 // do not override any other virtual functions in the base. GCC's 9804 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9805 // function from a base class. These cases may be better served by a 9806 // warning (not specific to virtual functions) on call sites when the 9807 // call would select a different function from the base class, were it 9808 // visible. 9809 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9810 if (!S->IsOverload(Method, MD, false)) 9811 return true; 9812 // Collect the overload only if its hidden. 9813 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9814 overloadedMethods.push_back(MD); 9815 } 9816 } 9817 9818 if (foundSameNameMethod) 9819 OverloadedMethods.append(overloadedMethods.begin(), 9820 overloadedMethods.end()); 9821 return foundSameNameMethod; 9822 } 9823 }; 9824 } // end anonymous namespace 9825 9826 /// Add the most overridden methods from MD to Methods 9827 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9828 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9829 if (MD->size_overridden_methods() == 0) 9830 Methods.insert(MD->getCanonicalDecl()); 9831 else 9832 for (const CXXMethodDecl *O : MD->overridden_methods()) 9833 AddMostOverridenMethods(O, Methods); 9834 } 9835 9836 /// Check if a method overloads virtual methods in a base class without 9837 /// overriding any. 9838 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9839 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9840 if (!MD->getDeclName().isIdentifier()) 9841 return; 9842 9843 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9844 /*bool RecordPaths=*/false, 9845 /*bool DetectVirtual=*/false); 9846 FindHiddenVirtualMethod FHVM; 9847 FHVM.Method = MD; 9848 FHVM.S = this; 9849 9850 // Keep the base methods that were overridden or introduced in the subclass 9851 // by 'using' in a set. A base method not in this set is hidden. 9852 CXXRecordDecl *DC = MD->getParent(); 9853 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9854 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9855 NamedDecl *ND = *I; 9856 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9857 ND = shad->getTargetDecl(); 9858 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9859 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9860 } 9861 9862 if (DC->lookupInBases(FHVM, Paths)) 9863 OverloadedMethods = FHVM.OverloadedMethods; 9864 } 9865 9866 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 9867 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9868 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 9869 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 9870 PartialDiagnostic PD = PDiag( 9871 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 9872 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 9873 Diag(overloadedMD->getLocation(), PD); 9874 } 9875 } 9876 9877 /// Diagnose methods which overload virtual methods in a base class 9878 /// without overriding any. 9879 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 9880 if (MD->isInvalidDecl()) 9881 return; 9882 9883 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 9884 return; 9885 9886 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9887 FindHiddenVirtualMethods(MD, OverloadedMethods); 9888 if (!OverloadedMethods.empty()) { 9889 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 9890 << MD << (OverloadedMethods.size() > 1); 9891 9892 NoteHiddenVirtualMethods(MD, OverloadedMethods); 9893 } 9894 } 9895 9896 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 9897 auto PrintDiagAndRemoveAttr = [&](unsigned N) { 9898 // No diagnostics if this is a template instantiation. 9899 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) { 9900 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9901 diag::ext_cannot_use_trivial_abi) << &RD; 9902 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9903 diag::note_cannot_use_trivial_abi_reason) << &RD << N; 9904 } 9905 RD.dropAttr<TrivialABIAttr>(); 9906 }; 9907 9908 // Ill-formed if the copy and move constructors are deleted. 9909 auto HasNonDeletedCopyOrMoveConstructor = [&]() { 9910 // If the type is dependent, then assume it might have 9911 // implicit copy or move ctor because we won't know yet at this point. 9912 if (RD.isDependentType()) 9913 return true; 9914 if (RD.needsImplicitCopyConstructor() && 9915 !RD.defaultedCopyConstructorIsDeleted()) 9916 return true; 9917 if (RD.needsImplicitMoveConstructor() && 9918 !RD.defaultedMoveConstructorIsDeleted()) 9919 return true; 9920 for (const CXXConstructorDecl *CD : RD.ctors()) 9921 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted()) 9922 return true; 9923 return false; 9924 }; 9925 9926 if (!HasNonDeletedCopyOrMoveConstructor()) { 9927 PrintDiagAndRemoveAttr(0); 9928 return; 9929 } 9930 9931 // Ill-formed if the struct has virtual functions. 9932 if (RD.isPolymorphic()) { 9933 PrintDiagAndRemoveAttr(1); 9934 return; 9935 } 9936 9937 for (const auto &B : RD.bases()) { 9938 // Ill-formed if the base class is non-trivial for the purpose of calls or a 9939 // virtual base. 9940 if (!B.getType()->isDependentType() && 9941 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) { 9942 PrintDiagAndRemoveAttr(2); 9943 return; 9944 } 9945 9946 if (B.isVirtual()) { 9947 PrintDiagAndRemoveAttr(3); 9948 return; 9949 } 9950 } 9951 9952 for (const auto *FD : RD.fields()) { 9953 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 9954 // non-trivial for the purpose of calls. 9955 QualType FT = FD->getType(); 9956 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 9957 PrintDiagAndRemoveAttr(4); 9958 return; 9959 } 9960 9961 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 9962 if (!RT->isDependentType() && 9963 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 9964 PrintDiagAndRemoveAttr(5); 9965 return; 9966 } 9967 } 9968 } 9969 9970 void Sema::ActOnFinishCXXMemberSpecification( 9971 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 9972 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 9973 if (!TagDecl) 9974 return; 9975 9976 AdjustDeclIfTemplate(TagDecl); 9977 9978 for (const ParsedAttr &AL : AttrList) { 9979 if (AL.getKind() != ParsedAttr::AT_Visibility) 9980 continue; 9981 AL.setInvalid(); 9982 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 9983 } 9984 9985 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 9986 // strict aliasing violation! 9987 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 9988 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 9989 9990 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 9991 } 9992 9993 /// Find the equality comparison functions that should be implicitly declared 9994 /// in a given class definition, per C++2a [class.compare.default]p3. 9995 static void findImplicitlyDeclaredEqualityComparisons( 9996 ASTContext &Ctx, CXXRecordDecl *RD, 9997 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 9998 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 9999 if (!RD->lookup(EqEq).empty()) 10000 // Member operator== explicitly declared: no implicit operator==s. 10001 return; 10002 10003 // Traverse friends looking for an '==' or a '<=>'. 10004 for (FriendDecl *Friend : RD->friends()) { 10005 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 10006 if (!FD) continue; 10007 10008 if (FD->getOverloadedOperator() == OO_EqualEqual) { 10009 // Friend operator== explicitly declared: no implicit operator==s. 10010 Spaceships.clear(); 10011 return; 10012 } 10013 10014 if (FD->getOverloadedOperator() == OO_Spaceship && 10015 FD->isExplicitlyDefaulted()) 10016 Spaceships.push_back(FD); 10017 } 10018 10019 // Look for members named 'operator<=>'. 10020 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 10021 for (NamedDecl *ND : RD->lookup(Cmp)) { 10022 // Note that we could find a non-function here (either a function template 10023 // or a using-declaration). Neither case results in an implicit 10024 // 'operator=='. 10025 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 10026 if (FD->isExplicitlyDefaulted()) 10027 Spaceships.push_back(FD); 10028 } 10029 } 10030 10031 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 10032 /// special functions, such as the default constructor, copy 10033 /// constructor, or destructor, to the given C++ class (C++ 10034 /// [special]p1). This routine can only be executed just before the 10035 /// definition of the class is complete. 10036 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 10037 // Don't add implicit special members to templated classes. 10038 // FIXME: This means unqualified lookups for 'operator=' within a class 10039 // template don't work properly. 10040 if (!ClassDecl->isDependentType()) { 10041 if (ClassDecl->needsImplicitDefaultConstructor()) { 10042 ++getASTContext().NumImplicitDefaultConstructors; 10043 10044 if (ClassDecl->hasInheritedConstructor()) 10045 DeclareImplicitDefaultConstructor(ClassDecl); 10046 } 10047 10048 if (ClassDecl->needsImplicitCopyConstructor()) { 10049 ++getASTContext().NumImplicitCopyConstructors; 10050 10051 // If the properties or semantics of the copy constructor couldn't be 10052 // determined while the class was being declared, force a declaration 10053 // of it now. 10054 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 10055 ClassDecl->hasInheritedConstructor()) 10056 DeclareImplicitCopyConstructor(ClassDecl); 10057 // For the MS ABI we need to know whether the copy ctor is deleted. A 10058 // prerequisite for deleting the implicit copy ctor is that the class has 10059 // a move ctor or move assignment that is either user-declared or whose 10060 // semantics are inherited from a subobject. FIXME: We should provide a 10061 // more direct way for CodeGen to ask whether the constructor was deleted. 10062 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 10063 (ClassDecl->hasUserDeclaredMoveConstructor() || 10064 ClassDecl->needsOverloadResolutionForMoveConstructor() || 10065 ClassDecl->hasUserDeclaredMoveAssignment() || 10066 ClassDecl->needsOverloadResolutionForMoveAssignment())) 10067 DeclareImplicitCopyConstructor(ClassDecl); 10068 } 10069 10070 if (getLangOpts().CPlusPlus11 && 10071 ClassDecl->needsImplicitMoveConstructor()) { 10072 ++getASTContext().NumImplicitMoveConstructors; 10073 10074 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 10075 ClassDecl->hasInheritedConstructor()) 10076 DeclareImplicitMoveConstructor(ClassDecl); 10077 } 10078 10079 if (ClassDecl->needsImplicitCopyAssignment()) { 10080 ++getASTContext().NumImplicitCopyAssignmentOperators; 10081 10082 // If we have a dynamic class, then the copy assignment operator may be 10083 // virtual, so we have to declare it immediately. This ensures that, e.g., 10084 // it shows up in the right place in the vtable and that we diagnose 10085 // problems with the implicit exception specification. 10086 if (ClassDecl->isDynamicClass() || 10087 ClassDecl->needsOverloadResolutionForCopyAssignment() || 10088 ClassDecl->hasInheritedAssignment()) 10089 DeclareImplicitCopyAssignment(ClassDecl); 10090 } 10091 10092 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 10093 ++getASTContext().NumImplicitMoveAssignmentOperators; 10094 10095 // Likewise for the move assignment operator. 10096 if (ClassDecl->isDynamicClass() || 10097 ClassDecl->needsOverloadResolutionForMoveAssignment() || 10098 ClassDecl->hasInheritedAssignment()) 10099 DeclareImplicitMoveAssignment(ClassDecl); 10100 } 10101 10102 if (ClassDecl->needsImplicitDestructor()) { 10103 ++getASTContext().NumImplicitDestructors; 10104 10105 // If we have a dynamic class, then the destructor may be virtual, so we 10106 // have to declare the destructor immediately. This ensures that, e.g., it 10107 // shows up in the right place in the vtable and that we diagnose problems 10108 // with the implicit exception specification. 10109 if (ClassDecl->isDynamicClass() || 10110 ClassDecl->needsOverloadResolutionForDestructor()) 10111 DeclareImplicitDestructor(ClassDecl); 10112 } 10113 } 10114 10115 // C++2a [class.compare.default]p3: 10116 // If the member-specification does not explicitly declare any member or 10117 // friend named operator==, an == operator function is declared implicitly 10118 // for each defaulted three-way comparison operator function defined in 10119 // the member-specification 10120 // FIXME: Consider doing this lazily. 10121 // We do this during the initial parse for a class template, not during 10122 // instantiation, so that we can handle unqualified lookups for 'operator==' 10123 // when parsing the template. 10124 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) { 10125 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships; 10126 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 10127 DefaultedSpaceships); 10128 for (auto *FD : DefaultedSpaceships) 10129 DeclareImplicitEqualityComparison(ClassDecl, FD); 10130 } 10131 } 10132 10133 unsigned 10134 Sema::ActOnReenterTemplateScope(Decl *D, 10135 llvm::function_ref<Scope *()> EnterScope) { 10136 if (!D) 10137 return 0; 10138 AdjustDeclIfTemplate(D); 10139 10140 // In order to get name lookup right, reenter template scopes in order from 10141 // outermost to innermost. 10142 SmallVector<TemplateParameterList *, 4> ParameterLists; 10143 DeclContext *LookupDC = dyn_cast<DeclContext>(D); 10144 10145 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 10146 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 10147 ParameterLists.push_back(DD->getTemplateParameterList(i)); 10148 10149 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10150 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 10151 ParameterLists.push_back(FTD->getTemplateParameters()); 10152 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 10153 LookupDC = VD->getDeclContext(); 10154 10155 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate()) 10156 ParameterLists.push_back(VTD->getTemplateParameters()); 10157 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) 10158 ParameterLists.push_back(PSD->getTemplateParameters()); 10159 } 10160 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 10161 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 10162 ParameterLists.push_back(TD->getTemplateParameterList(i)); 10163 10164 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 10165 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 10166 ParameterLists.push_back(CTD->getTemplateParameters()); 10167 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 10168 ParameterLists.push_back(PSD->getTemplateParameters()); 10169 } 10170 } 10171 // FIXME: Alias declarations and concepts. 10172 10173 unsigned Count = 0; 10174 Scope *InnermostTemplateScope = nullptr; 10175 for (TemplateParameterList *Params : ParameterLists) { 10176 // Ignore explicit specializations; they don't contribute to the template 10177 // depth. 10178 if (Params->size() == 0) 10179 continue; 10180 10181 InnermostTemplateScope = EnterScope(); 10182 for (NamedDecl *Param : *Params) { 10183 if (Param->getDeclName()) { 10184 InnermostTemplateScope->AddDecl(Param); 10185 IdResolver.AddDecl(Param); 10186 } 10187 } 10188 ++Count; 10189 } 10190 10191 // Associate the new template scopes with the corresponding entities. 10192 if (InnermostTemplateScope) { 10193 assert(LookupDC && "no enclosing DeclContext for template lookup"); 10194 EnterTemplatedContext(InnermostTemplateScope, LookupDC); 10195 } 10196 10197 return Count; 10198 } 10199 10200 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10201 if (!RecordD) return; 10202 AdjustDeclIfTemplate(RecordD); 10203 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 10204 PushDeclContext(S, Record); 10205 } 10206 10207 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10208 if (!RecordD) return; 10209 PopDeclContext(); 10210 } 10211 10212 /// This is used to implement the constant expression evaluation part of the 10213 /// attribute enable_if extension. There is nothing in standard C++ which would 10214 /// require reentering parameters. 10215 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 10216 if (!Param) 10217 return; 10218 10219 S->AddDecl(Param); 10220 if (Param->getDeclName()) 10221 IdResolver.AddDecl(Param); 10222 } 10223 10224 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 10225 /// parsing a top-level (non-nested) C++ class, and we are now 10226 /// parsing those parts of the given Method declaration that could 10227 /// not be parsed earlier (C++ [class.mem]p2), such as default 10228 /// arguments. This action should enter the scope of the given 10229 /// Method declaration as if we had just parsed the qualified method 10230 /// name. However, it should not bring the parameters into scope; 10231 /// that will be performed by ActOnDelayedCXXMethodParameter. 10232 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10233 } 10234 10235 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 10236 /// C++ method declaration. We're (re-)introducing the given 10237 /// function parameter into scope for use in parsing later parts of 10238 /// the method declaration. For example, we could see an 10239 /// ActOnParamDefaultArgument event for this parameter. 10240 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 10241 if (!ParamD) 10242 return; 10243 10244 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 10245 10246 S->AddDecl(Param); 10247 if (Param->getDeclName()) 10248 IdResolver.AddDecl(Param); 10249 } 10250 10251 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 10252 /// processing the delayed method declaration for Method. The method 10253 /// declaration is now considered finished. There may be a separate 10254 /// ActOnStartOfFunctionDef action later (not necessarily 10255 /// immediately!) for this method, if it was also defined inside the 10256 /// class body. 10257 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10258 if (!MethodD) 10259 return; 10260 10261 AdjustDeclIfTemplate(MethodD); 10262 10263 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 10264 10265 // Now that we have our default arguments, check the constructor 10266 // again. It could produce additional diagnostics or affect whether 10267 // the class has implicitly-declared destructors, among other 10268 // things. 10269 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 10270 CheckConstructor(Constructor); 10271 10272 // Check the default arguments, which we may have added. 10273 if (!Method->isInvalidDecl()) 10274 CheckCXXDefaultArguments(Method); 10275 } 10276 10277 // Emit the given diagnostic for each non-address-space qualifier. 10278 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 10279 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 10280 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10281 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 10282 bool DiagOccured = false; 10283 FTI.MethodQualifiers->forEachQualifier( 10284 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 10285 SourceLocation SL) { 10286 // This diagnostic should be emitted on any qualifier except an addr 10287 // space qualifier. However, forEachQualifier currently doesn't visit 10288 // addr space qualifiers, so there's no way to write this condition 10289 // right now; we just diagnose on everything. 10290 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 10291 DiagOccured = true; 10292 }); 10293 if (DiagOccured) 10294 D.setInvalidType(); 10295 } 10296 } 10297 10298 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 10299 /// the well-formedness of the constructor declarator @p D with type @p 10300 /// R. If there are any errors in the declarator, this routine will 10301 /// emit diagnostics and set the invalid bit to true. In any case, the type 10302 /// will be updated to reflect a well-formed type for the constructor and 10303 /// returned. 10304 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 10305 StorageClass &SC) { 10306 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 10307 10308 // C++ [class.ctor]p3: 10309 // A constructor shall not be virtual (10.3) or static (9.4). A 10310 // constructor can be invoked for a const, volatile or const 10311 // volatile object. A constructor shall not be declared const, 10312 // volatile, or const volatile (9.3.2). 10313 if (isVirtual) { 10314 if (!D.isInvalidType()) 10315 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10316 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 10317 << SourceRange(D.getIdentifierLoc()); 10318 D.setInvalidType(); 10319 } 10320 if (SC == SC_Static) { 10321 if (!D.isInvalidType()) 10322 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10323 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10324 << SourceRange(D.getIdentifierLoc()); 10325 D.setInvalidType(); 10326 SC = SC_None; 10327 } 10328 10329 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10330 diagnoseIgnoredQualifiers( 10331 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 10332 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 10333 D.getDeclSpec().getRestrictSpecLoc(), 10334 D.getDeclSpec().getAtomicSpecLoc()); 10335 D.setInvalidType(); 10336 } 10337 10338 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 10339 10340 // C++0x [class.ctor]p4: 10341 // A constructor shall not be declared with a ref-qualifier. 10342 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10343 if (FTI.hasRefQualifier()) { 10344 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 10345 << FTI.RefQualifierIsLValueRef 10346 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10347 D.setInvalidType(); 10348 } 10349 10350 // Rebuild the function type "R" without any type qualifiers (in 10351 // case any of the errors above fired) and with "void" as the 10352 // return type, since constructors don't have return types. 10353 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10354 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 10355 return R; 10356 10357 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10358 EPI.TypeQuals = Qualifiers(); 10359 EPI.RefQualifier = RQ_None; 10360 10361 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 10362 } 10363 10364 /// CheckConstructor - Checks a fully-formed constructor for 10365 /// well-formedness, issuing any diagnostics required. Returns true if 10366 /// the constructor declarator is invalid. 10367 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 10368 CXXRecordDecl *ClassDecl 10369 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 10370 if (!ClassDecl) 10371 return Constructor->setInvalidDecl(); 10372 10373 // C++ [class.copy]p3: 10374 // A declaration of a constructor for a class X is ill-formed if 10375 // its first parameter is of type (optionally cv-qualified) X and 10376 // either there are no other parameters or else all other 10377 // parameters have default arguments. 10378 if (!Constructor->isInvalidDecl() && 10379 Constructor->hasOneParamOrDefaultArgs() && 10380 Constructor->getTemplateSpecializationKind() != 10381 TSK_ImplicitInstantiation) { 10382 QualType ParamType = Constructor->getParamDecl(0)->getType(); 10383 QualType ClassTy = Context.getTagDeclType(ClassDecl); 10384 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 10385 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 10386 const char *ConstRef 10387 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 10388 : " const &"; 10389 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 10390 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 10391 10392 // FIXME: Rather that making the constructor invalid, we should endeavor 10393 // to fix the type. 10394 Constructor->setInvalidDecl(); 10395 } 10396 } 10397 } 10398 10399 /// CheckDestructor - Checks a fully-formed destructor definition for 10400 /// well-formedness, issuing any diagnostics required. Returns true 10401 /// on error. 10402 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 10403 CXXRecordDecl *RD = Destructor->getParent(); 10404 10405 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 10406 SourceLocation Loc; 10407 10408 if (!Destructor->isImplicit()) 10409 Loc = Destructor->getLocation(); 10410 else 10411 Loc = RD->getLocation(); 10412 10413 // If we have a virtual destructor, look up the deallocation function 10414 if (FunctionDecl *OperatorDelete = 10415 FindDeallocationFunctionForDestructor(Loc, RD)) { 10416 Expr *ThisArg = nullptr; 10417 10418 // If the notional 'delete this' expression requires a non-trivial 10419 // conversion from 'this' to the type of a destroying operator delete's 10420 // first parameter, perform that conversion now. 10421 if (OperatorDelete->isDestroyingOperatorDelete()) { 10422 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 10423 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 10424 // C++ [class.dtor]p13: 10425 // ... as if for the expression 'delete this' appearing in a 10426 // non-virtual destructor of the destructor's class. 10427 ContextRAII SwitchContext(*this, Destructor); 10428 ExprResult This = 10429 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 10430 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 10431 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 10432 if (This.isInvalid()) { 10433 // FIXME: Register this as a context note so that it comes out 10434 // in the right order. 10435 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 10436 return true; 10437 } 10438 ThisArg = This.get(); 10439 } 10440 } 10441 10442 DiagnoseUseOfDecl(OperatorDelete, Loc); 10443 MarkFunctionReferenced(Loc, OperatorDelete); 10444 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 10445 } 10446 } 10447 10448 return false; 10449 } 10450 10451 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 10452 /// the well-formednes of the destructor declarator @p D with type @p 10453 /// R. If there are any errors in the declarator, this routine will 10454 /// emit diagnostics and set the declarator to invalid. Even if this happens, 10455 /// will be updated to reflect a well-formed type for the destructor and 10456 /// returned. 10457 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 10458 StorageClass& SC) { 10459 // C++ [class.dtor]p1: 10460 // [...] A typedef-name that names a class is a class-name 10461 // (7.1.3); however, a typedef-name that names a class shall not 10462 // be used as the identifier in the declarator for a destructor 10463 // declaration. 10464 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 10465 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 10466 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10467 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 10468 else if (const TemplateSpecializationType *TST = 10469 DeclaratorType->getAs<TemplateSpecializationType>()) 10470 if (TST->isTypeAlias()) 10471 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10472 << DeclaratorType << 1; 10473 10474 // C++ [class.dtor]p2: 10475 // A destructor is used to destroy objects of its class type. A 10476 // destructor takes no parameters, and no return type can be 10477 // specified for it (not even void). The address of a destructor 10478 // shall not be taken. A destructor shall not be static. A 10479 // destructor can be invoked for a const, volatile or const 10480 // volatile object. A destructor shall not be declared const, 10481 // volatile or const volatile (9.3.2). 10482 if (SC == SC_Static) { 10483 if (!D.isInvalidType()) 10484 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 10485 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10486 << SourceRange(D.getIdentifierLoc()) 10487 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10488 10489 SC = SC_None; 10490 } 10491 if (!D.isInvalidType()) { 10492 // Destructors don't have return types, but the parser will 10493 // happily parse something like: 10494 // 10495 // class X { 10496 // float ~X(); 10497 // }; 10498 // 10499 // The return type will be eliminated later. 10500 if (D.getDeclSpec().hasTypeSpecifier()) 10501 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 10502 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 10503 << SourceRange(D.getIdentifierLoc()); 10504 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10505 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 10506 SourceLocation(), 10507 D.getDeclSpec().getConstSpecLoc(), 10508 D.getDeclSpec().getVolatileSpecLoc(), 10509 D.getDeclSpec().getRestrictSpecLoc(), 10510 D.getDeclSpec().getAtomicSpecLoc()); 10511 D.setInvalidType(); 10512 } 10513 } 10514 10515 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 10516 10517 // C++0x [class.dtor]p2: 10518 // A destructor shall not be declared with a ref-qualifier. 10519 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10520 if (FTI.hasRefQualifier()) { 10521 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 10522 << FTI.RefQualifierIsLValueRef 10523 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10524 D.setInvalidType(); 10525 } 10526 10527 // Make sure we don't have any parameters. 10528 if (FTIHasNonVoidParameters(FTI)) { 10529 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 10530 10531 // Delete the parameters. 10532 FTI.freeParams(); 10533 D.setInvalidType(); 10534 } 10535 10536 // Make sure the destructor isn't variadic. 10537 if (FTI.isVariadic) { 10538 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10539 D.setInvalidType(); 10540 } 10541 10542 // Rebuild the function type "R" without any type qualifiers or 10543 // parameters (in case any of the errors above fired) and with 10544 // "void" as the return type, since destructors don't have return 10545 // types. 10546 if (!D.isInvalidType()) 10547 return R; 10548 10549 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10550 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10551 EPI.Variadic = false; 10552 EPI.TypeQuals = Qualifiers(); 10553 EPI.RefQualifier = RQ_None; 10554 return Context.getFunctionType(Context.VoidTy, None, EPI); 10555 } 10556 10557 static void extendLeft(SourceRange &R, SourceRange Before) { 10558 if (Before.isInvalid()) 10559 return; 10560 R.setBegin(Before.getBegin()); 10561 if (R.getEnd().isInvalid()) 10562 R.setEnd(Before.getEnd()); 10563 } 10564 10565 static void extendRight(SourceRange &R, SourceRange After) { 10566 if (After.isInvalid()) 10567 return; 10568 if (R.getBegin().isInvalid()) 10569 R.setBegin(After.getBegin()); 10570 R.setEnd(After.getEnd()); 10571 } 10572 10573 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10574 /// well-formednes of the conversion function declarator @p D with 10575 /// type @p R. If there are any errors in the declarator, this routine 10576 /// will emit diagnostics and return true. Otherwise, it will return 10577 /// false. Either way, the type @p R will be updated to reflect a 10578 /// well-formed type for the conversion operator. 10579 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10580 StorageClass& SC) { 10581 // C++ [class.conv.fct]p1: 10582 // Neither parameter types nor return type can be specified. The 10583 // type of a conversion function (8.3.5) is "function taking no 10584 // parameter returning conversion-type-id." 10585 if (SC == SC_Static) { 10586 if (!D.isInvalidType()) 10587 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10588 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10589 << D.getName().getSourceRange(); 10590 D.setInvalidType(); 10591 SC = SC_None; 10592 } 10593 10594 TypeSourceInfo *ConvTSI = nullptr; 10595 QualType ConvType = 10596 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10597 10598 const DeclSpec &DS = D.getDeclSpec(); 10599 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10600 // Conversion functions don't have return types, but the parser will 10601 // happily parse something like: 10602 // 10603 // class X { 10604 // float operator bool(); 10605 // }; 10606 // 10607 // The return type will be changed later anyway. 10608 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10609 << SourceRange(DS.getTypeSpecTypeLoc()) 10610 << SourceRange(D.getIdentifierLoc()); 10611 D.setInvalidType(); 10612 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10613 // It's also plausible that the user writes type qualifiers in the wrong 10614 // place, such as: 10615 // struct S { const operator int(); }; 10616 // FIXME: we could provide a fixit to move the qualifiers onto the 10617 // conversion type. 10618 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10619 << SourceRange(D.getIdentifierLoc()) << 0; 10620 D.setInvalidType(); 10621 } 10622 10623 const auto *Proto = R->castAs<FunctionProtoType>(); 10624 10625 // Make sure we don't have any parameters. 10626 if (Proto->getNumParams() > 0) { 10627 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10628 10629 // Delete the parameters. 10630 D.getFunctionTypeInfo().freeParams(); 10631 D.setInvalidType(); 10632 } else if (Proto->isVariadic()) { 10633 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10634 D.setInvalidType(); 10635 } 10636 10637 // Diagnose "&operator bool()" and other such nonsense. This 10638 // is actually a gcc extension which we don't support. 10639 if (Proto->getReturnType() != ConvType) { 10640 bool NeedsTypedef = false; 10641 SourceRange Before, After; 10642 10643 // Walk the chunks and extract information on them for our diagnostic. 10644 bool PastFunctionChunk = false; 10645 for (auto &Chunk : D.type_objects()) { 10646 switch (Chunk.Kind) { 10647 case DeclaratorChunk::Function: 10648 if (!PastFunctionChunk) { 10649 if (Chunk.Fun.HasTrailingReturnType) { 10650 TypeSourceInfo *TRT = nullptr; 10651 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10652 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10653 } 10654 PastFunctionChunk = true; 10655 break; 10656 } 10657 LLVM_FALLTHROUGH; 10658 case DeclaratorChunk::Array: 10659 NeedsTypedef = true; 10660 extendRight(After, Chunk.getSourceRange()); 10661 break; 10662 10663 case DeclaratorChunk::Pointer: 10664 case DeclaratorChunk::BlockPointer: 10665 case DeclaratorChunk::Reference: 10666 case DeclaratorChunk::MemberPointer: 10667 case DeclaratorChunk::Pipe: 10668 extendLeft(Before, Chunk.getSourceRange()); 10669 break; 10670 10671 case DeclaratorChunk::Paren: 10672 extendLeft(Before, Chunk.Loc); 10673 extendRight(After, Chunk.EndLoc); 10674 break; 10675 } 10676 } 10677 10678 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10679 After.isValid() ? After.getBegin() : 10680 D.getIdentifierLoc(); 10681 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10682 DB << Before << After; 10683 10684 if (!NeedsTypedef) { 10685 DB << /*don't need a typedef*/0; 10686 10687 // If we can provide a correct fix-it hint, do so. 10688 if (After.isInvalid() && ConvTSI) { 10689 SourceLocation InsertLoc = 10690 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10691 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10692 << FixItHint::CreateInsertionFromRange( 10693 InsertLoc, CharSourceRange::getTokenRange(Before)) 10694 << FixItHint::CreateRemoval(Before); 10695 } 10696 } else if (!Proto->getReturnType()->isDependentType()) { 10697 DB << /*typedef*/1 << Proto->getReturnType(); 10698 } else if (getLangOpts().CPlusPlus11) { 10699 DB << /*alias template*/2 << Proto->getReturnType(); 10700 } else { 10701 DB << /*might not be fixable*/3; 10702 } 10703 10704 // Recover by incorporating the other type chunks into the result type. 10705 // Note, this does *not* change the name of the function. This is compatible 10706 // with the GCC extension: 10707 // struct S { &operator int(); } s; 10708 // int &r = s.operator int(); // ok in GCC 10709 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10710 ConvType = Proto->getReturnType(); 10711 } 10712 10713 // C++ [class.conv.fct]p4: 10714 // The conversion-type-id shall not represent a function type nor 10715 // an array type. 10716 if (ConvType->isArrayType()) { 10717 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10718 ConvType = Context.getPointerType(ConvType); 10719 D.setInvalidType(); 10720 } else if (ConvType->isFunctionType()) { 10721 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10722 ConvType = Context.getPointerType(ConvType); 10723 D.setInvalidType(); 10724 } 10725 10726 // Rebuild the function type "R" without any parameters (in case any 10727 // of the errors above fired) and with the conversion type as the 10728 // return type. 10729 if (D.isInvalidType()) 10730 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 10731 10732 // C++0x explicit conversion operators. 10733 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20) 10734 Diag(DS.getExplicitSpecLoc(), 10735 getLangOpts().CPlusPlus11 10736 ? diag::warn_cxx98_compat_explicit_conversion_functions 10737 : diag::ext_explicit_conversion_functions) 10738 << SourceRange(DS.getExplicitSpecRange()); 10739 } 10740 10741 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 10742 /// the declaration of the given C++ conversion function. This routine 10743 /// is responsible for recording the conversion function in the C++ 10744 /// class, if possible. 10745 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 10746 assert(Conversion && "Expected to receive a conversion function declaration"); 10747 10748 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 10749 10750 // Make sure we aren't redeclaring the conversion function. 10751 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 10752 // C++ [class.conv.fct]p1: 10753 // [...] A conversion function is never used to convert a 10754 // (possibly cv-qualified) object to the (possibly cv-qualified) 10755 // same object type (or a reference to it), to a (possibly 10756 // cv-qualified) base class of that type (or a reference to it), 10757 // or to (possibly cv-qualified) void. 10758 QualType ClassType 10759 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10760 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 10761 ConvType = ConvTypeRef->getPointeeType(); 10762 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 10763 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 10764 /* Suppress diagnostics for instantiations. */; 10765 else if (Conversion->size_overridden_methods() != 0) 10766 /* Suppress diagnostics for overriding virtual function in a base class. */; 10767 else if (ConvType->isRecordType()) { 10768 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 10769 if (ConvType == ClassType) 10770 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 10771 << ClassType; 10772 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 10773 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 10774 << ClassType << ConvType; 10775 } else if (ConvType->isVoidType()) { 10776 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 10777 << ClassType << ConvType; 10778 } 10779 10780 if (FunctionTemplateDecl *ConversionTemplate 10781 = Conversion->getDescribedFunctionTemplate()) 10782 return ConversionTemplate; 10783 10784 return Conversion; 10785 } 10786 10787 namespace { 10788 /// Utility class to accumulate and print a diagnostic listing the invalid 10789 /// specifier(s) on a declaration. 10790 struct BadSpecifierDiagnoser { 10791 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10792 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10793 ~BadSpecifierDiagnoser() { 10794 Diagnostic << Specifiers; 10795 } 10796 10797 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10798 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10799 } 10800 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10801 return check(SpecLoc, 10802 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10803 } 10804 void check(SourceLocation SpecLoc, const char *Spec) { 10805 if (SpecLoc.isInvalid()) return; 10806 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10807 if (!Specifiers.empty()) Specifiers += " "; 10808 Specifiers += Spec; 10809 } 10810 10811 Sema &S; 10812 Sema::SemaDiagnosticBuilder Diagnostic; 10813 std::string Specifiers; 10814 }; 10815 } 10816 10817 /// Check the validity of a declarator that we parsed for a deduction-guide. 10818 /// These aren't actually declarators in the grammar, so we need to check that 10819 /// the user didn't specify any pieces that are not part of the deduction-guide 10820 /// grammar. 10821 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10822 StorageClass &SC) { 10823 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10824 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10825 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 10826 10827 // C++ [temp.deduct.guide]p3: 10828 // A deduction-gide shall be declared in the same scope as the 10829 // corresponding class template. 10830 if (!CurContext->getRedeclContext()->Equals( 10831 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10832 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10833 << GuidedTemplateDecl; 10834 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10835 } 10836 10837 auto &DS = D.getMutableDeclSpec(); 10838 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10839 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10840 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10841 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10842 BadSpecifierDiagnoser Diagnoser( 10843 *this, D.getIdentifierLoc(), 10844 diag::err_deduction_guide_invalid_specifier); 10845 10846 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10847 DS.ClearStorageClassSpecs(); 10848 SC = SC_None; 10849 10850 // 'explicit' is permitted. 10851 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10852 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10853 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10854 DS.ClearConstexprSpec(); 10855 10856 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10857 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10858 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10859 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10860 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10861 DS.ClearTypeQualifiers(); 10862 10863 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 10864 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 10865 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 10866 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 10867 DS.ClearTypeSpecType(); 10868 } 10869 10870 if (D.isInvalidType()) 10871 return; 10872 10873 // Check the declarator is simple enough. 10874 bool FoundFunction = false; 10875 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 10876 if (Chunk.Kind == DeclaratorChunk::Paren) 10877 continue; 10878 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 10879 Diag(D.getDeclSpec().getBeginLoc(), 10880 diag::err_deduction_guide_with_complex_decl) 10881 << D.getSourceRange(); 10882 break; 10883 } 10884 if (!Chunk.Fun.hasTrailingReturnType()) { 10885 Diag(D.getName().getBeginLoc(), 10886 diag::err_deduction_guide_no_trailing_return_type); 10887 break; 10888 } 10889 10890 // Check that the return type is written as a specialization of 10891 // the template specified as the deduction-guide's name. 10892 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 10893 TypeSourceInfo *TSI = nullptr; 10894 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 10895 assert(TSI && "deduction guide has valid type but invalid return type?"); 10896 bool AcceptableReturnType = false; 10897 bool MightInstantiateToSpecialization = false; 10898 if (auto RetTST = 10899 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 10900 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 10901 bool TemplateMatches = 10902 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 10903 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 10904 AcceptableReturnType = true; 10905 else { 10906 // This could still instantiate to the right type, unless we know it 10907 // names the wrong class template. 10908 auto *TD = SpecifiedName.getAsTemplateDecl(); 10909 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 10910 !TemplateMatches); 10911 } 10912 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 10913 MightInstantiateToSpecialization = true; 10914 } 10915 10916 if (!AcceptableReturnType) { 10917 Diag(TSI->getTypeLoc().getBeginLoc(), 10918 diag::err_deduction_guide_bad_trailing_return_type) 10919 << GuidedTemplate << TSI->getType() 10920 << MightInstantiateToSpecialization 10921 << TSI->getTypeLoc().getSourceRange(); 10922 } 10923 10924 // Keep going to check that we don't have any inner declarator pieces (we 10925 // could still have a function returning a pointer to a function). 10926 FoundFunction = true; 10927 } 10928 10929 if (D.isFunctionDefinition()) 10930 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 10931 } 10932 10933 //===----------------------------------------------------------------------===// 10934 // Namespace Handling 10935 //===----------------------------------------------------------------------===// 10936 10937 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 10938 /// reopened. 10939 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 10940 SourceLocation Loc, 10941 IdentifierInfo *II, bool *IsInline, 10942 NamespaceDecl *PrevNS) { 10943 assert(*IsInline != PrevNS->isInline()); 10944 10945 if (PrevNS->isInline()) 10946 // The user probably just forgot the 'inline', so suggest that it 10947 // be added back. 10948 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 10949 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 10950 else 10951 S.Diag(Loc, diag::err_inline_namespace_mismatch); 10952 10953 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 10954 *IsInline = PrevNS->isInline(); 10955 } 10956 10957 /// ActOnStartNamespaceDef - This is called at the start of a namespace 10958 /// definition. 10959 Decl *Sema::ActOnStartNamespaceDef( 10960 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 10961 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 10962 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 10963 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 10964 // For anonymous namespace, take the location of the left brace. 10965 SourceLocation Loc = II ? IdentLoc : LBrace; 10966 bool IsInline = InlineLoc.isValid(); 10967 bool IsInvalid = false; 10968 bool IsStd = false; 10969 bool AddToKnown = false; 10970 Scope *DeclRegionScope = NamespcScope->getParent(); 10971 10972 NamespaceDecl *PrevNS = nullptr; 10973 if (II) { 10974 // C++ [namespace.def]p2: 10975 // The identifier in an original-namespace-definition shall not 10976 // have been previously defined in the declarative region in 10977 // which the original-namespace-definition appears. The 10978 // identifier in an original-namespace-definition is the name of 10979 // the namespace. Subsequently in that declarative region, it is 10980 // treated as an original-namespace-name. 10981 // 10982 // Since namespace names are unique in their scope, and we don't 10983 // look through using directives, just look for any ordinary names 10984 // as if by qualified name lookup. 10985 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 10986 ForExternalRedeclaration); 10987 LookupQualifiedName(R, CurContext->getRedeclContext()); 10988 NamedDecl *PrevDecl = 10989 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 10990 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 10991 10992 if (PrevNS) { 10993 // This is an extended namespace definition. 10994 if (IsInline != PrevNS->isInline()) 10995 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 10996 &IsInline, PrevNS); 10997 } else if (PrevDecl) { 10998 // This is an invalid name redefinition. 10999 Diag(Loc, diag::err_redefinition_different_kind) 11000 << II; 11001 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11002 IsInvalid = true; 11003 // Continue on to push Namespc as current DeclContext and return it. 11004 } else if (II->isStr("std") && 11005 CurContext->getRedeclContext()->isTranslationUnit()) { 11006 // This is the first "real" definition of the namespace "std", so update 11007 // our cache of the "std" namespace to point at this definition. 11008 PrevNS = getStdNamespace(); 11009 IsStd = true; 11010 AddToKnown = !IsInline; 11011 } else { 11012 // We've seen this namespace for the first time. 11013 AddToKnown = !IsInline; 11014 } 11015 } else { 11016 // Anonymous namespaces. 11017 11018 // Determine whether the parent already has an anonymous namespace. 11019 DeclContext *Parent = CurContext->getRedeclContext(); 11020 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11021 PrevNS = TU->getAnonymousNamespace(); 11022 } else { 11023 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 11024 PrevNS = ND->getAnonymousNamespace(); 11025 } 11026 11027 if (PrevNS && IsInline != PrevNS->isInline()) 11028 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 11029 &IsInline, PrevNS); 11030 } 11031 11032 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 11033 StartLoc, Loc, II, PrevNS); 11034 if (IsInvalid) 11035 Namespc->setInvalidDecl(); 11036 11037 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 11038 AddPragmaAttributes(DeclRegionScope, Namespc); 11039 11040 // FIXME: Should we be merging attributes? 11041 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 11042 PushNamespaceVisibilityAttr(Attr, Loc); 11043 11044 if (IsStd) 11045 StdNamespace = Namespc; 11046 if (AddToKnown) 11047 KnownNamespaces[Namespc] = false; 11048 11049 if (II) { 11050 PushOnScopeChains(Namespc, DeclRegionScope); 11051 } else { 11052 // Link the anonymous namespace into its parent. 11053 DeclContext *Parent = CurContext->getRedeclContext(); 11054 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11055 TU->setAnonymousNamespace(Namespc); 11056 } else { 11057 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 11058 } 11059 11060 CurContext->addDecl(Namespc); 11061 11062 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 11063 // behaves as if it were replaced by 11064 // namespace unique { /* empty body */ } 11065 // using namespace unique; 11066 // namespace unique { namespace-body } 11067 // where all occurrences of 'unique' in a translation unit are 11068 // replaced by the same identifier and this identifier differs 11069 // from all other identifiers in the entire program. 11070 11071 // We just create the namespace with an empty name and then add an 11072 // implicit using declaration, just like the standard suggests. 11073 // 11074 // CodeGen enforces the "universally unique" aspect by giving all 11075 // declarations semantically contained within an anonymous 11076 // namespace internal linkage. 11077 11078 if (!PrevNS) { 11079 UD = UsingDirectiveDecl::Create(Context, Parent, 11080 /* 'using' */ LBrace, 11081 /* 'namespace' */ SourceLocation(), 11082 /* qualifier */ NestedNameSpecifierLoc(), 11083 /* identifier */ SourceLocation(), 11084 Namespc, 11085 /* Ancestor */ Parent); 11086 UD->setImplicit(); 11087 Parent->addDecl(UD); 11088 } 11089 } 11090 11091 ActOnDocumentableDecl(Namespc); 11092 11093 // Although we could have an invalid decl (i.e. the namespace name is a 11094 // redefinition), push it as current DeclContext and try to continue parsing. 11095 // FIXME: We should be able to push Namespc here, so that the each DeclContext 11096 // for the namespace has the declarations that showed up in that particular 11097 // namespace definition. 11098 PushDeclContext(NamespcScope, Namespc); 11099 return Namespc; 11100 } 11101 11102 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 11103 /// is a namespace alias, returns the namespace it points to. 11104 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 11105 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 11106 return AD->getNamespace(); 11107 return dyn_cast_or_null<NamespaceDecl>(D); 11108 } 11109 11110 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 11111 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 11112 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 11113 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 11114 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 11115 Namespc->setRBraceLoc(RBrace); 11116 PopDeclContext(); 11117 if (Namespc->hasAttr<VisibilityAttr>()) 11118 PopPragmaVisibility(true, RBrace); 11119 // If this namespace contains an export-declaration, export it now. 11120 if (DeferredExportedNamespaces.erase(Namespc)) 11121 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 11122 } 11123 11124 CXXRecordDecl *Sema::getStdBadAlloc() const { 11125 return cast_or_null<CXXRecordDecl>( 11126 StdBadAlloc.get(Context.getExternalSource())); 11127 } 11128 11129 EnumDecl *Sema::getStdAlignValT() const { 11130 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 11131 } 11132 11133 NamespaceDecl *Sema::getStdNamespace() const { 11134 return cast_or_null<NamespaceDecl>( 11135 StdNamespace.get(Context.getExternalSource())); 11136 } 11137 11138 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 11139 if (!StdExperimentalNamespaceCache) { 11140 if (auto Std = getStdNamespace()) { 11141 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 11142 SourceLocation(), LookupNamespaceName); 11143 if (!LookupQualifiedName(Result, Std) || 11144 !(StdExperimentalNamespaceCache = 11145 Result.getAsSingle<NamespaceDecl>())) 11146 Result.suppressDiagnostics(); 11147 } 11148 } 11149 return StdExperimentalNamespaceCache; 11150 } 11151 11152 namespace { 11153 11154 enum UnsupportedSTLSelect { 11155 USS_InvalidMember, 11156 USS_MissingMember, 11157 USS_NonTrivial, 11158 USS_Other 11159 }; 11160 11161 struct InvalidSTLDiagnoser { 11162 Sema &S; 11163 SourceLocation Loc; 11164 QualType TyForDiags; 11165 11166 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 11167 const VarDecl *VD = nullptr) { 11168 { 11169 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 11170 << TyForDiags << ((int)Sel); 11171 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 11172 assert(!Name.empty()); 11173 D << Name; 11174 } 11175 } 11176 if (Sel == USS_InvalidMember) { 11177 S.Diag(VD->getLocation(), diag::note_var_declared_here) 11178 << VD << VD->getSourceRange(); 11179 } 11180 return QualType(); 11181 } 11182 }; 11183 } // namespace 11184 11185 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 11186 SourceLocation Loc, 11187 ComparisonCategoryUsage Usage) { 11188 assert(getLangOpts().CPlusPlus && 11189 "Looking for comparison category type outside of C++."); 11190 11191 // Use an elaborated type for diagnostics which has a name containing the 11192 // prepended 'std' namespace but not any inline namespace names. 11193 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 11194 auto *NNS = 11195 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 11196 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 11197 }; 11198 11199 // Check if we've already successfully checked the comparison category type 11200 // before. If so, skip checking it again. 11201 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 11202 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 11203 // The only thing we need to check is that the type has a reachable 11204 // definition in the current context. 11205 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11206 return QualType(); 11207 11208 return Info->getType(); 11209 } 11210 11211 // If lookup failed 11212 if (!Info) { 11213 std::string NameForDiags = "std::"; 11214 NameForDiags += ComparisonCategories::getCategoryString(Kind); 11215 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 11216 << NameForDiags << (int)Usage; 11217 return QualType(); 11218 } 11219 11220 assert(Info->Kind == Kind); 11221 assert(Info->Record); 11222 11223 // Update the Record decl in case we encountered a forward declaration on our 11224 // first pass. FIXME: This is a bit of a hack. 11225 if (Info->Record->hasDefinition()) 11226 Info->Record = Info->Record->getDefinition(); 11227 11228 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11229 return QualType(); 11230 11231 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 11232 11233 if (!Info->Record->isTriviallyCopyable()) 11234 return UnsupportedSTLError(USS_NonTrivial); 11235 11236 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 11237 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 11238 // Tolerate empty base classes. 11239 if (Base->isEmpty()) 11240 continue; 11241 // Reject STL implementations which have at least one non-empty base. 11242 return UnsupportedSTLError(); 11243 } 11244 11245 // Check that the STL has implemented the types using a single integer field. 11246 // This expectation allows better codegen for builtin operators. We require: 11247 // (1) The class has exactly one field. 11248 // (2) The field is an integral or enumeration type. 11249 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 11250 if (std::distance(FIt, FEnd) != 1 || 11251 !FIt->getType()->isIntegralOrEnumerationType()) { 11252 return UnsupportedSTLError(); 11253 } 11254 11255 // Build each of the require values and store them in Info. 11256 for (ComparisonCategoryResult CCR : 11257 ComparisonCategories::getPossibleResultsForType(Kind)) { 11258 StringRef MemName = ComparisonCategories::getResultString(CCR); 11259 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 11260 11261 if (!ValInfo) 11262 return UnsupportedSTLError(USS_MissingMember, MemName); 11263 11264 VarDecl *VD = ValInfo->VD; 11265 assert(VD && "should not be null!"); 11266 11267 // Attempt to diagnose reasons why the STL definition of this type 11268 // might be foobar, including it failing to be a constant expression. 11269 // TODO Handle more ways the lookup or result can be invalid. 11270 if (!VD->isStaticDataMember() || 11271 !VD->isUsableInConstantExpressions(Context)) 11272 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 11273 11274 // Attempt to evaluate the var decl as a constant expression and extract 11275 // the value of its first field as a ICE. If this fails, the STL 11276 // implementation is not supported. 11277 if (!ValInfo->hasValidIntValue()) 11278 return UnsupportedSTLError(); 11279 11280 MarkVariableReferenced(Loc, VD); 11281 } 11282 11283 // We've successfully built the required types and expressions. Update 11284 // the cache and return the newly cached value. 11285 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 11286 return Info->getType(); 11287 } 11288 11289 /// Retrieve the special "std" namespace, which may require us to 11290 /// implicitly define the namespace. 11291 NamespaceDecl *Sema::getOrCreateStdNamespace() { 11292 if (!StdNamespace) { 11293 // The "std" namespace has not yet been defined, so build one implicitly. 11294 StdNamespace = NamespaceDecl::Create(Context, 11295 Context.getTranslationUnitDecl(), 11296 /*Inline=*/false, 11297 SourceLocation(), SourceLocation(), 11298 &PP.getIdentifierTable().get("std"), 11299 /*PrevDecl=*/nullptr); 11300 getStdNamespace()->setImplicit(true); 11301 } 11302 11303 return getStdNamespace(); 11304 } 11305 11306 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 11307 assert(getLangOpts().CPlusPlus && 11308 "Looking for std::initializer_list outside of C++."); 11309 11310 // We're looking for implicit instantiations of 11311 // template <typename E> class std::initializer_list. 11312 11313 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 11314 return false; 11315 11316 ClassTemplateDecl *Template = nullptr; 11317 const TemplateArgument *Arguments = nullptr; 11318 11319 if (const RecordType *RT = Ty->getAs<RecordType>()) { 11320 11321 ClassTemplateSpecializationDecl *Specialization = 11322 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 11323 if (!Specialization) 11324 return false; 11325 11326 Template = Specialization->getSpecializedTemplate(); 11327 Arguments = Specialization->getTemplateArgs().data(); 11328 } else if (const TemplateSpecializationType *TST = 11329 Ty->getAs<TemplateSpecializationType>()) { 11330 Template = dyn_cast_or_null<ClassTemplateDecl>( 11331 TST->getTemplateName().getAsTemplateDecl()); 11332 Arguments = TST->getArgs(); 11333 } 11334 if (!Template) 11335 return false; 11336 11337 if (!StdInitializerList) { 11338 // Haven't recognized std::initializer_list yet, maybe this is it. 11339 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 11340 if (TemplateClass->getIdentifier() != 11341 &PP.getIdentifierTable().get("initializer_list") || 11342 !getStdNamespace()->InEnclosingNamespaceSetOf( 11343 TemplateClass->getDeclContext())) 11344 return false; 11345 // This is a template called std::initializer_list, but is it the right 11346 // template? 11347 TemplateParameterList *Params = Template->getTemplateParameters(); 11348 if (Params->getMinRequiredArguments() != 1) 11349 return false; 11350 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 11351 return false; 11352 11353 // It's the right template. 11354 StdInitializerList = Template; 11355 } 11356 11357 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 11358 return false; 11359 11360 // This is an instance of std::initializer_list. Find the argument type. 11361 if (Element) 11362 *Element = Arguments[0].getAsType(); 11363 return true; 11364 } 11365 11366 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 11367 NamespaceDecl *Std = S.getStdNamespace(); 11368 if (!Std) { 11369 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11370 return nullptr; 11371 } 11372 11373 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 11374 Loc, Sema::LookupOrdinaryName); 11375 if (!S.LookupQualifiedName(Result, Std)) { 11376 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11377 return nullptr; 11378 } 11379 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 11380 if (!Template) { 11381 Result.suppressDiagnostics(); 11382 // We found something weird. Complain about the first thing we found. 11383 NamedDecl *Found = *Result.begin(); 11384 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 11385 return nullptr; 11386 } 11387 11388 // We found some template called std::initializer_list. Now verify that it's 11389 // correct. 11390 TemplateParameterList *Params = Template->getTemplateParameters(); 11391 if (Params->getMinRequiredArguments() != 1 || 11392 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 11393 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 11394 return nullptr; 11395 } 11396 11397 return Template; 11398 } 11399 11400 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 11401 if (!StdInitializerList) { 11402 StdInitializerList = LookupStdInitializerList(*this, Loc); 11403 if (!StdInitializerList) 11404 return QualType(); 11405 } 11406 11407 TemplateArgumentListInfo Args(Loc, Loc); 11408 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 11409 Context.getTrivialTypeSourceInfo(Element, 11410 Loc))); 11411 return Context.getCanonicalType( 11412 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 11413 } 11414 11415 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 11416 // C++ [dcl.init.list]p2: 11417 // A constructor is an initializer-list constructor if its first parameter 11418 // is of type std::initializer_list<E> or reference to possibly cv-qualified 11419 // std::initializer_list<E> for some type E, and either there are no other 11420 // parameters or else all other parameters have default arguments. 11421 if (!Ctor->hasOneParamOrDefaultArgs()) 11422 return false; 11423 11424 QualType ArgType = Ctor->getParamDecl(0)->getType(); 11425 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 11426 ArgType = RT->getPointeeType().getUnqualifiedType(); 11427 11428 return isStdInitializerList(ArgType, nullptr); 11429 } 11430 11431 /// Determine whether a using statement is in a context where it will be 11432 /// apply in all contexts. 11433 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 11434 switch (CurContext->getDeclKind()) { 11435 case Decl::TranslationUnit: 11436 return true; 11437 case Decl::LinkageSpec: 11438 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 11439 default: 11440 return false; 11441 } 11442 } 11443 11444 namespace { 11445 11446 // Callback to only accept typo corrections that are namespaces. 11447 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 11448 public: 11449 bool ValidateCandidate(const TypoCorrection &candidate) override { 11450 if (NamedDecl *ND = candidate.getCorrectionDecl()) 11451 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 11452 return false; 11453 } 11454 11455 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11456 return std::make_unique<NamespaceValidatorCCC>(*this); 11457 } 11458 }; 11459 11460 } 11461 11462 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 11463 CXXScopeSpec &SS, 11464 SourceLocation IdentLoc, 11465 IdentifierInfo *Ident) { 11466 R.clear(); 11467 NamespaceValidatorCCC CCC{}; 11468 if (TypoCorrection Corrected = 11469 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 11470 Sema::CTK_ErrorRecovery)) { 11471 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 11472 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 11473 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 11474 Ident->getName().equals(CorrectedStr); 11475 S.diagnoseTypo(Corrected, 11476 S.PDiag(diag::err_using_directive_member_suggest) 11477 << Ident << DC << DroppedSpecifier << SS.getRange(), 11478 S.PDiag(diag::note_namespace_defined_here)); 11479 } else { 11480 S.diagnoseTypo(Corrected, 11481 S.PDiag(diag::err_using_directive_suggest) << Ident, 11482 S.PDiag(diag::note_namespace_defined_here)); 11483 } 11484 R.addDecl(Corrected.getFoundDecl()); 11485 return true; 11486 } 11487 return false; 11488 } 11489 11490 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 11491 SourceLocation NamespcLoc, CXXScopeSpec &SS, 11492 SourceLocation IdentLoc, 11493 IdentifierInfo *NamespcName, 11494 const ParsedAttributesView &AttrList) { 11495 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11496 assert(NamespcName && "Invalid NamespcName."); 11497 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 11498 11499 // This can only happen along a recovery path. 11500 while (S->isTemplateParamScope()) 11501 S = S->getParent(); 11502 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11503 11504 UsingDirectiveDecl *UDir = nullptr; 11505 NestedNameSpecifier *Qualifier = nullptr; 11506 if (SS.isSet()) 11507 Qualifier = SS.getScopeRep(); 11508 11509 // Lookup namespace name. 11510 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 11511 LookupParsedName(R, S, &SS); 11512 if (R.isAmbiguous()) 11513 return nullptr; 11514 11515 if (R.empty()) { 11516 R.clear(); 11517 // Allow "using namespace std;" or "using namespace ::std;" even if 11518 // "std" hasn't been defined yet, for GCC compatibility. 11519 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11520 NamespcName->isStr("std")) { 11521 Diag(IdentLoc, diag::ext_using_undefined_std); 11522 R.addDecl(getOrCreateStdNamespace()); 11523 R.resolveKind(); 11524 } 11525 // Otherwise, attempt typo correction. 11526 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11527 } 11528 11529 if (!R.empty()) { 11530 NamedDecl *Named = R.getRepresentativeDecl(); 11531 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11532 assert(NS && "expected namespace decl"); 11533 11534 // The use of a nested name specifier may trigger deprecation warnings. 11535 DiagnoseUseOfDecl(Named, IdentLoc); 11536 11537 // C++ [namespace.udir]p1: 11538 // A using-directive specifies that the names in the nominated 11539 // namespace can be used in the scope in which the 11540 // using-directive appears after the using-directive. During 11541 // unqualified name lookup (3.4.1), the names appear as if they 11542 // were declared in the nearest enclosing namespace which 11543 // contains both the using-directive and the nominated 11544 // namespace. [Note: in this context, "contains" means "contains 11545 // directly or indirectly". ] 11546 11547 // Find enclosing context containing both using-directive and 11548 // nominated namespace. 11549 DeclContext *CommonAncestor = NS; 11550 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11551 CommonAncestor = CommonAncestor->getParent(); 11552 11553 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11554 SS.getWithLocInContext(Context), 11555 IdentLoc, Named, CommonAncestor); 11556 11557 if (IsUsingDirectiveInToplevelContext(CurContext) && 11558 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11559 Diag(IdentLoc, diag::warn_using_directive_in_header); 11560 } 11561 11562 PushUsingDirective(S, UDir); 11563 } else { 11564 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11565 } 11566 11567 if (UDir) 11568 ProcessDeclAttributeList(S, UDir, AttrList); 11569 11570 return UDir; 11571 } 11572 11573 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11574 // If the scope has an associated entity and the using directive is at 11575 // namespace or translation unit scope, add the UsingDirectiveDecl into 11576 // its lookup structure so qualified name lookup can find it. 11577 DeclContext *Ctx = S->getEntity(); 11578 if (Ctx && !Ctx->isFunctionOrMethod()) 11579 Ctx->addDecl(UDir); 11580 else 11581 // Otherwise, it is at block scope. The using-directives will affect lookup 11582 // only to the end of the scope. 11583 S->PushUsingDirective(UDir); 11584 } 11585 11586 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11587 SourceLocation UsingLoc, 11588 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11589 UnqualifiedId &Name, 11590 SourceLocation EllipsisLoc, 11591 const ParsedAttributesView &AttrList) { 11592 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11593 11594 if (SS.isEmpty()) { 11595 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11596 return nullptr; 11597 } 11598 11599 switch (Name.getKind()) { 11600 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11601 case UnqualifiedIdKind::IK_Identifier: 11602 case UnqualifiedIdKind::IK_OperatorFunctionId: 11603 case UnqualifiedIdKind::IK_LiteralOperatorId: 11604 case UnqualifiedIdKind::IK_ConversionFunctionId: 11605 break; 11606 11607 case UnqualifiedIdKind::IK_ConstructorName: 11608 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11609 // C++11 inheriting constructors. 11610 Diag(Name.getBeginLoc(), 11611 getLangOpts().CPlusPlus11 11612 ? diag::warn_cxx98_compat_using_decl_constructor 11613 : diag::err_using_decl_constructor) 11614 << SS.getRange(); 11615 11616 if (getLangOpts().CPlusPlus11) break; 11617 11618 return nullptr; 11619 11620 case UnqualifiedIdKind::IK_DestructorName: 11621 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11622 return nullptr; 11623 11624 case UnqualifiedIdKind::IK_TemplateId: 11625 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11626 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11627 return nullptr; 11628 11629 case UnqualifiedIdKind::IK_DeductionGuideName: 11630 llvm_unreachable("cannot parse qualified deduction guide name"); 11631 } 11632 11633 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11634 DeclarationName TargetName = TargetNameInfo.getName(); 11635 if (!TargetName) 11636 return nullptr; 11637 11638 // Warn about access declarations. 11639 if (UsingLoc.isInvalid()) { 11640 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11641 ? diag::err_access_decl 11642 : diag::warn_access_decl_deprecated) 11643 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11644 } 11645 11646 if (EllipsisLoc.isInvalid()) { 11647 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11648 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11649 return nullptr; 11650 } else { 11651 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11652 !TargetNameInfo.containsUnexpandedParameterPack()) { 11653 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11654 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11655 EllipsisLoc = SourceLocation(); 11656 } 11657 } 11658 11659 NamedDecl *UD = 11660 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 11661 SS, TargetNameInfo, EllipsisLoc, AttrList, 11662 /*IsInstantiation*/ false, 11663 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists)); 11664 if (UD) 11665 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11666 11667 return UD; 11668 } 11669 11670 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 11671 SourceLocation UsingLoc, 11672 SourceLocation EnumLoc, 11673 const DeclSpec &DS) { 11674 switch (DS.getTypeSpecType()) { 11675 case DeclSpec::TST_error: 11676 // This will already have been diagnosed 11677 return nullptr; 11678 11679 case DeclSpec::TST_enum: 11680 break; 11681 11682 case DeclSpec::TST_typename: 11683 Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent); 11684 return nullptr; 11685 11686 default: 11687 llvm_unreachable("unexpected DeclSpec type"); 11688 } 11689 11690 // As with enum-decls, we ignore attributes for now. 11691 auto *Enum = cast<EnumDecl>(DS.getRepAsDecl()); 11692 if (auto *Def = Enum->getDefinition()) 11693 Enum = Def; 11694 11695 auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, 11696 DS.getTypeSpecTypeNameLoc(), Enum); 11697 if (UD) 11698 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11699 11700 return UD; 11701 } 11702 11703 /// Determine whether a using declaration considers the given 11704 /// declarations as "equivalent", e.g., if they are redeclarations of 11705 /// the same entity or are both typedefs of the same type. 11706 static bool 11707 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11708 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11709 return true; 11710 11711 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11712 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11713 return Context.hasSameType(TD1->getUnderlyingType(), 11714 TD2->getUnderlyingType()); 11715 11716 // Two using_if_exists using-declarations are equivalent if both are 11717 // unresolved. 11718 if (isa<UnresolvedUsingIfExistsDecl>(D1) && 11719 isa<UnresolvedUsingIfExistsDecl>(D2)) 11720 return true; 11721 11722 return false; 11723 } 11724 11725 11726 /// Determines whether to create a using shadow decl for a particular 11727 /// decl, given the set of decls existing prior to this using lookup. 11728 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig, 11729 const LookupResult &Previous, 11730 UsingShadowDecl *&PrevShadow) { 11731 // Diagnose finding a decl which is not from a base class of the 11732 // current class. We do this now because there are cases where this 11733 // function will silently decide not to build a shadow decl, which 11734 // will pre-empt further diagnostics. 11735 // 11736 // We don't need to do this in C++11 because we do the check once on 11737 // the qualifier. 11738 // 11739 // FIXME: diagnose the following if we care enough: 11740 // struct A { int foo; }; 11741 // struct B : A { using A::foo; }; 11742 // template <class T> struct C : A {}; 11743 // template <class T> struct D : C<T> { using B::foo; } // <--- 11744 // This is invalid (during instantiation) in C++03 because B::foo 11745 // resolves to the using decl in B, which is not a base class of D<T>. 11746 // We can't diagnose it immediately because C<T> is an unknown 11747 // specialization. The UsingShadowDecl in D<T> then points directly 11748 // to A::foo, which will look well-formed when we instantiate. 11749 // The right solution is to not collapse the shadow-decl chain. 11750 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) 11751 if (auto *Using = dyn_cast<UsingDecl>(BUD)) { 11752 DeclContext *OrigDC = Orig->getDeclContext(); 11753 11754 // Handle enums and anonymous structs. 11755 if (isa<EnumDecl>(OrigDC)) 11756 OrigDC = OrigDC->getParent(); 11757 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 11758 while (OrigRec->isAnonymousStructOrUnion()) 11759 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 11760 11761 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 11762 if (OrigDC == CurContext) { 11763 Diag(Using->getLocation(), 11764 diag::err_using_decl_nested_name_specifier_is_current_class) 11765 << Using->getQualifierLoc().getSourceRange(); 11766 Diag(Orig->getLocation(), diag::note_using_decl_target); 11767 Using->setInvalidDecl(); 11768 return true; 11769 } 11770 11771 Diag(Using->getQualifierLoc().getBeginLoc(), 11772 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11773 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext) 11774 << Using->getQualifierLoc().getSourceRange(); 11775 Diag(Orig->getLocation(), diag::note_using_decl_target); 11776 Using->setInvalidDecl(); 11777 return true; 11778 } 11779 } 11780 11781 if (Previous.empty()) return false; 11782 11783 NamedDecl *Target = Orig; 11784 if (isa<UsingShadowDecl>(Target)) 11785 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11786 11787 // If the target happens to be one of the previous declarations, we 11788 // don't have a conflict. 11789 // 11790 // FIXME: but we might be increasing its access, in which case we 11791 // should redeclare it. 11792 NamedDecl *NonTag = nullptr, *Tag = nullptr; 11793 bool FoundEquivalentDecl = false; 11794 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 11795 I != E; ++I) { 11796 NamedDecl *D = (*I)->getUnderlyingDecl(); 11797 // We can have UsingDecls in our Previous results because we use the same 11798 // LookupResult for checking whether the UsingDecl itself is a valid 11799 // redeclaration. 11800 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D)) 11801 continue; 11802 11803 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 11804 // C++ [class.mem]p19: 11805 // If T is the name of a class, then [every named member other than 11806 // a non-static data member] shall have a name different from T 11807 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11808 !isa<IndirectFieldDecl>(Target) && 11809 !isa<UnresolvedUsingValueDecl>(Target) && 11810 DiagnoseClassNameShadow( 11811 CurContext, 11812 DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation()))) 11813 return true; 11814 } 11815 11816 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11817 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11818 PrevShadow = Shadow; 11819 FoundEquivalentDecl = true; 11820 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11821 // We don't conflict with an existing using shadow decl of an equivalent 11822 // declaration, but we're not a redeclaration of it. 11823 FoundEquivalentDecl = true; 11824 } 11825 11826 if (isVisible(D)) 11827 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11828 } 11829 11830 if (FoundEquivalentDecl) 11831 return false; 11832 11833 // Always emit a diagnostic for a mismatch between an unresolved 11834 // using_if_exists and a resolved using declaration in either direction. 11835 if (isa<UnresolvedUsingIfExistsDecl>(Target) != 11836 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) { 11837 if (!NonTag && !Tag) 11838 return false; 11839 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11840 Diag(Target->getLocation(), diag::note_using_decl_target); 11841 Diag((NonTag ? NonTag : Tag)->getLocation(), 11842 diag::note_using_decl_conflict); 11843 BUD->setInvalidDecl(); 11844 return true; 11845 } 11846 11847 if (FunctionDecl *FD = Target->getAsFunction()) { 11848 NamedDecl *OldDecl = nullptr; 11849 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11850 /*IsForUsingDecl*/ true)) { 11851 case Ovl_Overload: 11852 return false; 11853 11854 case Ovl_NonFunction: 11855 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11856 break; 11857 11858 // We found a decl with the exact signature. 11859 case Ovl_Match: 11860 // If we're in a record, we want to hide the target, so we 11861 // return true (without a diagnostic) to tell the caller not to 11862 // build a shadow decl. 11863 if (CurContext->isRecord()) 11864 return true; 11865 11866 // If we're not in a record, this is an error. 11867 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11868 break; 11869 } 11870 11871 Diag(Target->getLocation(), diag::note_using_decl_target); 11872 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 11873 BUD->setInvalidDecl(); 11874 return true; 11875 } 11876 11877 // Target is not a function. 11878 11879 if (isa<TagDecl>(Target)) { 11880 // No conflict between a tag and a non-tag. 11881 if (!Tag) return false; 11882 11883 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11884 Diag(Target->getLocation(), diag::note_using_decl_target); 11885 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 11886 BUD->setInvalidDecl(); 11887 return true; 11888 } 11889 11890 // No conflict between a tag and a non-tag. 11891 if (!NonTag) return false; 11892 11893 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11894 Diag(Target->getLocation(), diag::note_using_decl_target); 11895 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 11896 BUD->setInvalidDecl(); 11897 return true; 11898 } 11899 11900 /// Determine whether a direct base class is a virtual base class. 11901 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 11902 if (!Derived->getNumVBases()) 11903 return false; 11904 for (auto &B : Derived->bases()) 11905 if (B.getType()->getAsCXXRecordDecl() == Base) 11906 return B.isVirtual(); 11907 llvm_unreachable("not a direct base class"); 11908 } 11909 11910 /// Builds a shadow declaration corresponding to a 'using' declaration. 11911 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, 11912 NamedDecl *Orig, 11913 UsingShadowDecl *PrevDecl) { 11914 // If we resolved to another shadow declaration, just coalesce them. 11915 NamedDecl *Target = Orig; 11916 if (isa<UsingShadowDecl>(Target)) { 11917 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11918 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 11919 } 11920 11921 NamedDecl *NonTemplateTarget = Target; 11922 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 11923 NonTemplateTarget = TargetTD->getTemplatedDecl(); 11924 11925 UsingShadowDecl *Shadow; 11926 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 11927 UsingDecl *Using = cast<UsingDecl>(BUD); 11928 bool IsVirtualBase = 11929 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 11930 Using->getQualifier()->getAsRecordDecl()); 11931 Shadow = ConstructorUsingShadowDecl::Create( 11932 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase); 11933 } else { 11934 Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(), 11935 Target->getDeclName(), BUD, Target); 11936 } 11937 BUD->addShadowDecl(Shadow); 11938 11939 Shadow->setAccess(BUD->getAccess()); 11940 if (Orig->isInvalidDecl() || BUD->isInvalidDecl()) 11941 Shadow->setInvalidDecl(); 11942 11943 Shadow->setPreviousDecl(PrevDecl); 11944 11945 if (S) 11946 PushOnScopeChains(Shadow, S); 11947 else 11948 CurContext->addDecl(Shadow); 11949 11950 11951 return Shadow; 11952 } 11953 11954 /// Hides a using shadow declaration. This is required by the current 11955 /// using-decl implementation when a resolvable using declaration in a 11956 /// class is followed by a declaration which would hide or override 11957 /// one or more of the using decl's targets; for example: 11958 /// 11959 /// struct Base { void foo(int); }; 11960 /// struct Derived : Base { 11961 /// using Base::foo; 11962 /// void foo(int); 11963 /// }; 11964 /// 11965 /// The governing language is C++03 [namespace.udecl]p12: 11966 /// 11967 /// When a using-declaration brings names from a base class into a 11968 /// derived class scope, member functions in the derived class 11969 /// override and/or hide member functions with the same name and 11970 /// parameter types in a base class (rather than conflicting). 11971 /// 11972 /// There are two ways to implement this: 11973 /// (1) optimistically create shadow decls when they're not hidden 11974 /// by existing declarations, or 11975 /// (2) don't create any shadow decls (or at least don't make them 11976 /// visible) until we've fully parsed/instantiated the class. 11977 /// The problem with (1) is that we might have to retroactively remove 11978 /// a shadow decl, which requires several O(n) operations because the 11979 /// decl structures are (very reasonably) not designed for removal. 11980 /// (2) avoids this but is very fiddly and phase-dependent. 11981 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 11982 if (Shadow->getDeclName().getNameKind() == 11983 DeclarationName::CXXConversionFunctionName) 11984 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 11985 11986 // Remove it from the DeclContext... 11987 Shadow->getDeclContext()->removeDecl(Shadow); 11988 11989 // ...and the scope, if applicable... 11990 if (S) { 11991 S->RemoveDecl(Shadow); 11992 IdResolver.RemoveDecl(Shadow); 11993 } 11994 11995 // ...and the using decl. 11996 Shadow->getIntroducer()->removeShadowDecl(Shadow); 11997 11998 // TODO: complain somehow if Shadow was used. It shouldn't 11999 // be possible for this to happen, because...? 12000 } 12001 12002 /// Find the base specifier for a base class with the given type. 12003 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 12004 QualType DesiredBase, 12005 bool &AnyDependentBases) { 12006 // Check whether the named type is a direct base class. 12007 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 12008 .getUnqualifiedType(); 12009 for (auto &Base : Derived->bases()) { 12010 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 12011 if (CanonicalDesiredBase == BaseType) 12012 return &Base; 12013 if (BaseType->isDependentType()) 12014 AnyDependentBases = true; 12015 } 12016 return nullptr; 12017 } 12018 12019 namespace { 12020 class UsingValidatorCCC final : public CorrectionCandidateCallback { 12021 public: 12022 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 12023 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 12024 : HasTypenameKeyword(HasTypenameKeyword), 12025 IsInstantiation(IsInstantiation), OldNNS(NNS), 12026 RequireMemberOf(RequireMemberOf) {} 12027 12028 bool ValidateCandidate(const TypoCorrection &Candidate) override { 12029 NamedDecl *ND = Candidate.getCorrectionDecl(); 12030 12031 // Keywords are not valid here. 12032 if (!ND || isa<NamespaceDecl>(ND)) 12033 return false; 12034 12035 // Completely unqualified names are invalid for a 'using' declaration. 12036 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 12037 return false; 12038 12039 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 12040 // reject. 12041 12042 if (RequireMemberOf) { 12043 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 12044 if (FoundRecord && FoundRecord->isInjectedClassName()) { 12045 // No-one ever wants a using-declaration to name an injected-class-name 12046 // of a base class, unless they're declaring an inheriting constructor. 12047 ASTContext &Ctx = ND->getASTContext(); 12048 if (!Ctx.getLangOpts().CPlusPlus11) 12049 return false; 12050 QualType FoundType = Ctx.getRecordType(FoundRecord); 12051 12052 // Check that the injected-class-name is named as a member of its own 12053 // type; we don't want to suggest 'using Derived::Base;', since that 12054 // means something else. 12055 NestedNameSpecifier *Specifier = 12056 Candidate.WillReplaceSpecifier() 12057 ? Candidate.getCorrectionSpecifier() 12058 : OldNNS; 12059 if (!Specifier->getAsType() || 12060 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 12061 return false; 12062 12063 // Check that this inheriting constructor declaration actually names a 12064 // direct base class of the current class. 12065 bool AnyDependentBases = false; 12066 if (!findDirectBaseWithType(RequireMemberOf, 12067 Ctx.getRecordType(FoundRecord), 12068 AnyDependentBases) && 12069 !AnyDependentBases) 12070 return false; 12071 } else { 12072 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 12073 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 12074 return false; 12075 12076 // FIXME: Check that the base class member is accessible? 12077 } 12078 } else { 12079 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 12080 if (FoundRecord && FoundRecord->isInjectedClassName()) 12081 return false; 12082 } 12083 12084 if (isa<TypeDecl>(ND)) 12085 return HasTypenameKeyword || !IsInstantiation; 12086 12087 return !HasTypenameKeyword; 12088 } 12089 12090 std::unique_ptr<CorrectionCandidateCallback> clone() override { 12091 return std::make_unique<UsingValidatorCCC>(*this); 12092 } 12093 12094 private: 12095 bool HasTypenameKeyword; 12096 bool IsInstantiation; 12097 NestedNameSpecifier *OldNNS; 12098 CXXRecordDecl *RequireMemberOf; 12099 }; 12100 } // end anonymous namespace 12101 12102 /// Remove decls we can't actually see from a lookup being used to declare 12103 /// shadow using decls. 12104 /// 12105 /// \param S - The scope of the potential shadow decl 12106 /// \param Previous - The lookup of a potential shadow decl's name. 12107 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) { 12108 // It is really dumb that we have to do this. 12109 LookupResult::Filter F = Previous.makeFilter(); 12110 while (F.hasNext()) { 12111 NamedDecl *D = F.next(); 12112 if (!isDeclInScope(D, CurContext, S)) 12113 F.erase(); 12114 // If we found a local extern declaration that's not ordinarily visible, 12115 // and this declaration is being added to a non-block scope, ignore it. 12116 // We're only checking for scope conflicts here, not also for violations 12117 // of the linkage rules. 12118 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 12119 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 12120 F.erase(); 12121 } 12122 F.done(); 12123 } 12124 12125 /// Builds a using declaration. 12126 /// 12127 /// \param IsInstantiation - Whether this call arises from an 12128 /// instantiation of an unresolved using declaration. We treat 12129 /// the lookup differently for these declarations. 12130 NamedDecl *Sema::BuildUsingDeclaration( 12131 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 12132 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 12133 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 12134 const ParsedAttributesView &AttrList, bool IsInstantiation, 12135 bool IsUsingIfExists) { 12136 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 12137 SourceLocation IdentLoc = NameInfo.getLoc(); 12138 assert(IdentLoc.isValid() && "Invalid TargetName location."); 12139 12140 // FIXME: We ignore attributes for now. 12141 12142 // For an inheriting constructor declaration, the name of the using 12143 // declaration is the name of a constructor in this class, not in the 12144 // base class. 12145 DeclarationNameInfo UsingName = NameInfo; 12146 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 12147 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 12148 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12149 Context.getCanonicalType(Context.getRecordType(RD)))); 12150 12151 // Do the redeclaration lookup in the current scope. 12152 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 12153 ForVisibleRedeclaration); 12154 Previous.setHideTags(false); 12155 if (S) { 12156 LookupName(Previous, S); 12157 12158 FilterUsingLookup(S, Previous); 12159 } else { 12160 assert(IsInstantiation && "no scope in non-instantiation"); 12161 if (CurContext->isRecord()) 12162 LookupQualifiedName(Previous, CurContext); 12163 else { 12164 // No redeclaration check is needed here; in non-member contexts we 12165 // diagnosed all possible conflicts with other using-declarations when 12166 // building the template: 12167 // 12168 // For a dependent non-type using declaration, the only valid case is 12169 // if we instantiate to a single enumerator. We check for conflicts 12170 // between shadow declarations we introduce, and we check in the template 12171 // definition for conflicts between a non-type using declaration and any 12172 // other declaration, which together covers all cases. 12173 // 12174 // A dependent typename using declaration will never successfully 12175 // instantiate, since it will always name a class member, so we reject 12176 // that in the template definition. 12177 } 12178 } 12179 12180 // Check for invalid redeclarations. 12181 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 12182 SS, IdentLoc, Previous)) 12183 return nullptr; 12184 12185 // 'using_if_exists' doesn't make sense on an inherited constructor. 12186 if (IsUsingIfExists && UsingName.getName().getNameKind() == 12187 DeclarationName::CXXConstructorName) { 12188 Diag(UsingLoc, diag::err_using_if_exists_on_ctor); 12189 return nullptr; 12190 } 12191 12192 DeclContext *LookupContext = computeDeclContext(SS); 12193 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12194 if (!LookupContext || EllipsisLoc.isValid()) { 12195 NamedDecl *D; 12196 // Dependent scope, or an unexpanded pack 12197 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, 12198 SS, NameInfo, IdentLoc)) 12199 return nullptr; 12200 12201 if (HasTypenameKeyword) { 12202 // FIXME: not all declaration name kinds are legal here 12203 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 12204 UsingLoc, TypenameLoc, 12205 QualifierLoc, 12206 IdentLoc, NameInfo.getName(), 12207 EllipsisLoc); 12208 } else { 12209 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 12210 QualifierLoc, NameInfo, EllipsisLoc); 12211 } 12212 D->setAccess(AS); 12213 CurContext->addDecl(D); 12214 ProcessDeclAttributeList(S, D, AttrList); 12215 return D; 12216 } 12217 12218 auto Build = [&](bool Invalid) { 12219 UsingDecl *UD = 12220 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 12221 UsingName, HasTypenameKeyword); 12222 UD->setAccess(AS); 12223 CurContext->addDecl(UD); 12224 ProcessDeclAttributeList(S, UD, AttrList); 12225 UD->setInvalidDecl(Invalid); 12226 return UD; 12227 }; 12228 auto BuildInvalid = [&]{ return Build(true); }; 12229 auto BuildValid = [&]{ return Build(false); }; 12230 12231 if (RequireCompleteDeclContext(SS, LookupContext)) 12232 return BuildInvalid(); 12233 12234 // Look up the target name. 12235 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12236 12237 // Unlike most lookups, we don't always want to hide tag 12238 // declarations: tag names are visible through the using declaration 12239 // even if hidden by ordinary names, *except* in a dependent context 12240 // where it's important for the sanity of two-phase lookup. 12241 if (!IsInstantiation) 12242 R.setHideTags(false); 12243 12244 // For the purposes of this lookup, we have a base object type 12245 // equal to that of the current context. 12246 if (CurContext->isRecord()) { 12247 R.setBaseObjectType( 12248 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 12249 } 12250 12251 LookupQualifiedName(R, LookupContext); 12252 12253 // Validate the context, now we have a lookup 12254 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 12255 IdentLoc, &R)) 12256 return nullptr; 12257 12258 if (R.empty() && IsUsingIfExists) 12259 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc, 12260 UsingName.getName()), 12261 AS_public); 12262 12263 // Try to correct typos if possible. If constructor name lookup finds no 12264 // results, that means the named class has no explicit constructors, and we 12265 // suppressed declaring implicit ones (probably because it's dependent or 12266 // invalid). 12267 if (R.empty() && 12268 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 12269 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of 12270 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where 12271 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later. 12272 auto *II = NameInfo.getName().getAsIdentifierInfo(); 12273 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 12274 CurContext->isStdNamespace() && 12275 isa<TranslationUnitDecl>(LookupContext) && 12276 getSourceManager().isInSystemHeader(UsingLoc)) 12277 return nullptr; 12278 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 12279 dyn_cast<CXXRecordDecl>(CurContext)); 12280 if (TypoCorrection Corrected = 12281 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 12282 CTK_ErrorRecovery)) { 12283 // We reject candidates where DroppedSpecifier == true, hence the 12284 // literal '0' below. 12285 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 12286 << NameInfo.getName() << LookupContext << 0 12287 << SS.getRange()); 12288 12289 // If we picked a correction with no attached Decl we can't do anything 12290 // useful with it, bail out. 12291 NamedDecl *ND = Corrected.getCorrectionDecl(); 12292 if (!ND) 12293 return BuildInvalid(); 12294 12295 // If we corrected to an inheriting constructor, handle it as one. 12296 auto *RD = dyn_cast<CXXRecordDecl>(ND); 12297 if (RD && RD->isInjectedClassName()) { 12298 // The parent of the injected class name is the class itself. 12299 RD = cast<CXXRecordDecl>(RD->getParent()); 12300 12301 // Fix up the information we'll use to build the using declaration. 12302 if (Corrected.WillReplaceSpecifier()) { 12303 NestedNameSpecifierLocBuilder Builder; 12304 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 12305 QualifierLoc.getSourceRange()); 12306 QualifierLoc = Builder.getWithLocInContext(Context); 12307 } 12308 12309 // In this case, the name we introduce is the name of a derived class 12310 // constructor. 12311 auto *CurClass = cast<CXXRecordDecl>(CurContext); 12312 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12313 Context.getCanonicalType(Context.getRecordType(CurClass)))); 12314 UsingName.setNamedTypeInfo(nullptr); 12315 for (auto *Ctor : LookupConstructors(RD)) 12316 R.addDecl(Ctor); 12317 R.resolveKind(); 12318 } else { 12319 // FIXME: Pick up all the declarations if we found an overloaded 12320 // function. 12321 UsingName.setName(ND->getDeclName()); 12322 R.addDecl(ND); 12323 } 12324 } else { 12325 Diag(IdentLoc, diag::err_no_member) 12326 << NameInfo.getName() << LookupContext << SS.getRange(); 12327 return BuildInvalid(); 12328 } 12329 } 12330 12331 if (R.isAmbiguous()) 12332 return BuildInvalid(); 12333 12334 if (HasTypenameKeyword) { 12335 // If we asked for a typename and got a non-type decl, error out. 12336 if (!R.getAsSingle<TypeDecl>() && 12337 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) { 12338 Diag(IdentLoc, diag::err_using_typename_non_type); 12339 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12340 Diag((*I)->getUnderlyingDecl()->getLocation(), 12341 diag::note_using_decl_target); 12342 return BuildInvalid(); 12343 } 12344 } else { 12345 // If we asked for a non-typename and we got a type, error out, 12346 // but only if this is an instantiation of an unresolved using 12347 // decl. Otherwise just silently find the type name. 12348 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 12349 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 12350 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 12351 return BuildInvalid(); 12352 } 12353 } 12354 12355 // C++14 [namespace.udecl]p6: 12356 // A using-declaration shall not name a namespace. 12357 if (R.getAsSingle<NamespaceDecl>()) { 12358 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 12359 << SS.getRange(); 12360 return BuildInvalid(); 12361 } 12362 12363 UsingDecl *UD = BuildValid(); 12364 12365 // Some additional rules apply to inheriting constructors. 12366 if (UsingName.getName().getNameKind() == 12367 DeclarationName::CXXConstructorName) { 12368 // Suppress access diagnostics; the access check is instead performed at the 12369 // point of use for an inheriting constructor. 12370 R.suppressDiagnostics(); 12371 if (CheckInheritingConstructorUsingDecl(UD)) 12372 return UD; 12373 } 12374 12375 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 12376 UsingShadowDecl *PrevDecl = nullptr; 12377 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 12378 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 12379 } 12380 12381 return UD; 12382 } 12383 12384 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 12385 SourceLocation UsingLoc, 12386 SourceLocation EnumLoc, 12387 SourceLocation NameLoc, 12388 EnumDecl *ED) { 12389 bool Invalid = false; 12390 12391 if (CurContext->getRedeclContext()->isRecord()) { 12392 /// In class scope, check if this is a duplicate, for better a diagnostic. 12393 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc); 12394 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName, 12395 ForVisibleRedeclaration); 12396 12397 LookupName(Previous, S); 12398 12399 for (NamedDecl *D : Previous) 12400 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D)) 12401 if (UED->getEnumDecl() == ED) { 12402 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration) 12403 << SourceRange(EnumLoc, NameLoc); 12404 Diag(D->getLocation(), diag::note_using_enum_decl) << 1; 12405 Invalid = true; 12406 break; 12407 } 12408 } 12409 12410 if (RequireCompleteEnumDecl(ED, NameLoc)) 12411 Invalid = true; 12412 12413 UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc, 12414 EnumLoc, NameLoc, ED); 12415 UD->setAccess(AS); 12416 CurContext->addDecl(UD); 12417 12418 if (Invalid) { 12419 UD->setInvalidDecl(); 12420 return UD; 12421 } 12422 12423 // Create the shadow decls for each enumerator 12424 for (EnumConstantDecl *EC : ED->enumerators()) { 12425 UsingShadowDecl *PrevDecl = nullptr; 12426 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation()); 12427 LookupResult Previous(*this, DNI, LookupOrdinaryName, 12428 ForVisibleRedeclaration); 12429 LookupName(Previous, S); 12430 FilterUsingLookup(S, Previous); 12431 12432 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl)) 12433 BuildUsingShadowDecl(S, UD, EC, PrevDecl); 12434 } 12435 12436 return UD; 12437 } 12438 12439 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 12440 ArrayRef<NamedDecl *> Expansions) { 12441 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 12442 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 12443 isa<UsingPackDecl>(InstantiatedFrom)); 12444 12445 auto *UPD = 12446 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 12447 UPD->setAccess(InstantiatedFrom->getAccess()); 12448 CurContext->addDecl(UPD); 12449 return UPD; 12450 } 12451 12452 /// Additional checks for a using declaration referring to a constructor name. 12453 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 12454 assert(!UD->hasTypename() && "expecting a constructor name"); 12455 12456 const Type *SourceType = UD->getQualifier()->getAsType(); 12457 assert(SourceType && 12458 "Using decl naming constructor doesn't have type in scope spec."); 12459 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 12460 12461 // Check whether the named type is a direct base class. 12462 bool AnyDependentBases = false; 12463 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 12464 AnyDependentBases); 12465 if (!Base && !AnyDependentBases) { 12466 Diag(UD->getUsingLoc(), 12467 diag::err_using_decl_constructor_not_in_direct_base) 12468 << UD->getNameInfo().getSourceRange() 12469 << QualType(SourceType, 0) << TargetClass; 12470 UD->setInvalidDecl(); 12471 return true; 12472 } 12473 12474 if (Base) 12475 Base->setInheritConstructors(); 12476 12477 return false; 12478 } 12479 12480 /// Checks that the given using declaration is not an invalid 12481 /// redeclaration. Note that this is checking only for the using decl 12482 /// itself, not for any ill-formedness among the UsingShadowDecls. 12483 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 12484 bool HasTypenameKeyword, 12485 const CXXScopeSpec &SS, 12486 SourceLocation NameLoc, 12487 const LookupResult &Prev) { 12488 NestedNameSpecifier *Qual = SS.getScopeRep(); 12489 12490 // C++03 [namespace.udecl]p8: 12491 // C++0x [namespace.udecl]p10: 12492 // A using-declaration is a declaration and can therefore be used 12493 // repeatedly where (and only where) multiple declarations are 12494 // allowed. 12495 // 12496 // That's in non-member contexts. 12497 if (!CurContext->getRedeclContext()->isRecord()) { 12498 // A dependent qualifier outside a class can only ever resolve to an 12499 // enumeration type. Therefore it conflicts with any other non-type 12500 // declaration in the same scope. 12501 // FIXME: How should we check for dependent type-type conflicts at block 12502 // scope? 12503 if (Qual->isDependent() && !HasTypenameKeyword) { 12504 for (auto *D : Prev) { 12505 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 12506 bool OldCouldBeEnumerator = 12507 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 12508 Diag(NameLoc, 12509 OldCouldBeEnumerator ? diag::err_redefinition 12510 : diag::err_redefinition_different_kind) 12511 << Prev.getLookupName(); 12512 Diag(D->getLocation(), diag::note_previous_definition); 12513 return true; 12514 } 12515 } 12516 } 12517 return false; 12518 } 12519 12520 const NestedNameSpecifier *CNNS = 12521 Context.getCanonicalNestedNameSpecifier(Qual); 12522 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 12523 NamedDecl *D = *I; 12524 12525 bool DTypename; 12526 NestedNameSpecifier *DQual; 12527 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 12528 DTypename = UD->hasTypename(); 12529 DQual = UD->getQualifier(); 12530 } else if (UnresolvedUsingValueDecl *UD 12531 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 12532 DTypename = false; 12533 DQual = UD->getQualifier(); 12534 } else if (UnresolvedUsingTypenameDecl *UD 12535 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 12536 DTypename = true; 12537 DQual = UD->getQualifier(); 12538 } else continue; 12539 12540 // using decls differ if one says 'typename' and the other doesn't. 12541 // FIXME: non-dependent using decls? 12542 if (HasTypenameKeyword != DTypename) continue; 12543 12544 // using decls differ if they name different scopes (but note that 12545 // template instantiation can cause this check to trigger when it 12546 // didn't before instantiation). 12547 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual)) 12548 continue; 12549 12550 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 12551 Diag(D->getLocation(), diag::note_using_decl) << 1; 12552 return true; 12553 } 12554 12555 return false; 12556 } 12557 12558 /// Checks that the given nested-name qualifier used in a using decl 12559 /// in the current context is appropriately related to the current 12560 /// scope. If an error is found, diagnoses it and returns true. 12561 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the 12562 /// result of that lookup. UD is likewise nullptr, except when we have an 12563 /// already-populated UsingDecl whose shadow decls contain the same information 12564 /// (i.e. we're instantiating a UsingDecl with non-dependent scope). 12565 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, 12566 const CXXScopeSpec &SS, 12567 const DeclarationNameInfo &NameInfo, 12568 SourceLocation NameLoc, 12569 const LookupResult *R, const UsingDecl *UD) { 12570 DeclContext *NamedContext = computeDeclContext(SS); 12571 assert(bool(NamedContext) == (R || UD) && !(R && UD) && 12572 "resolvable context must have exactly one set of decls"); 12573 12574 // C++ 20 permits using an enumerator that does not have a class-hierarchy 12575 // relationship. 12576 bool Cxx20Enumerator = false; 12577 if (NamedContext) { 12578 EnumConstantDecl *EC = nullptr; 12579 if (R) 12580 EC = R->getAsSingle<EnumConstantDecl>(); 12581 else if (UD && UD->shadow_size() == 1) 12582 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl()); 12583 if (EC) 12584 Cxx20Enumerator = getLangOpts().CPlusPlus20; 12585 12586 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) { 12587 // C++14 [namespace.udecl]p7: 12588 // A using-declaration shall not name a scoped enumerator. 12589 // C++20 p1099 permits enumerators. 12590 if (EC && R && ED->isScoped()) 12591 Diag(SS.getBeginLoc(), 12592 getLangOpts().CPlusPlus20 12593 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator 12594 : diag::ext_using_decl_scoped_enumerator) 12595 << SS.getRange(); 12596 12597 // We want to consider the scope of the enumerator 12598 NamedContext = ED->getDeclContext(); 12599 } 12600 } 12601 12602 if (!CurContext->isRecord()) { 12603 // C++03 [namespace.udecl]p3: 12604 // C++0x [namespace.udecl]p8: 12605 // A using-declaration for a class member shall be a member-declaration. 12606 // C++20 [namespace.udecl]p7 12607 // ... other than an enumerator ... 12608 12609 // If we weren't able to compute a valid scope, it might validly be a 12610 // dependent class or enumeration scope. If we have a 'typename' keyword, 12611 // the scope must resolve to a class type. 12612 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord() 12613 : !HasTypename) 12614 return false; // OK 12615 12616 Diag(NameLoc, 12617 Cxx20Enumerator 12618 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator 12619 : diag::err_using_decl_can_not_refer_to_class_member) 12620 << SS.getRange(); 12621 12622 if (Cxx20Enumerator) 12623 return false; // OK 12624 12625 auto *RD = NamedContext 12626 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 12627 : nullptr; 12628 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) { 12629 // See if there's a helpful fixit 12630 12631 if (!R) { 12632 // We will have already diagnosed the problem on the template 12633 // definition, Maybe we should do so again? 12634 } else if (R->getAsSingle<TypeDecl>()) { 12635 if (getLangOpts().CPlusPlus11) { 12636 // Convert 'using X::Y;' to 'using Y = X::Y;'. 12637 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 12638 << 0 // alias declaration 12639 << FixItHint::CreateInsertion(SS.getBeginLoc(), 12640 NameInfo.getName().getAsString() + 12641 " = "); 12642 } else { 12643 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 12644 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 12645 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 12646 << 1 // typedef declaration 12647 << FixItHint::CreateReplacement(UsingLoc, "typedef") 12648 << FixItHint::CreateInsertion( 12649 InsertLoc, " " + NameInfo.getName().getAsString()); 12650 } 12651 } else if (R->getAsSingle<VarDecl>()) { 12652 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12653 // repeating the type of the static data member here. 12654 FixItHint FixIt; 12655 if (getLangOpts().CPlusPlus11) { 12656 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12657 FixIt = FixItHint::CreateReplacement( 12658 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 12659 } 12660 12661 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12662 << 2 // reference declaration 12663 << FixIt; 12664 } else if (R->getAsSingle<EnumConstantDecl>()) { 12665 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12666 // repeating the type of the enumeration here, and we can't do so if 12667 // the type is anonymous. 12668 FixItHint FixIt; 12669 if (getLangOpts().CPlusPlus11) { 12670 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12671 FixIt = FixItHint::CreateReplacement( 12672 UsingLoc, 12673 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 12674 } 12675 12676 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12677 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 12678 << FixIt; 12679 } 12680 } 12681 12682 return true; // Fail 12683 } 12684 12685 // If the named context is dependent, we can't decide much. 12686 if (!NamedContext) { 12687 // FIXME: in C++0x, we can diagnose if we can prove that the 12688 // nested-name-specifier does not refer to a base class, which is 12689 // still possible in some cases. 12690 12691 // Otherwise we have to conservatively report that things might be 12692 // okay. 12693 return false; 12694 } 12695 12696 // The current scope is a record. 12697 if (!NamedContext->isRecord()) { 12698 // Ideally this would point at the last name in the specifier, 12699 // but we don't have that level of source info. 12700 Diag(SS.getBeginLoc(), 12701 Cxx20Enumerator 12702 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator 12703 : diag::err_using_decl_nested_name_specifier_is_not_class) 12704 << SS.getScopeRep() << SS.getRange(); 12705 12706 if (Cxx20Enumerator) 12707 return false; // OK 12708 12709 return true; 12710 } 12711 12712 if (!NamedContext->isDependentContext() && 12713 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 12714 return true; 12715 12716 if (getLangOpts().CPlusPlus11) { 12717 // C++11 [namespace.udecl]p3: 12718 // In a using-declaration used as a member-declaration, the 12719 // nested-name-specifier shall name a base class of the class 12720 // being defined. 12721 12722 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 12723 cast<CXXRecordDecl>(NamedContext))) { 12724 12725 if (Cxx20Enumerator) { 12726 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator) 12727 << SS.getRange(); 12728 return false; 12729 } 12730 12731 if (CurContext == NamedContext) { 12732 Diag(SS.getBeginLoc(), 12733 diag::err_using_decl_nested_name_specifier_is_current_class) 12734 << SS.getRange(); 12735 return !getLangOpts().CPlusPlus20; 12736 } 12737 12738 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 12739 Diag(SS.getBeginLoc(), 12740 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12741 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext) 12742 << SS.getRange(); 12743 } 12744 return true; 12745 } 12746 12747 return false; 12748 } 12749 12750 // C++03 [namespace.udecl]p4: 12751 // A using-declaration used as a member-declaration shall refer 12752 // to a member of a base class of the class being defined [etc.]. 12753 12754 // Salient point: SS doesn't have to name a base class as long as 12755 // lookup only finds members from base classes. Therefore we can 12756 // diagnose here only if we can prove that that can't happen, 12757 // i.e. if the class hierarchies provably don't intersect. 12758 12759 // TODO: it would be nice if "definitely valid" results were cached 12760 // in the UsingDecl and UsingShadowDecl so that these checks didn't 12761 // need to be repeated. 12762 12763 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 12764 auto Collect = [&Bases](const CXXRecordDecl *Base) { 12765 Bases.insert(Base); 12766 return true; 12767 }; 12768 12769 // Collect all bases. Return false if we find a dependent base. 12770 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 12771 return false; 12772 12773 // Returns true if the base is dependent or is one of the accumulated base 12774 // classes. 12775 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 12776 return !Bases.count(Base); 12777 }; 12778 12779 // Return false if the class has a dependent base or if it or one 12780 // of its bases is present in the base set of the current context. 12781 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 12782 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 12783 return false; 12784 12785 Diag(SS.getRange().getBegin(), 12786 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12787 << SS.getScopeRep() 12788 << cast<CXXRecordDecl>(CurContext) 12789 << SS.getRange(); 12790 12791 return true; 12792 } 12793 12794 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 12795 MultiTemplateParamsArg TemplateParamLists, 12796 SourceLocation UsingLoc, UnqualifiedId &Name, 12797 const ParsedAttributesView &AttrList, 12798 TypeResult Type, Decl *DeclFromDeclSpec) { 12799 // Skip up to the relevant declaration scope. 12800 while (S->isTemplateParamScope()) 12801 S = S->getParent(); 12802 assert((S->getFlags() & Scope::DeclScope) && 12803 "got alias-declaration outside of declaration scope"); 12804 12805 if (Type.isInvalid()) 12806 return nullptr; 12807 12808 bool Invalid = false; 12809 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 12810 TypeSourceInfo *TInfo = nullptr; 12811 GetTypeFromParser(Type.get(), &TInfo); 12812 12813 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 12814 return nullptr; 12815 12816 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 12817 UPPC_DeclarationType)) { 12818 Invalid = true; 12819 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12820 TInfo->getTypeLoc().getBeginLoc()); 12821 } 12822 12823 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12824 TemplateParamLists.size() 12825 ? forRedeclarationInCurContext() 12826 : ForVisibleRedeclaration); 12827 LookupName(Previous, S); 12828 12829 // Warn about shadowing the name of a template parameter. 12830 if (Previous.isSingleResult() && 12831 Previous.getFoundDecl()->isTemplateParameter()) { 12832 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 12833 Previous.clear(); 12834 } 12835 12836 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 12837 "name in alias declaration must be an identifier"); 12838 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 12839 Name.StartLocation, 12840 Name.Identifier, TInfo); 12841 12842 NewTD->setAccess(AS); 12843 12844 if (Invalid) 12845 NewTD->setInvalidDecl(); 12846 12847 ProcessDeclAttributeList(S, NewTD, AttrList); 12848 AddPragmaAttributes(S, NewTD); 12849 12850 CheckTypedefForVariablyModifiedType(S, NewTD); 12851 Invalid |= NewTD->isInvalidDecl(); 12852 12853 bool Redeclaration = false; 12854 12855 NamedDecl *NewND; 12856 if (TemplateParamLists.size()) { 12857 TypeAliasTemplateDecl *OldDecl = nullptr; 12858 TemplateParameterList *OldTemplateParams = nullptr; 12859 12860 if (TemplateParamLists.size() != 1) { 12861 Diag(UsingLoc, diag::err_alias_template_extra_headers) 12862 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 12863 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 12864 } 12865 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 12866 12867 // Check that we can declare a template here. 12868 if (CheckTemplateDeclScope(S, TemplateParams)) 12869 return nullptr; 12870 12871 // Only consider previous declarations in the same scope. 12872 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 12873 /*ExplicitInstantiationOrSpecialization*/false); 12874 if (!Previous.empty()) { 12875 Redeclaration = true; 12876 12877 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 12878 if (!OldDecl && !Invalid) { 12879 Diag(UsingLoc, diag::err_redefinition_different_kind) 12880 << Name.Identifier; 12881 12882 NamedDecl *OldD = Previous.getRepresentativeDecl(); 12883 if (OldD->getLocation().isValid()) 12884 Diag(OldD->getLocation(), diag::note_previous_definition); 12885 12886 Invalid = true; 12887 } 12888 12889 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 12890 if (TemplateParameterListsAreEqual(TemplateParams, 12891 OldDecl->getTemplateParameters(), 12892 /*Complain=*/true, 12893 TPL_TemplateMatch)) 12894 OldTemplateParams = 12895 OldDecl->getMostRecentDecl()->getTemplateParameters(); 12896 else 12897 Invalid = true; 12898 12899 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 12900 if (!Invalid && 12901 !Context.hasSameType(OldTD->getUnderlyingType(), 12902 NewTD->getUnderlyingType())) { 12903 // FIXME: The C++0x standard does not clearly say this is ill-formed, 12904 // but we can't reasonably accept it. 12905 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 12906 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 12907 if (OldTD->getLocation().isValid()) 12908 Diag(OldTD->getLocation(), diag::note_previous_definition); 12909 Invalid = true; 12910 } 12911 } 12912 } 12913 12914 // Merge any previous default template arguments into our parameters, 12915 // and check the parameter list. 12916 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 12917 TPC_TypeAliasTemplate)) 12918 return nullptr; 12919 12920 TypeAliasTemplateDecl *NewDecl = 12921 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 12922 Name.Identifier, TemplateParams, 12923 NewTD); 12924 NewTD->setDescribedAliasTemplate(NewDecl); 12925 12926 NewDecl->setAccess(AS); 12927 12928 if (Invalid) 12929 NewDecl->setInvalidDecl(); 12930 else if (OldDecl) { 12931 NewDecl->setPreviousDecl(OldDecl); 12932 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 12933 } 12934 12935 NewND = NewDecl; 12936 } else { 12937 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 12938 setTagNameForLinkagePurposes(TD, NewTD); 12939 handleTagNumbering(TD, S); 12940 } 12941 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 12942 NewND = NewTD; 12943 } 12944 12945 PushOnScopeChains(NewND, S); 12946 ActOnDocumentableDecl(NewND); 12947 return NewND; 12948 } 12949 12950 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 12951 SourceLocation AliasLoc, 12952 IdentifierInfo *Alias, CXXScopeSpec &SS, 12953 SourceLocation IdentLoc, 12954 IdentifierInfo *Ident) { 12955 12956 // Lookup the namespace name. 12957 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 12958 LookupParsedName(R, S, &SS); 12959 12960 if (R.isAmbiguous()) 12961 return nullptr; 12962 12963 if (R.empty()) { 12964 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 12965 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 12966 return nullptr; 12967 } 12968 } 12969 assert(!R.isAmbiguous() && !R.empty()); 12970 NamedDecl *ND = R.getRepresentativeDecl(); 12971 12972 // Check if we have a previous declaration with the same name. 12973 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 12974 ForVisibleRedeclaration); 12975 LookupName(PrevR, S); 12976 12977 // Check we're not shadowing a template parameter. 12978 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 12979 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 12980 PrevR.clear(); 12981 } 12982 12983 // Filter out any other lookup result from an enclosing scope. 12984 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 12985 /*AllowInlineNamespace*/false); 12986 12987 // Find the previous declaration and check that we can redeclare it. 12988 NamespaceAliasDecl *Prev = nullptr; 12989 if (PrevR.isSingleResult()) { 12990 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 12991 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 12992 // We already have an alias with the same name that points to the same 12993 // namespace; check that it matches. 12994 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 12995 Prev = AD; 12996 } else if (isVisible(PrevDecl)) { 12997 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 12998 << Alias; 12999 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 13000 << AD->getNamespace(); 13001 return nullptr; 13002 } 13003 } else if (isVisible(PrevDecl)) { 13004 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 13005 ? diag::err_redefinition 13006 : diag::err_redefinition_different_kind; 13007 Diag(AliasLoc, DiagID) << Alias; 13008 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13009 return nullptr; 13010 } 13011 } 13012 13013 // The use of a nested name specifier may trigger deprecation warnings. 13014 DiagnoseUseOfDecl(ND, IdentLoc); 13015 13016 NamespaceAliasDecl *AliasDecl = 13017 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 13018 Alias, SS.getWithLocInContext(Context), 13019 IdentLoc, ND); 13020 if (Prev) 13021 AliasDecl->setPreviousDecl(Prev); 13022 13023 PushOnScopeChains(AliasDecl, S); 13024 return AliasDecl; 13025 } 13026 13027 namespace { 13028 struct SpecialMemberExceptionSpecInfo 13029 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 13030 SourceLocation Loc; 13031 Sema::ImplicitExceptionSpecification ExceptSpec; 13032 13033 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 13034 Sema::CXXSpecialMember CSM, 13035 Sema::InheritedConstructorInfo *ICI, 13036 SourceLocation Loc) 13037 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 13038 13039 bool visitBase(CXXBaseSpecifier *Base); 13040 bool visitField(FieldDecl *FD); 13041 13042 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 13043 unsigned Quals); 13044 13045 void visitSubobjectCall(Subobject Subobj, 13046 Sema::SpecialMemberOverloadResult SMOR); 13047 }; 13048 } 13049 13050 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 13051 auto *RT = Base->getType()->getAs<RecordType>(); 13052 if (!RT) 13053 return false; 13054 13055 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 13056 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 13057 if (auto *BaseCtor = SMOR.getMethod()) { 13058 visitSubobjectCall(Base, BaseCtor); 13059 return false; 13060 } 13061 13062 visitClassSubobject(BaseClass, Base, 0); 13063 return false; 13064 } 13065 13066 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 13067 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 13068 Expr *E = FD->getInClassInitializer(); 13069 if (!E) 13070 // FIXME: It's a little wasteful to build and throw away a 13071 // CXXDefaultInitExpr here. 13072 // FIXME: We should have a single context note pointing at Loc, and 13073 // this location should be MD->getLocation() instead, since that's 13074 // the location where we actually use the default init expression. 13075 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 13076 if (E) 13077 ExceptSpec.CalledExpr(E); 13078 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 13079 ->getAs<RecordType>()) { 13080 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 13081 FD->getType().getCVRQualifiers()); 13082 } 13083 return false; 13084 } 13085 13086 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 13087 Subobject Subobj, 13088 unsigned Quals) { 13089 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 13090 bool IsMutable = Field && Field->isMutable(); 13091 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 13092 } 13093 13094 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 13095 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 13096 // Note, if lookup fails, it doesn't matter what exception specification we 13097 // choose because the special member will be deleted. 13098 if (CXXMethodDecl *MD = SMOR.getMethod()) 13099 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 13100 } 13101 13102 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 13103 llvm::APSInt Result; 13104 ExprResult Converted = CheckConvertedConstantExpression( 13105 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 13106 ExplicitSpec.setExpr(Converted.get()); 13107 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 13108 ExplicitSpec.setKind(Result.getBoolValue() 13109 ? ExplicitSpecKind::ResolvedTrue 13110 : ExplicitSpecKind::ResolvedFalse); 13111 return true; 13112 } 13113 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 13114 return false; 13115 } 13116 13117 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 13118 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 13119 if (!ExplicitExpr->isTypeDependent()) 13120 tryResolveExplicitSpecifier(ES); 13121 return ES; 13122 } 13123 13124 static Sema::ImplicitExceptionSpecification 13125 ComputeDefaultedSpecialMemberExceptionSpec( 13126 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 13127 Sema::InheritedConstructorInfo *ICI) { 13128 ComputingExceptionSpec CES(S, MD, Loc); 13129 13130 CXXRecordDecl *ClassDecl = MD->getParent(); 13131 13132 // C++ [except.spec]p14: 13133 // An implicitly declared special member function (Clause 12) shall have an 13134 // exception-specification. [...] 13135 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 13136 if (ClassDecl->isInvalidDecl()) 13137 return Info.ExceptSpec; 13138 13139 // FIXME: If this diagnostic fires, we're probably missing a check for 13140 // attempting to resolve an exception specification before it's known 13141 // at a higher level. 13142 if (S.RequireCompleteType(MD->getLocation(), 13143 S.Context.getRecordType(ClassDecl), 13144 diag::err_exception_spec_incomplete_type)) 13145 return Info.ExceptSpec; 13146 13147 // C++1z [except.spec]p7: 13148 // [Look for exceptions thrown by] a constructor selected [...] to 13149 // initialize a potentially constructed subobject, 13150 // C++1z [except.spec]p8: 13151 // The exception specification for an implicitly-declared destructor, or a 13152 // destructor without a noexcept-specifier, is potentially-throwing if and 13153 // only if any of the destructors for any of its potentially constructed 13154 // subojects is potentially throwing. 13155 // FIXME: We respect the first rule but ignore the "potentially constructed" 13156 // in the second rule to resolve a core issue (no number yet) that would have 13157 // us reject: 13158 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 13159 // struct B : A {}; 13160 // struct C : B { void f(); }; 13161 // ... due to giving B::~B() a non-throwing exception specification. 13162 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 13163 : Info.VisitAllBases); 13164 13165 return Info.ExceptSpec; 13166 } 13167 13168 namespace { 13169 /// RAII object to register a special member as being currently declared. 13170 struct DeclaringSpecialMember { 13171 Sema &S; 13172 Sema::SpecialMemberDecl D; 13173 Sema::ContextRAII SavedContext; 13174 bool WasAlreadyBeingDeclared; 13175 13176 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 13177 : S(S), D(RD, CSM), SavedContext(S, RD) { 13178 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 13179 if (WasAlreadyBeingDeclared) 13180 // This almost never happens, but if it does, ensure that our cache 13181 // doesn't contain a stale result. 13182 S.SpecialMemberCache.clear(); 13183 else { 13184 // Register a note to be produced if we encounter an error while 13185 // declaring the special member. 13186 Sema::CodeSynthesisContext Ctx; 13187 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 13188 // FIXME: We don't have a location to use here. Using the class's 13189 // location maintains the fiction that we declare all special members 13190 // with the class, but (1) it's not clear that lying about that helps our 13191 // users understand what's going on, and (2) there may be outer contexts 13192 // on the stack (some of which are relevant) and printing them exposes 13193 // our lies. 13194 Ctx.PointOfInstantiation = RD->getLocation(); 13195 Ctx.Entity = RD; 13196 Ctx.SpecialMember = CSM; 13197 S.pushCodeSynthesisContext(Ctx); 13198 } 13199 } 13200 ~DeclaringSpecialMember() { 13201 if (!WasAlreadyBeingDeclared) { 13202 S.SpecialMembersBeingDeclared.erase(D); 13203 S.popCodeSynthesisContext(); 13204 } 13205 } 13206 13207 /// Are we already trying to declare this special member? 13208 bool isAlreadyBeingDeclared() const { 13209 return WasAlreadyBeingDeclared; 13210 } 13211 }; 13212 } 13213 13214 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 13215 // Look up any existing declarations, but don't trigger declaration of all 13216 // implicit special members with this name. 13217 DeclarationName Name = FD->getDeclName(); 13218 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 13219 ForExternalRedeclaration); 13220 for (auto *D : FD->getParent()->lookup(Name)) 13221 if (auto *Acceptable = R.getAcceptableDecl(D)) 13222 R.addDecl(Acceptable); 13223 R.resolveKind(); 13224 R.suppressDiagnostics(); 13225 13226 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 13227 } 13228 13229 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 13230 QualType ResultTy, 13231 ArrayRef<QualType> Args) { 13232 // Build an exception specification pointing back at this constructor. 13233 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 13234 13235 LangAS AS = getDefaultCXXMethodAddrSpace(); 13236 if (AS != LangAS::Default) { 13237 EPI.TypeQuals.addAddressSpace(AS); 13238 } 13239 13240 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 13241 SpecialMem->setType(QT); 13242 13243 // During template instantiation of implicit special member functions we need 13244 // a reliable TypeSourceInfo for the function prototype in order to allow 13245 // functions to be substituted. 13246 if (inTemplateInstantiation() && 13247 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) { 13248 TypeSourceInfo *TSI = 13249 Context.getTrivialTypeSourceInfo(SpecialMem->getType()); 13250 SpecialMem->setTypeSourceInfo(TSI); 13251 } 13252 } 13253 13254 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 13255 CXXRecordDecl *ClassDecl) { 13256 // C++ [class.ctor]p5: 13257 // A default constructor for a class X is a constructor of class X 13258 // that can be called without an argument. If there is no 13259 // user-declared constructor for class X, a default constructor is 13260 // implicitly declared. An implicitly-declared default constructor 13261 // is an inline public member of its class. 13262 assert(ClassDecl->needsImplicitDefaultConstructor() && 13263 "Should not build implicit default constructor!"); 13264 13265 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 13266 if (DSM.isAlreadyBeingDeclared()) 13267 return nullptr; 13268 13269 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13270 CXXDefaultConstructor, 13271 false); 13272 13273 // Create the actual constructor declaration. 13274 CanQualType ClassType 13275 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13276 SourceLocation ClassLoc = ClassDecl->getLocation(); 13277 DeclarationName Name 13278 = Context.DeclarationNames.getCXXConstructorName(ClassType); 13279 DeclarationNameInfo NameInfo(Name, ClassLoc); 13280 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 13281 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 13282 /*TInfo=*/nullptr, ExplicitSpecifier(), 13283 getCurFPFeatures().isFPConstrained(), 13284 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 13285 Constexpr ? ConstexprSpecKind::Constexpr 13286 : ConstexprSpecKind::Unspecified); 13287 DefaultCon->setAccess(AS_public); 13288 DefaultCon->setDefaulted(); 13289 13290 if (getLangOpts().CUDA) { 13291 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 13292 DefaultCon, 13293 /* ConstRHS */ false, 13294 /* Diagnose */ false); 13295 } 13296 13297 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 13298 13299 // We don't need to use SpecialMemberIsTrivial here; triviality for default 13300 // constructors is easy to compute. 13301 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 13302 13303 // Note that we have declared this constructor. 13304 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 13305 13306 Scope *S = getScopeForContext(ClassDecl); 13307 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 13308 13309 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 13310 SetDeclDeleted(DefaultCon, ClassLoc); 13311 13312 if (S) 13313 PushOnScopeChains(DefaultCon, S, false); 13314 ClassDecl->addDecl(DefaultCon); 13315 13316 return DefaultCon; 13317 } 13318 13319 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 13320 CXXConstructorDecl *Constructor) { 13321 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 13322 !Constructor->doesThisDeclarationHaveABody() && 13323 !Constructor->isDeleted()) && 13324 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 13325 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13326 return; 13327 13328 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13329 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 13330 13331 SynthesizedFunctionScope Scope(*this, Constructor); 13332 13333 // The exception specification is needed because we are defining the 13334 // function. 13335 ResolveExceptionSpec(CurrentLocation, 13336 Constructor->getType()->castAs<FunctionProtoType>()); 13337 MarkVTableUsed(CurrentLocation, ClassDecl); 13338 13339 // Add a context note for diagnostics produced after this point. 13340 Scope.addContextNote(CurrentLocation); 13341 13342 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 13343 Constructor->setInvalidDecl(); 13344 return; 13345 } 13346 13347 SourceLocation Loc = Constructor->getEndLoc().isValid() 13348 ? Constructor->getEndLoc() 13349 : Constructor->getLocation(); 13350 Constructor->setBody(new (Context) CompoundStmt(Loc)); 13351 Constructor->markUsed(Context); 13352 13353 if (ASTMutationListener *L = getASTMutationListener()) { 13354 L->CompletedImplicitDefinition(Constructor); 13355 } 13356 13357 DiagnoseUninitializedFields(*this, Constructor); 13358 } 13359 13360 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 13361 // Perform any delayed checks on exception specifications. 13362 CheckDelayedMemberExceptionSpecs(); 13363 } 13364 13365 /// Find or create the fake constructor we synthesize to model constructing an 13366 /// object of a derived class via a constructor of a base class. 13367 CXXConstructorDecl * 13368 Sema::findInheritingConstructor(SourceLocation Loc, 13369 CXXConstructorDecl *BaseCtor, 13370 ConstructorUsingShadowDecl *Shadow) { 13371 CXXRecordDecl *Derived = Shadow->getParent(); 13372 SourceLocation UsingLoc = Shadow->getLocation(); 13373 13374 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 13375 // For now we use the name of the base class constructor as a member of the 13376 // derived class to indicate a (fake) inherited constructor name. 13377 DeclarationName Name = BaseCtor->getDeclName(); 13378 13379 // Check to see if we already have a fake constructor for this inherited 13380 // constructor call. 13381 for (NamedDecl *Ctor : Derived->lookup(Name)) 13382 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 13383 ->getInheritedConstructor() 13384 .getConstructor(), 13385 BaseCtor)) 13386 return cast<CXXConstructorDecl>(Ctor); 13387 13388 DeclarationNameInfo NameInfo(Name, UsingLoc); 13389 TypeSourceInfo *TInfo = 13390 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 13391 FunctionProtoTypeLoc ProtoLoc = 13392 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 13393 13394 // Check the inherited constructor is valid and find the list of base classes 13395 // from which it was inherited. 13396 InheritedConstructorInfo ICI(*this, Loc, Shadow); 13397 13398 bool Constexpr = 13399 BaseCtor->isConstexpr() && 13400 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 13401 false, BaseCtor, &ICI); 13402 13403 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 13404 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 13405 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 13406 /*isInline=*/true, 13407 /*isImplicitlyDeclared=*/true, 13408 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified, 13409 InheritedConstructor(Shadow, BaseCtor), 13410 BaseCtor->getTrailingRequiresClause()); 13411 if (Shadow->isInvalidDecl()) 13412 DerivedCtor->setInvalidDecl(); 13413 13414 // Build an unevaluated exception specification for this fake constructor. 13415 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 13416 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13417 EPI.ExceptionSpec.Type = EST_Unevaluated; 13418 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 13419 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 13420 FPT->getParamTypes(), EPI)); 13421 13422 // Build the parameter declarations. 13423 SmallVector<ParmVarDecl *, 16> ParamDecls; 13424 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 13425 TypeSourceInfo *TInfo = 13426 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 13427 ParmVarDecl *PD = ParmVarDecl::Create( 13428 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 13429 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 13430 PD->setScopeInfo(0, I); 13431 PD->setImplicit(); 13432 // Ensure attributes are propagated onto parameters (this matters for 13433 // format, pass_object_size, ...). 13434 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 13435 ParamDecls.push_back(PD); 13436 ProtoLoc.setParam(I, PD); 13437 } 13438 13439 // Set up the new constructor. 13440 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 13441 DerivedCtor->setAccess(BaseCtor->getAccess()); 13442 DerivedCtor->setParams(ParamDecls); 13443 Derived->addDecl(DerivedCtor); 13444 13445 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 13446 SetDeclDeleted(DerivedCtor, UsingLoc); 13447 13448 return DerivedCtor; 13449 } 13450 13451 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 13452 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 13453 Ctor->getInheritedConstructor().getShadowDecl()); 13454 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 13455 /*Diagnose*/true); 13456 } 13457 13458 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 13459 CXXConstructorDecl *Constructor) { 13460 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13461 assert(Constructor->getInheritedConstructor() && 13462 !Constructor->doesThisDeclarationHaveABody() && 13463 !Constructor->isDeleted()); 13464 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13465 return; 13466 13467 // Initializations are performed "as if by a defaulted default constructor", 13468 // so enter the appropriate scope. 13469 SynthesizedFunctionScope Scope(*this, Constructor); 13470 13471 // The exception specification is needed because we are defining the 13472 // function. 13473 ResolveExceptionSpec(CurrentLocation, 13474 Constructor->getType()->castAs<FunctionProtoType>()); 13475 MarkVTableUsed(CurrentLocation, ClassDecl); 13476 13477 // Add a context note for diagnostics produced after this point. 13478 Scope.addContextNote(CurrentLocation); 13479 13480 ConstructorUsingShadowDecl *Shadow = 13481 Constructor->getInheritedConstructor().getShadowDecl(); 13482 CXXConstructorDecl *InheritedCtor = 13483 Constructor->getInheritedConstructor().getConstructor(); 13484 13485 // [class.inhctor.init]p1: 13486 // initialization proceeds as if a defaulted default constructor is used to 13487 // initialize the D object and each base class subobject from which the 13488 // constructor was inherited 13489 13490 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 13491 CXXRecordDecl *RD = Shadow->getParent(); 13492 SourceLocation InitLoc = Shadow->getLocation(); 13493 13494 // Build explicit initializers for all base classes from which the 13495 // constructor was inherited. 13496 SmallVector<CXXCtorInitializer*, 8> Inits; 13497 for (bool VBase : {false, true}) { 13498 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 13499 if (B.isVirtual() != VBase) 13500 continue; 13501 13502 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 13503 if (!BaseRD) 13504 continue; 13505 13506 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 13507 if (!BaseCtor.first) 13508 continue; 13509 13510 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 13511 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 13512 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 13513 13514 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 13515 Inits.push_back(new (Context) CXXCtorInitializer( 13516 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 13517 SourceLocation())); 13518 } 13519 } 13520 13521 // We now proceed as if for a defaulted default constructor, with the relevant 13522 // initializers replaced. 13523 13524 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 13525 Constructor->setInvalidDecl(); 13526 return; 13527 } 13528 13529 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 13530 Constructor->markUsed(Context); 13531 13532 if (ASTMutationListener *L = getASTMutationListener()) { 13533 L->CompletedImplicitDefinition(Constructor); 13534 } 13535 13536 DiagnoseUninitializedFields(*this, Constructor); 13537 } 13538 13539 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 13540 // C++ [class.dtor]p2: 13541 // If a class has no user-declared destructor, a destructor is 13542 // declared implicitly. An implicitly-declared destructor is an 13543 // inline public member of its class. 13544 assert(ClassDecl->needsImplicitDestructor()); 13545 13546 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 13547 if (DSM.isAlreadyBeingDeclared()) 13548 return nullptr; 13549 13550 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13551 CXXDestructor, 13552 false); 13553 13554 // Create the actual destructor declaration. 13555 CanQualType ClassType 13556 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13557 SourceLocation ClassLoc = ClassDecl->getLocation(); 13558 DeclarationName Name 13559 = Context.DeclarationNames.getCXXDestructorName(ClassType); 13560 DeclarationNameInfo NameInfo(Name, ClassLoc); 13561 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create( 13562 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr, 13563 getCurFPFeatures().isFPConstrained(), 13564 /*isInline=*/true, 13565 /*isImplicitlyDeclared=*/true, 13566 Constexpr ? ConstexprSpecKind::Constexpr 13567 : ConstexprSpecKind::Unspecified); 13568 Destructor->setAccess(AS_public); 13569 Destructor->setDefaulted(); 13570 13571 if (getLangOpts().CUDA) { 13572 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 13573 Destructor, 13574 /* ConstRHS */ false, 13575 /* Diagnose */ false); 13576 } 13577 13578 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 13579 13580 // We don't need to use SpecialMemberIsTrivial here; triviality for 13581 // destructors is easy to compute. 13582 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 13583 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 13584 ClassDecl->hasTrivialDestructorForCall()); 13585 13586 // Note that we have declared this destructor. 13587 ++getASTContext().NumImplicitDestructorsDeclared; 13588 13589 Scope *S = getScopeForContext(ClassDecl); 13590 CheckImplicitSpecialMemberDeclaration(S, Destructor); 13591 13592 // We can't check whether an implicit destructor is deleted before we complete 13593 // the definition of the class, because its validity depends on the alignment 13594 // of the class. We'll check this from ActOnFields once the class is complete. 13595 if (ClassDecl->isCompleteDefinition() && 13596 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 13597 SetDeclDeleted(Destructor, ClassLoc); 13598 13599 // Introduce this destructor into its scope. 13600 if (S) 13601 PushOnScopeChains(Destructor, S, false); 13602 ClassDecl->addDecl(Destructor); 13603 13604 return Destructor; 13605 } 13606 13607 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 13608 CXXDestructorDecl *Destructor) { 13609 assert((Destructor->isDefaulted() && 13610 !Destructor->doesThisDeclarationHaveABody() && 13611 !Destructor->isDeleted()) && 13612 "DefineImplicitDestructor - call it for implicit default dtor"); 13613 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 13614 return; 13615 13616 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13617 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 13618 13619 SynthesizedFunctionScope Scope(*this, Destructor); 13620 13621 // The exception specification is needed because we are defining the 13622 // function. 13623 ResolveExceptionSpec(CurrentLocation, 13624 Destructor->getType()->castAs<FunctionProtoType>()); 13625 MarkVTableUsed(CurrentLocation, ClassDecl); 13626 13627 // Add a context note for diagnostics produced after this point. 13628 Scope.addContextNote(CurrentLocation); 13629 13630 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13631 Destructor->getParent()); 13632 13633 if (CheckDestructor(Destructor)) { 13634 Destructor->setInvalidDecl(); 13635 return; 13636 } 13637 13638 SourceLocation Loc = Destructor->getEndLoc().isValid() 13639 ? Destructor->getEndLoc() 13640 : Destructor->getLocation(); 13641 Destructor->setBody(new (Context) CompoundStmt(Loc)); 13642 Destructor->markUsed(Context); 13643 13644 if (ASTMutationListener *L = getASTMutationListener()) { 13645 L->CompletedImplicitDefinition(Destructor); 13646 } 13647 } 13648 13649 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 13650 CXXDestructorDecl *Destructor) { 13651 if (Destructor->isInvalidDecl()) 13652 return; 13653 13654 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13655 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() && 13656 "implicit complete dtors unneeded outside MS ABI"); 13657 assert(ClassDecl->getNumVBases() > 0 && 13658 "complete dtor only exists for classes with vbases"); 13659 13660 SynthesizedFunctionScope Scope(*this, Destructor); 13661 13662 // Add a context note for diagnostics produced after this point. 13663 Scope.addContextNote(CurrentLocation); 13664 13665 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl); 13666 } 13667 13668 /// Perform any semantic analysis which needs to be delayed until all 13669 /// pending class member declarations have been parsed. 13670 void Sema::ActOnFinishCXXMemberDecls() { 13671 // If the context is an invalid C++ class, just suppress these checks. 13672 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 13673 if (Record->isInvalidDecl()) { 13674 DelayedOverridingExceptionSpecChecks.clear(); 13675 DelayedEquivalentExceptionSpecChecks.clear(); 13676 return; 13677 } 13678 checkForMultipleExportedDefaultConstructors(*this, Record); 13679 } 13680 } 13681 13682 void Sema::ActOnFinishCXXNonNestedClass() { 13683 referenceDLLExportedClassMethods(); 13684 13685 if (!DelayedDllExportMemberFunctions.empty()) { 13686 SmallVector<CXXMethodDecl*, 4> WorkList; 13687 std::swap(DelayedDllExportMemberFunctions, WorkList); 13688 for (CXXMethodDecl *M : WorkList) { 13689 DefineDefaultedFunction(*this, M, M->getLocation()); 13690 13691 // Pass the method to the consumer to get emitted. This is not necessary 13692 // for explicit instantiation definitions, as they will get emitted 13693 // anyway. 13694 if (M->getParent()->getTemplateSpecializationKind() != 13695 TSK_ExplicitInstantiationDefinition) 13696 ActOnFinishInlineFunctionDef(M); 13697 } 13698 } 13699 } 13700 13701 void Sema::referenceDLLExportedClassMethods() { 13702 if (!DelayedDllExportClasses.empty()) { 13703 // Calling ReferenceDllExportedMembers might cause the current function to 13704 // be called again, so use a local copy of DelayedDllExportClasses. 13705 SmallVector<CXXRecordDecl *, 4> WorkList; 13706 std::swap(DelayedDllExportClasses, WorkList); 13707 for (CXXRecordDecl *Class : WorkList) 13708 ReferenceDllExportedMembers(*this, Class); 13709 } 13710 } 13711 13712 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 13713 assert(getLangOpts().CPlusPlus11 && 13714 "adjusting dtor exception specs was introduced in c++11"); 13715 13716 if (Destructor->isDependentContext()) 13717 return; 13718 13719 // C++11 [class.dtor]p3: 13720 // A declaration of a destructor that does not have an exception- 13721 // specification is implicitly considered to have the same exception- 13722 // specification as an implicit declaration. 13723 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); 13724 if (DtorType->hasExceptionSpec()) 13725 return; 13726 13727 // Replace the destructor's type, building off the existing one. Fortunately, 13728 // the only thing of interest in the destructor type is its extended info. 13729 // The return and arguments are fixed. 13730 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 13731 EPI.ExceptionSpec.Type = EST_Unevaluated; 13732 EPI.ExceptionSpec.SourceDecl = Destructor; 13733 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 13734 13735 // FIXME: If the destructor has a body that could throw, and the newly created 13736 // spec doesn't allow exceptions, we should emit a warning, because this 13737 // change in behavior can break conforming C++03 programs at runtime. 13738 // However, we don't have a body or an exception specification yet, so it 13739 // needs to be done somewhere else. 13740 } 13741 13742 namespace { 13743 /// An abstract base class for all helper classes used in building the 13744 // copy/move operators. These classes serve as factory functions and help us 13745 // avoid using the same Expr* in the AST twice. 13746 class ExprBuilder { 13747 ExprBuilder(const ExprBuilder&) = delete; 13748 ExprBuilder &operator=(const ExprBuilder&) = delete; 13749 13750 protected: 13751 static Expr *assertNotNull(Expr *E) { 13752 assert(E && "Expression construction must not fail."); 13753 return E; 13754 } 13755 13756 public: 13757 ExprBuilder() {} 13758 virtual ~ExprBuilder() {} 13759 13760 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 13761 }; 13762 13763 class RefBuilder: public ExprBuilder { 13764 VarDecl *Var; 13765 QualType VarType; 13766 13767 public: 13768 Expr *build(Sema &S, SourceLocation Loc) const override { 13769 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 13770 } 13771 13772 RefBuilder(VarDecl *Var, QualType VarType) 13773 : Var(Var), VarType(VarType) {} 13774 }; 13775 13776 class ThisBuilder: public ExprBuilder { 13777 public: 13778 Expr *build(Sema &S, SourceLocation Loc) const override { 13779 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 13780 } 13781 }; 13782 13783 class CastBuilder: public ExprBuilder { 13784 const ExprBuilder &Builder; 13785 QualType Type; 13786 ExprValueKind Kind; 13787 const CXXCastPath &Path; 13788 13789 public: 13790 Expr *build(Sema &S, SourceLocation Loc) const override { 13791 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 13792 CK_UncheckedDerivedToBase, Kind, 13793 &Path).get()); 13794 } 13795 13796 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 13797 const CXXCastPath &Path) 13798 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 13799 }; 13800 13801 class DerefBuilder: public ExprBuilder { 13802 const ExprBuilder &Builder; 13803 13804 public: 13805 Expr *build(Sema &S, SourceLocation Loc) const override { 13806 return assertNotNull( 13807 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 13808 } 13809 13810 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13811 }; 13812 13813 class MemberBuilder: public ExprBuilder { 13814 const ExprBuilder &Builder; 13815 QualType Type; 13816 CXXScopeSpec SS; 13817 bool IsArrow; 13818 LookupResult &MemberLookup; 13819 13820 public: 13821 Expr *build(Sema &S, SourceLocation Loc) const override { 13822 return assertNotNull(S.BuildMemberReferenceExpr( 13823 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 13824 nullptr, MemberLookup, nullptr, nullptr).get()); 13825 } 13826 13827 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 13828 LookupResult &MemberLookup) 13829 : Builder(Builder), Type(Type), IsArrow(IsArrow), 13830 MemberLookup(MemberLookup) {} 13831 }; 13832 13833 class MoveCastBuilder: public ExprBuilder { 13834 const ExprBuilder &Builder; 13835 13836 public: 13837 Expr *build(Sema &S, SourceLocation Loc) const override { 13838 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 13839 } 13840 13841 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13842 }; 13843 13844 class LvalueConvBuilder: public ExprBuilder { 13845 const ExprBuilder &Builder; 13846 13847 public: 13848 Expr *build(Sema &S, SourceLocation Loc) const override { 13849 return assertNotNull( 13850 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 13851 } 13852 13853 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13854 }; 13855 13856 class SubscriptBuilder: public ExprBuilder { 13857 const ExprBuilder &Base; 13858 const ExprBuilder &Index; 13859 13860 public: 13861 Expr *build(Sema &S, SourceLocation Loc) const override { 13862 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 13863 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 13864 } 13865 13866 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 13867 : Base(Base), Index(Index) {} 13868 }; 13869 13870 } // end anonymous namespace 13871 13872 /// When generating a defaulted copy or move assignment operator, if a field 13873 /// should be copied with __builtin_memcpy rather than via explicit assignments, 13874 /// do so. This optimization only applies for arrays of scalars, and for arrays 13875 /// of class type where the selected copy/move-assignment operator is trivial. 13876 static StmtResult 13877 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 13878 const ExprBuilder &ToB, const ExprBuilder &FromB) { 13879 // Compute the size of the memory buffer to be copied. 13880 QualType SizeType = S.Context.getSizeType(); 13881 llvm::APInt Size(S.Context.getTypeSize(SizeType), 13882 S.Context.getTypeSizeInChars(T).getQuantity()); 13883 13884 // Take the address of the field references for "from" and "to". We 13885 // directly construct UnaryOperators here because semantic analysis 13886 // does not permit us to take the address of an xvalue. 13887 Expr *From = FromB.build(S, Loc); 13888 From = UnaryOperator::Create( 13889 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()), 13890 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13891 Expr *To = ToB.build(S, Loc); 13892 To = UnaryOperator::Create( 13893 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()), 13894 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13895 13896 const Type *E = T->getBaseElementTypeUnsafe(); 13897 bool NeedsCollectableMemCpy = 13898 E->isRecordType() && 13899 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 13900 13901 // Create a reference to the __builtin_objc_memmove_collectable function 13902 StringRef MemCpyName = NeedsCollectableMemCpy ? 13903 "__builtin_objc_memmove_collectable" : 13904 "__builtin_memcpy"; 13905 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 13906 Sema::LookupOrdinaryName); 13907 S.LookupName(R, S.TUScope, true); 13908 13909 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 13910 if (!MemCpy) 13911 // Something went horribly wrong earlier, and we will have complained 13912 // about it. 13913 return StmtError(); 13914 13915 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 13916 VK_PRValue, Loc, nullptr); 13917 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 13918 13919 Expr *CallArgs[] = { 13920 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 13921 }; 13922 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 13923 Loc, CallArgs, Loc); 13924 13925 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 13926 return Call.getAs<Stmt>(); 13927 } 13928 13929 /// Builds a statement that copies/moves the given entity from \p From to 13930 /// \c To. 13931 /// 13932 /// This routine is used to copy/move the members of a class with an 13933 /// implicitly-declared copy/move assignment operator. When the entities being 13934 /// copied are arrays, this routine builds for loops to copy them. 13935 /// 13936 /// \param S The Sema object used for type-checking. 13937 /// 13938 /// \param Loc The location where the implicit copy/move is being generated. 13939 /// 13940 /// \param T The type of the expressions being copied/moved. Both expressions 13941 /// must have this type. 13942 /// 13943 /// \param To The expression we are copying/moving to. 13944 /// 13945 /// \param From The expression we are copying/moving from. 13946 /// 13947 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 13948 /// Otherwise, it's a non-static member subobject. 13949 /// 13950 /// \param Copying Whether we're copying or moving. 13951 /// 13952 /// \param Depth Internal parameter recording the depth of the recursion. 13953 /// 13954 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 13955 /// if a memcpy should be used instead. 13956 static StmtResult 13957 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 13958 const ExprBuilder &To, const ExprBuilder &From, 13959 bool CopyingBaseSubobject, bool Copying, 13960 unsigned Depth = 0) { 13961 // C++11 [class.copy]p28: 13962 // Each subobject is assigned in the manner appropriate to its type: 13963 // 13964 // - if the subobject is of class type, as if by a call to operator= with 13965 // the subobject as the object expression and the corresponding 13966 // subobject of x as a single function argument (as if by explicit 13967 // qualification; that is, ignoring any possible virtual overriding 13968 // functions in more derived classes); 13969 // 13970 // C++03 [class.copy]p13: 13971 // - if the subobject is of class type, the copy assignment operator for 13972 // the class is used (as if by explicit qualification; that is, 13973 // ignoring any possible virtual overriding functions in more derived 13974 // classes); 13975 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 13976 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 13977 13978 // Look for operator=. 13979 DeclarationName Name 13980 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13981 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 13982 S.LookupQualifiedName(OpLookup, ClassDecl, false); 13983 13984 // Prior to C++11, filter out any result that isn't a copy/move-assignment 13985 // operator. 13986 if (!S.getLangOpts().CPlusPlus11) { 13987 LookupResult::Filter F = OpLookup.makeFilter(); 13988 while (F.hasNext()) { 13989 NamedDecl *D = F.next(); 13990 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 13991 if (Method->isCopyAssignmentOperator() || 13992 (!Copying && Method->isMoveAssignmentOperator())) 13993 continue; 13994 13995 F.erase(); 13996 } 13997 F.done(); 13998 } 13999 14000 // Suppress the protected check (C++ [class.protected]) for each of the 14001 // assignment operators we found. This strange dance is required when 14002 // we're assigning via a base classes's copy-assignment operator. To 14003 // ensure that we're getting the right base class subobject (without 14004 // ambiguities), we need to cast "this" to that subobject type; to 14005 // ensure that we don't go through the virtual call mechanism, we need 14006 // to qualify the operator= name with the base class (see below). However, 14007 // this means that if the base class has a protected copy assignment 14008 // operator, the protected member access check will fail. So, we 14009 // rewrite "protected" access to "public" access in this case, since we 14010 // know by construction that we're calling from a derived class. 14011 if (CopyingBaseSubobject) { 14012 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 14013 L != LEnd; ++L) { 14014 if (L.getAccess() == AS_protected) 14015 L.setAccess(AS_public); 14016 } 14017 } 14018 14019 // Create the nested-name-specifier that will be used to qualify the 14020 // reference to operator=; this is required to suppress the virtual 14021 // call mechanism. 14022 CXXScopeSpec SS; 14023 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 14024 SS.MakeTrivial(S.Context, 14025 NestedNameSpecifier::Create(S.Context, nullptr, false, 14026 CanonicalT), 14027 Loc); 14028 14029 // Create the reference to operator=. 14030 ExprResult OpEqualRef 14031 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 14032 SS, /*TemplateKWLoc=*/SourceLocation(), 14033 /*FirstQualifierInScope=*/nullptr, 14034 OpLookup, 14035 /*TemplateArgs=*/nullptr, /*S*/nullptr, 14036 /*SuppressQualifierCheck=*/true); 14037 if (OpEqualRef.isInvalid()) 14038 return StmtError(); 14039 14040 // Build the call to the assignment operator. 14041 14042 Expr *FromInst = From.build(S, Loc); 14043 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 14044 OpEqualRef.getAs<Expr>(), 14045 Loc, FromInst, Loc); 14046 if (Call.isInvalid()) 14047 return StmtError(); 14048 14049 // If we built a call to a trivial 'operator=' while copying an array, 14050 // bail out. We'll replace the whole shebang with a memcpy. 14051 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 14052 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 14053 return StmtResult((Stmt*)nullptr); 14054 14055 // Convert to an expression-statement, and clean up any produced 14056 // temporaries. 14057 return S.ActOnExprStmt(Call); 14058 } 14059 14060 // - if the subobject is of scalar type, the built-in assignment 14061 // operator is used. 14062 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 14063 if (!ArrayTy) { 14064 ExprResult Assignment = S.CreateBuiltinBinOp( 14065 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 14066 if (Assignment.isInvalid()) 14067 return StmtError(); 14068 return S.ActOnExprStmt(Assignment); 14069 } 14070 14071 // - if the subobject is an array, each element is assigned, in the 14072 // manner appropriate to the element type; 14073 14074 // Construct a loop over the array bounds, e.g., 14075 // 14076 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 14077 // 14078 // that will copy each of the array elements. 14079 QualType SizeType = S.Context.getSizeType(); 14080 14081 // Create the iteration variable. 14082 IdentifierInfo *IterationVarName = nullptr; 14083 { 14084 SmallString<8> Str; 14085 llvm::raw_svector_ostream OS(Str); 14086 OS << "__i" << Depth; 14087 IterationVarName = &S.Context.Idents.get(OS.str()); 14088 } 14089 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 14090 IterationVarName, SizeType, 14091 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 14092 SC_None); 14093 14094 // Initialize the iteration variable to zero. 14095 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 14096 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 14097 14098 // Creates a reference to the iteration variable. 14099 RefBuilder IterationVarRef(IterationVar, SizeType); 14100 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 14101 14102 // Create the DeclStmt that holds the iteration variable. 14103 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 14104 14105 // Subscript the "from" and "to" expressions with the iteration variable. 14106 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 14107 MoveCastBuilder FromIndexMove(FromIndexCopy); 14108 const ExprBuilder *FromIndex; 14109 if (Copying) 14110 FromIndex = &FromIndexCopy; 14111 else 14112 FromIndex = &FromIndexMove; 14113 14114 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 14115 14116 // Build the copy/move for an individual element of the array. 14117 StmtResult Copy = 14118 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 14119 ToIndex, *FromIndex, CopyingBaseSubobject, 14120 Copying, Depth + 1); 14121 // Bail out if copying fails or if we determined that we should use memcpy. 14122 if (Copy.isInvalid() || !Copy.get()) 14123 return Copy; 14124 14125 // Create the comparison against the array bound. 14126 llvm::APInt Upper 14127 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 14128 Expr *Comparison = BinaryOperator::Create( 14129 S.Context, IterationVarRefRVal.build(S, Loc), 14130 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE, 14131 S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc, 14132 S.CurFPFeatureOverrides()); 14133 14134 // Create the pre-increment of the iteration variable. We can determine 14135 // whether the increment will overflow based on the value of the array 14136 // bound. 14137 Expr *Increment = UnaryOperator::Create( 14138 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue, 14139 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides()); 14140 14141 // Construct the loop that copies all elements of this array. 14142 return S.ActOnForStmt( 14143 Loc, Loc, InitStmt, 14144 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 14145 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 14146 } 14147 14148 static StmtResult 14149 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 14150 const ExprBuilder &To, const ExprBuilder &From, 14151 bool CopyingBaseSubobject, bool Copying) { 14152 // Maybe we should use a memcpy? 14153 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 14154 T.isTriviallyCopyableType(S.Context)) 14155 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 14156 14157 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 14158 CopyingBaseSubobject, 14159 Copying, 0)); 14160 14161 // If we ended up picking a trivial assignment operator for an array of a 14162 // non-trivially-copyable class type, just emit a memcpy. 14163 if (!Result.isInvalid() && !Result.get()) 14164 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 14165 14166 return Result; 14167 } 14168 14169 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 14170 // Note: The following rules are largely analoguous to the copy 14171 // constructor rules. Note that virtual bases are not taken into account 14172 // for determining the argument type of the operator. Note also that 14173 // operators taking an object instead of a reference are allowed. 14174 assert(ClassDecl->needsImplicitCopyAssignment()); 14175 14176 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 14177 if (DSM.isAlreadyBeingDeclared()) 14178 return nullptr; 14179 14180 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14181 LangAS AS = getDefaultCXXMethodAddrSpace(); 14182 if (AS != LangAS::Default) 14183 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14184 QualType RetType = Context.getLValueReferenceType(ArgType); 14185 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 14186 if (Const) 14187 ArgType = ArgType.withConst(); 14188 14189 ArgType = Context.getLValueReferenceType(ArgType); 14190 14191 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14192 CXXCopyAssignment, 14193 Const); 14194 14195 // An implicitly-declared copy assignment operator is an inline public 14196 // member of its class. 14197 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14198 SourceLocation ClassLoc = ClassDecl->getLocation(); 14199 DeclarationNameInfo NameInfo(Name, ClassLoc); 14200 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 14201 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14202 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14203 getCurFPFeatures().isFPConstrained(), 14204 /*isInline=*/true, 14205 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14206 SourceLocation()); 14207 CopyAssignment->setAccess(AS_public); 14208 CopyAssignment->setDefaulted(); 14209 CopyAssignment->setImplicit(); 14210 14211 if (getLangOpts().CUDA) { 14212 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 14213 CopyAssignment, 14214 /* ConstRHS */ Const, 14215 /* Diagnose */ false); 14216 } 14217 14218 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 14219 14220 // Add the parameter to the operator. 14221 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 14222 ClassLoc, ClassLoc, 14223 /*Id=*/nullptr, ArgType, 14224 /*TInfo=*/nullptr, SC_None, 14225 nullptr); 14226 CopyAssignment->setParams(FromParam); 14227 14228 CopyAssignment->setTrivial( 14229 ClassDecl->needsOverloadResolutionForCopyAssignment() 14230 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 14231 : ClassDecl->hasTrivialCopyAssignment()); 14232 14233 // Note that we have added this copy-assignment operator. 14234 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 14235 14236 Scope *S = getScopeForContext(ClassDecl); 14237 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 14238 14239 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) { 14240 ClassDecl->setImplicitCopyAssignmentIsDeleted(); 14241 SetDeclDeleted(CopyAssignment, ClassLoc); 14242 } 14243 14244 if (S) 14245 PushOnScopeChains(CopyAssignment, S, false); 14246 ClassDecl->addDecl(CopyAssignment); 14247 14248 return CopyAssignment; 14249 } 14250 14251 /// Diagnose an implicit copy operation for a class which is odr-used, but 14252 /// which is deprecated because the class has a user-declared copy constructor, 14253 /// copy assignment operator, or destructor. 14254 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 14255 assert(CopyOp->isImplicit()); 14256 14257 CXXRecordDecl *RD = CopyOp->getParent(); 14258 CXXMethodDecl *UserDeclaredOperation = nullptr; 14259 14260 // In Microsoft mode, assignment operations don't affect constructors and 14261 // vice versa. 14262 if (RD->hasUserDeclaredDestructor()) { 14263 UserDeclaredOperation = RD->getDestructor(); 14264 } else if (!isa<CXXConstructorDecl>(CopyOp) && 14265 RD->hasUserDeclaredCopyConstructor() && 14266 !S.getLangOpts().MSVCCompat) { 14267 // Find any user-declared copy constructor. 14268 for (auto *I : RD->ctors()) { 14269 if (I->isCopyConstructor()) { 14270 UserDeclaredOperation = I; 14271 break; 14272 } 14273 } 14274 assert(UserDeclaredOperation); 14275 } else if (isa<CXXConstructorDecl>(CopyOp) && 14276 RD->hasUserDeclaredCopyAssignment() && 14277 !S.getLangOpts().MSVCCompat) { 14278 // Find any user-declared move assignment operator. 14279 for (auto *I : RD->methods()) { 14280 if (I->isCopyAssignmentOperator()) { 14281 UserDeclaredOperation = I; 14282 break; 14283 } 14284 } 14285 assert(UserDeclaredOperation); 14286 } 14287 14288 if (UserDeclaredOperation) { 14289 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided(); 14290 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation); 14291 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp); 14292 unsigned DiagID = 14293 (UDOIsUserProvided && UDOIsDestructor) 14294 ? diag::warn_deprecated_copy_with_user_provided_dtor 14295 : (UDOIsUserProvided && !UDOIsDestructor) 14296 ? diag::warn_deprecated_copy_with_user_provided_copy 14297 : (!UDOIsUserProvided && UDOIsDestructor) 14298 ? diag::warn_deprecated_copy_with_dtor 14299 : diag::warn_deprecated_copy; 14300 S.Diag(UserDeclaredOperation->getLocation(), DiagID) 14301 << RD << IsCopyAssignment; 14302 } 14303 } 14304 14305 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 14306 CXXMethodDecl *CopyAssignOperator) { 14307 assert((CopyAssignOperator->isDefaulted() && 14308 CopyAssignOperator->isOverloadedOperator() && 14309 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 14310 !CopyAssignOperator->doesThisDeclarationHaveABody() && 14311 !CopyAssignOperator->isDeleted()) && 14312 "DefineImplicitCopyAssignment called for wrong function"); 14313 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 14314 return; 14315 14316 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 14317 if (ClassDecl->isInvalidDecl()) { 14318 CopyAssignOperator->setInvalidDecl(); 14319 return; 14320 } 14321 14322 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 14323 14324 // The exception specification is needed because we are defining the 14325 // function. 14326 ResolveExceptionSpec(CurrentLocation, 14327 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 14328 14329 // Add a context note for diagnostics produced after this point. 14330 Scope.addContextNote(CurrentLocation); 14331 14332 // C++11 [class.copy]p18: 14333 // The [definition of an implicitly declared copy assignment operator] is 14334 // deprecated if the class has a user-declared copy constructor or a 14335 // user-declared destructor. 14336 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 14337 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 14338 14339 // C++0x [class.copy]p30: 14340 // The implicitly-defined or explicitly-defaulted copy assignment operator 14341 // for a non-union class X performs memberwise copy assignment of its 14342 // subobjects. The direct base classes of X are assigned first, in the 14343 // order of their declaration in the base-specifier-list, and then the 14344 // immediate non-static data members of X are assigned, in the order in 14345 // which they were declared in the class definition. 14346 14347 // The statements that form the synthesized function body. 14348 SmallVector<Stmt*, 8> Statements; 14349 14350 // The parameter for the "other" object, which we are copying from. 14351 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 14352 Qualifiers OtherQuals = Other->getType().getQualifiers(); 14353 QualType OtherRefType = Other->getType(); 14354 if (const LValueReferenceType *OtherRef 14355 = OtherRefType->getAs<LValueReferenceType>()) { 14356 OtherRefType = OtherRef->getPointeeType(); 14357 OtherQuals = OtherRefType.getQualifiers(); 14358 } 14359 14360 // Our location for everything implicitly-generated. 14361 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 14362 ? CopyAssignOperator->getEndLoc() 14363 : CopyAssignOperator->getLocation(); 14364 14365 // Builds a DeclRefExpr for the "other" object. 14366 RefBuilder OtherRef(Other, OtherRefType); 14367 14368 // Builds the "this" pointer. 14369 ThisBuilder This; 14370 14371 // Assign base classes. 14372 bool Invalid = false; 14373 for (auto &Base : ClassDecl->bases()) { 14374 // Form the assignment: 14375 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 14376 QualType BaseType = Base.getType().getUnqualifiedType(); 14377 if (!BaseType->isRecordType()) { 14378 Invalid = true; 14379 continue; 14380 } 14381 14382 CXXCastPath BasePath; 14383 BasePath.push_back(&Base); 14384 14385 // Construct the "from" expression, which is an implicit cast to the 14386 // appropriately-qualified base type. 14387 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 14388 VK_LValue, BasePath); 14389 14390 // Dereference "this". 14391 DerefBuilder DerefThis(This); 14392 CastBuilder To(DerefThis, 14393 Context.getQualifiedType( 14394 BaseType, CopyAssignOperator->getMethodQualifiers()), 14395 VK_LValue, BasePath); 14396 14397 // Build the copy. 14398 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 14399 To, From, 14400 /*CopyingBaseSubobject=*/true, 14401 /*Copying=*/true); 14402 if (Copy.isInvalid()) { 14403 CopyAssignOperator->setInvalidDecl(); 14404 return; 14405 } 14406 14407 // Success! Record the copy. 14408 Statements.push_back(Copy.getAs<Expr>()); 14409 } 14410 14411 // Assign non-static members. 14412 for (auto *Field : ClassDecl->fields()) { 14413 // FIXME: We should form some kind of AST representation for the implied 14414 // memcpy in a union copy operation. 14415 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14416 continue; 14417 14418 if (Field->isInvalidDecl()) { 14419 Invalid = true; 14420 continue; 14421 } 14422 14423 // Check for members of reference type; we can't copy those. 14424 if (Field->getType()->isReferenceType()) { 14425 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14426 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14427 Diag(Field->getLocation(), diag::note_declared_at); 14428 Invalid = true; 14429 continue; 14430 } 14431 14432 // Check for members of const-qualified, non-class type. 14433 QualType BaseType = Context.getBaseElementType(Field->getType()); 14434 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14435 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14436 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14437 Diag(Field->getLocation(), diag::note_declared_at); 14438 Invalid = true; 14439 continue; 14440 } 14441 14442 // Suppress assigning zero-width bitfields. 14443 if (Field->isZeroLengthBitField(Context)) 14444 continue; 14445 14446 QualType FieldType = Field->getType().getNonReferenceType(); 14447 if (FieldType->isIncompleteArrayType()) { 14448 assert(ClassDecl->hasFlexibleArrayMember() && 14449 "Incomplete array type is not valid"); 14450 continue; 14451 } 14452 14453 // Build references to the field in the object we're copying from and to. 14454 CXXScopeSpec SS; // Intentionally empty 14455 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14456 LookupMemberName); 14457 MemberLookup.addDecl(Field); 14458 MemberLookup.resolveKind(); 14459 14460 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 14461 14462 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 14463 14464 // Build the copy of this field. 14465 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 14466 To, From, 14467 /*CopyingBaseSubobject=*/false, 14468 /*Copying=*/true); 14469 if (Copy.isInvalid()) { 14470 CopyAssignOperator->setInvalidDecl(); 14471 return; 14472 } 14473 14474 // Success! Record the copy. 14475 Statements.push_back(Copy.getAs<Stmt>()); 14476 } 14477 14478 if (!Invalid) { 14479 // Add a "return *this;" 14480 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14481 14482 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14483 if (Return.isInvalid()) 14484 Invalid = true; 14485 else 14486 Statements.push_back(Return.getAs<Stmt>()); 14487 } 14488 14489 if (Invalid) { 14490 CopyAssignOperator->setInvalidDecl(); 14491 return; 14492 } 14493 14494 StmtResult Body; 14495 { 14496 CompoundScopeRAII CompoundScope(*this); 14497 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14498 /*isStmtExpr=*/false); 14499 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14500 } 14501 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 14502 CopyAssignOperator->markUsed(Context); 14503 14504 if (ASTMutationListener *L = getASTMutationListener()) { 14505 L->CompletedImplicitDefinition(CopyAssignOperator); 14506 } 14507 } 14508 14509 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 14510 assert(ClassDecl->needsImplicitMoveAssignment()); 14511 14512 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 14513 if (DSM.isAlreadyBeingDeclared()) 14514 return nullptr; 14515 14516 // Note: The following rules are largely analoguous to the move 14517 // constructor rules. 14518 14519 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14520 LangAS AS = getDefaultCXXMethodAddrSpace(); 14521 if (AS != LangAS::Default) 14522 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14523 QualType RetType = Context.getLValueReferenceType(ArgType); 14524 ArgType = Context.getRValueReferenceType(ArgType); 14525 14526 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14527 CXXMoveAssignment, 14528 false); 14529 14530 // An implicitly-declared move assignment operator is an inline public 14531 // member of its class. 14532 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14533 SourceLocation ClassLoc = ClassDecl->getLocation(); 14534 DeclarationNameInfo NameInfo(Name, ClassLoc); 14535 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 14536 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14537 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14538 getCurFPFeatures().isFPConstrained(), 14539 /*isInline=*/true, 14540 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14541 SourceLocation()); 14542 MoveAssignment->setAccess(AS_public); 14543 MoveAssignment->setDefaulted(); 14544 MoveAssignment->setImplicit(); 14545 14546 if (getLangOpts().CUDA) { 14547 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 14548 MoveAssignment, 14549 /* ConstRHS */ false, 14550 /* Diagnose */ false); 14551 } 14552 14553 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType); 14554 14555 // Add the parameter to the operator. 14556 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 14557 ClassLoc, ClassLoc, 14558 /*Id=*/nullptr, ArgType, 14559 /*TInfo=*/nullptr, SC_None, 14560 nullptr); 14561 MoveAssignment->setParams(FromParam); 14562 14563 MoveAssignment->setTrivial( 14564 ClassDecl->needsOverloadResolutionForMoveAssignment() 14565 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 14566 : ClassDecl->hasTrivialMoveAssignment()); 14567 14568 // Note that we have added this copy-assignment operator. 14569 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 14570 14571 Scope *S = getScopeForContext(ClassDecl); 14572 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 14573 14574 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 14575 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 14576 SetDeclDeleted(MoveAssignment, ClassLoc); 14577 } 14578 14579 if (S) 14580 PushOnScopeChains(MoveAssignment, S, false); 14581 ClassDecl->addDecl(MoveAssignment); 14582 14583 return MoveAssignment; 14584 } 14585 14586 /// Check if we're implicitly defining a move assignment operator for a class 14587 /// with virtual bases. Such a move assignment might move-assign the virtual 14588 /// base multiple times. 14589 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 14590 SourceLocation CurrentLocation) { 14591 assert(!Class->isDependentContext() && "should not define dependent move"); 14592 14593 // Only a virtual base could get implicitly move-assigned multiple times. 14594 // Only a non-trivial move assignment can observe this. We only want to 14595 // diagnose if we implicitly define an assignment operator that assigns 14596 // two base classes, both of which move-assign the same virtual base. 14597 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 14598 Class->getNumBases() < 2) 14599 return; 14600 14601 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 14602 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 14603 VBaseMap VBases; 14604 14605 for (auto &BI : Class->bases()) { 14606 Worklist.push_back(&BI); 14607 while (!Worklist.empty()) { 14608 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 14609 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 14610 14611 // If the base has no non-trivial move assignment operators, 14612 // we don't care about moves from it. 14613 if (!Base->hasNonTrivialMoveAssignment()) 14614 continue; 14615 14616 // If there's nothing virtual here, skip it. 14617 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 14618 continue; 14619 14620 // If we're not actually going to call a move assignment for this base, 14621 // or the selected move assignment is trivial, skip it. 14622 Sema::SpecialMemberOverloadResult SMOR = 14623 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 14624 /*ConstArg*/false, /*VolatileArg*/false, 14625 /*RValueThis*/true, /*ConstThis*/false, 14626 /*VolatileThis*/false); 14627 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 14628 !SMOR.getMethod()->isMoveAssignmentOperator()) 14629 continue; 14630 14631 if (BaseSpec->isVirtual()) { 14632 // We're going to move-assign this virtual base, and its move 14633 // assignment operator is not trivial. If this can happen for 14634 // multiple distinct direct bases of Class, diagnose it. (If it 14635 // only happens in one base, we'll diagnose it when synthesizing 14636 // that base class's move assignment operator.) 14637 CXXBaseSpecifier *&Existing = 14638 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 14639 .first->second; 14640 if (Existing && Existing != &BI) { 14641 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 14642 << Class << Base; 14643 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 14644 << (Base->getCanonicalDecl() == 14645 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14646 << Base << Existing->getType() << Existing->getSourceRange(); 14647 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 14648 << (Base->getCanonicalDecl() == 14649 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14650 << Base << BI.getType() << BaseSpec->getSourceRange(); 14651 14652 // Only diagnose each vbase once. 14653 Existing = nullptr; 14654 } 14655 } else { 14656 // Only walk over bases that have defaulted move assignment operators. 14657 // We assume that any user-provided move assignment operator handles 14658 // the multiple-moves-of-vbase case itself somehow. 14659 if (!SMOR.getMethod()->isDefaulted()) 14660 continue; 14661 14662 // We're going to move the base classes of Base. Add them to the list. 14663 for (auto &BI : Base->bases()) 14664 Worklist.push_back(&BI); 14665 } 14666 } 14667 } 14668 } 14669 14670 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 14671 CXXMethodDecl *MoveAssignOperator) { 14672 assert((MoveAssignOperator->isDefaulted() && 14673 MoveAssignOperator->isOverloadedOperator() && 14674 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 14675 !MoveAssignOperator->doesThisDeclarationHaveABody() && 14676 !MoveAssignOperator->isDeleted()) && 14677 "DefineImplicitMoveAssignment called for wrong function"); 14678 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 14679 return; 14680 14681 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 14682 if (ClassDecl->isInvalidDecl()) { 14683 MoveAssignOperator->setInvalidDecl(); 14684 return; 14685 } 14686 14687 // C++0x [class.copy]p28: 14688 // The implicitly-defined or move assignment operator for a non-union class 14689 // X performs memberwise move assignment of its subobjects. The direct base 14690 // classes of X are assigned first, in the order of their declaration in the 14691 // base-specifier-list, and then the immediate non-static data members of X 14692 // are assigned, in the order in which they were declared in the class 14693 // definition. 14694 14695 // Issue a warning if our implicit move assignment operator will move 14696 // from a virtual base more than once. 14697 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 14698 14699 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 14700 14701 // The exception specification is needed because we are defining the 14702 // function. 14703 ResolveExceptionSpec(CurrentLocation, 14704 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 14705 14706 // Add a context note for diagnostics produced after this point. 14707 Scope.addContextNote(CurrentLocation); 14708 14709 // The statements that form the synthesized function body. 14710 SmallVector<Stmt*, 8> Statements; 14711 14712 // The parameter for the "other" object, which we are move from. 14713 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 14714 QualType OtherRefType = 14715 Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); 14716 14717 // Our location for everything implicitly-generated. 14718 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 14719 ? MoveAssignOperator->getEndLoc() 14720 : MoveAssignOperator->getLocation(); 14721 14722 // Builds a reference to the "other" object. 14723 RefBuilder OtherRef(Other, OtherRefType); 14724 // Cast to rvalue. 14725 MoveCastBuilder MoveOther(OtherRef); 14726 14727 // Builds the "this" pointer. 14728 ThisBuilder This; 14729 14730 // Assign base classes. 14731 bool Invalid = false; 14732 for (auto &Base : ClassDecl->bases()) { 14733 // C++11 [class.copy]p28: 14734 // It is unspecified whether subobjects representing virtual base classes 14735 // are assigned more than once by the implicitly-defined copy assignment 14736 // operator. 14737 // FIXME: Do not assign to a vbase that will be assigned by some other base 14738 // class. For a move-assignment, this can result in the vbase being moved 14739 // multiple times. 14740 14741 // Form the assignment: 14742 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 14743 QualType BaseType = Base.getType().getUnqualifiedType(); 14744 if (!BaseType->isRecordType()) { 14745 Invalid = true; 14746 continue; 14747 } 14748 14749 CXXCastPath BasePath; 14750 BasePath.push_back(&Base); 14751 14752 // Construct the "from" expression, which is an implicit cast to the 14753 // appropriately-qualified base type. 14754 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 14755 14756 // Dereference "this". 14757 DerefBuilder DerefThis(This); 14758 14759 // Implicitly cast "this" to the appropriately-qualified base type. 14760 CastBuilder To(DerefThis, 14761 Context.getQualifiedType( 14762 BaseType, MoveAssignOperator->getMethodQualifiers()), 14763 VK_LValue, BasePath); 14764 14765 // Build the move. 14766 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 14767 To, From, 14768 /*CopyingBaseSubobject=*/true, 14769 /*Copying=*/false); 14770 if (Move.isInvalid()) { 14771 MoveAssignOperator->setInvalidDecl(); 14772 return; 14773 } 14774 14775 // Success! Record the move. 14776 Statements.push_back(Move.getAs<Expr>()); 14777 } 14778 14779 // Assign non-static members. 14780 for (auto *Field : ClassDecl->fields()) { 14781 // FIXME: We should form some kind of AST representation for the implied 14782 // memcpy in a union copy operation. 14783 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14784 continue; 14785 14786 if (Field->isInvalidDecl()) { 14787 Invalid = true; 14788 continue; 14789 } 14790 14791 // Check for members of reference type; we can't move those. 14792 if (Field->getType()->isReferenceType()) { 14793 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14794 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14795 Diag(Field->getLocation(), diag::note_declared_at); 14796 Invalid = true; 14797 continue; 14798 } 14799 14800 // Check for members of const-qualified, non-class type. 14801 QualType BaseType = Context.getBaseElementType(Field->getType()); 14802 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14803 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14804 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14805 Diag(Field->getLocation(), diag::note_declared_at); 14806 Invalid = true; 14807 continue; 14808 } 14809 14810 // Suppress assigning zero-width bitfields. 14811 if (Field->isZeroLengthBitField(Context)) 14812 continue; 14813 14814 QualType FieldType = Field->getType().getNonReferenceType(); 14815 if (FieldType->isIncompleteArrayType()) { 14816 assert(ClassDecl->hasFlexibleArrayMember() && 14817 "Incomplete array type is not valid"); 14818 continue; 14819 } 14820 14821 // Build references to the field in the object we're copying from and to. 14822 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14823 LookupMemberName); 14824 MemberLookup.addDecl(Field); 14825 MemberLookup.resolveKind(); 14826 MemberBuilder From(MoveOther, OtherRefType, 14827 /*IsArrow=*/false, MemberLookup); 14828 MemberBuilder To(This, getCurrentThisType(), 14829 /*IsArrow=*/true, MemberLookup); 14830 14831 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 14832 "Member reference with rvalue base must be rvalue except for reference " 14833 "members, which aren't allowed for move assignment."); 14834 14835 // Build the move of this field. 14836 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 14837 To, From, 14838 /*CopyingBaseSubobject=*/false, 14839 /*Copying=*/false); 14840 if (Move.isInvalid()) { 14841 MoveAssignOperator->setInvalidDecl(); 14842 return; 14843 } 14844 14845 // Success! Record the copy. 14846 Statements.push_back(Move.getAs<Stmt>()); 14847 } 14848 14849 if (!Invalid) { 14850 // Add a "return *this;" 14851 ExprResult ThisObj = 14852 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14853 14854 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14855 if (Return.isInvalid()) 14856 Invalid = true; 14857 else 14858 Statements.push_back(Return.getAs<Stmt>()); 14859 } 14860 14861 if (Invalid) { 14862 MoveAssignOperator->setInvalidDecl(); 14863 return; 14864 } 14865 14866 StmtResult Body; 14867 { 14868 CompoundScopeRAII CompoundScope(*this); 14869 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14870 /*isStmtExpr=*/false); 14871 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14872 } 14873 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 14874 MoveAssignOperator->markUsed(Context); 14875 14876 if (ASTMutationListener *L = getASTMutationListener()) { 14877 L->CompletedImplicitDefinition(MoveAssignOperator); 14878 } 14879 } 14880 14881 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 14882 CXXRecordDecl *ClassDecl) { 14883 // C++ [class.copy]p4: 14884 // If the class definition does not explicitly declare a copy 14885 // constructor, one is declared implicitly. 14886 assert(ClassDecl->needsImplicitCopyConstructor()); 14887 14888 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 14889 if (DSM.isAlreadyBeingDeclared()) 14890 return nullptr; 14891 14892 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14893 QualType ArgType = ClassType; 14894 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 14895 if (Const) 14896 ArgType = ArgType.withConst(); 14897 14898 LangAS AS = getDefaultCXXMethodAddrSpace(); 14899 if (AS != LangAS::Default) 14900 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14901 14902 ArgType = Context.getLValueReferenceType(ArgType); 14903 14904 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14905 CXXCopyConstructor, 14906 Const); 14907 14908 DeclarationName Name 14909 = Context.DeclarationNames.getCXXConstructorName( 14910 Context.getCanonicalType(ClassType)); 14911 SourceLocation ClassLoc = ClassDecl->getLocation(); 14912 DeclarationNameInfo NameInfo(Name, ClassLoc); 14913 14914 // An implicitly-declared copy constructor is an inline public 14915 // member of its class. 14916 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 14917 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14918 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 14919 /*isInline=*/true, 14920 /*isImplicitlyDeclared=*/true, 14921 Constexpr ? ConstexprSpecKind::Constexpr 14922 : ConstexprSpecKind::Unspecified); 14923 CopyConstructor->setAccess(AS_public); 14924 CopyConstructor->setDefaulted(); 14925 14926 if (getLangOpts().CUDA) { 14927 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 14928 CopyConstructor, 14929 /* ConstRHS */ Const, 14930 /* Diagnose */ false); 14931 } 14932 14933 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 14934 14935 // During template instantiation of special member functions we need a 14936 // reliable TypeSourceInfo for the parameter types in order to allow functions 14937 // to be substituted. 14938 TypeSourceInfo *TSI = nullptr; 14939 if (inTemplateInstantiation() && ClassDecl->isLambda()) 14940 TSI = Context.getTrivialTypeSourceInfo(ArgType); 14941 14942 // Add the parameter to the constructor. 14943 ParmVarDecl *FromParam = 14944 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc, 14945 /*IdentifierInfo=*/nullptr, ArgType, 14946 /*TInfo=*/TSI, SC_None, nullptr); 14947 CopyConstructor->setParams(FromParam); 14948 14949 CopyConstructor->setTrivial( 14950 ClassDecl->needsOverloadResolutionForCopyConstructor() 14951 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 14952 : ClassDecl->hasTrivialCopyConstructor()); 14953 14954 CopyConstructor->setTrivialForCall( 14955 ClassDecl->hasAttr<TrivialABIAttr>() || 14956 (ClassDecl->needsOverloadResolutionForCopyConstructor() 14957 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 14958 TAH_ConsiderTrivialABI) 14959 : ClassDecl->hasTrivialCopyConstructorForCall())); 14960 14961 // Note that we have declared this constructor. 14962 ++getASTContext().NumImplicitCopyConstructorsDeclared; 14963 14964 Scope *S = getScopeForContext(ClassDecl); 14965 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 14966 14967 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 14968 ClassDecl->setImplicitCopyConstructorIsDeleted(); 14969 SetDeclDeleted(CopyConstructor, ClassLoc); 14970 } 14971 14972 if (S) 14973 PushOnScopeChains(CopyConstructor, S, false); 14974 ClassDecl->addDecl(CopyConstructor); 14975 14976 return CopyConstructor; 14977 } 14978 14979 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 14980 CXXConstructorDecl *CopyConstructor) { 14981 assert((CopyConstructor->isDefaulted() && 14982 CopyConstructor->isCopyConstructor() && 14983 !CopyConstructor->doesThisDeclarationHaveABody() && 14984 !CopyConstructor->isDeleted()) && 14985 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 14986 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 14987 return; 14988 14989 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 14990 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 14991 14992 SynthesizedFunctionScope Scope(*this, CopyConstructor); 14993 14994 // The exception specification is needed because we are defining the 14995 // function. 14996 ResolveExceptionSpec(CurrentLocation, 14997 CopyConstructor->getType()->castAs<FunctionProtoType>()); 14998 MarkVTableUsed(CurrentLocation, ClassDecl); 14999 15000 // Add a context note for diagnostics produced after this point. 15001 Scope.addContextNote(CurrentLocation); 15002 15003 // C++11 [class.copy]p7: 15004 // The [definition of an implicitly declared copy constructor] is 15005 // deprecated if the class has a user-declared copy assignment operator 15006 // or a user-declared destructor. 15007 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 15008 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 15009 15010 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 15011 CopyConstructor->setInvalidDecl(); 15012 } else { 15013 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 15014 ? CopyConstructor->getEndLoc() 15015 : CopyConstructor->getLocation(); 15016 Sema::CompoundScopeRAII CompoundScope(*this); 15017 CopyConstructor->setBody( 15018 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 15019 CopyConstructor->markUsed(Context); 15020 } 15021 15022 if (ASTMutationListener *L = getASTMutationListener()) { 15023 L->CompletedImplicitDefinition(CopyConstructor); 15024 } 15025 } 15026 15027 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 15028 CXXRecordDecl *ClassDecl) { 15029 assert(ClassDecl->needsImplicitMoveConstructor()); 15030 15031 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 15032 if (DSM.isAlreadyBeingDeclared()) 15033 return nullptr; 15034 15035 QualType ClassType = Context.getTypeDeclType(ClassDecl); 15036 15037 QualType ArgType = ClassType; 15038 LangAS AS = getDefaultCXXMethodAddrSpace(); 15039 if (AS != LangAS::Default) 15040 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 15041 ArgType = Context.getRValueReferenceType(ArgType); 15042 15043 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 15044 CXXMoveConstructor, 15045 false); 15046 15047 DeclarationName Name 15048 = Context.DeclarationNames.getCXXConstructorName( 15049 Context.getCanonicalType(ClassType)); 15050 SourceLocation ClassLoc = ClassDecl->getLocation(); 15051 DeclarationNameInfo NameInfo(Name, ClassLoc); 15052 15053 // C++11 [class.copy]p11: 15054 // An implicitly-declared copy/move constructor is an inline public 15055 // member of its class. 15056 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 15057 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 15058 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 15059 /*isInline=*/true, 15060 /*isImplicitlyDeclared=*/true, 15061 Constexpr ? ConstexprSpecKind::Constexpr 15062 : ConstexprSpecKind::Unspecified); 15063 MoveConstructor->setAccess(AS_public); 15064 MoveConstructor->setDefaulted(); 15065 15066 if (getLangOpts().CUDA) { 15067 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 15068 MoveConstructor, 15069 /* ConstRHS */ false, 15070 /* Diagnose */ false); 15071 } 15072 15073 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 15074 15075 // Add the parameter to the constructor. 15076 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 15077 ClassLoc, ClassLoc, 15078 /*IdentifierInfo=*/nullptr, 15079 ArgType, /*TInfo=*/nullptr, 15080 SC_None, nullptr); 15081 MoveConstructor->setParams(FromParam); 15082 15083 MoveConstructor->setTrivial( 15084 ClassDecl->needsOverloadResolutionForMoveConstructor() 15085 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 15086 : ClassDecl->hasTrivialMoveConstructor()); 15087 15088 MoveConstructor->setTrivialForCall( 15089 ClassDecl->hasAttr<TrivialABIAttr>() || 15090 (ClassDecl->needsOverloadResolutionForMoveConstructor() 15091 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 15092 TAH_ConsiderTrivialABI) 15093 : ClassDecl->hasTrivialMoveConstructorForCall())); 15094 15095 // Note that we have declared this constructor. 15096 ++getASTContext().NumImplicitMoveConstructorsDeclared; 15097 15098 Scope *S = getScopeForContext(ClassDecl); 15099 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 15100 15101 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 15102 ClassDecl->setImplicitMoveConstructorIsDeleted(); 15103 SetDeclDeleted(MoveConstructor, ClassLoc); 15104 } 15105 15106 if (S) 15107 PushOnScopeChains(MoveConstructor, S, false); 15108 ClassDecl->addDecl(MoveConstructor); 15109 15110 return MoveConstructor; 15111 } 15112 15113 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 15114 CXXConstructorDecl *MoveConstructor) { 15115 assert((MoveConstructor->isDefaulted() && 15116 MoveConstructor->isMoveConstructor() && 15117 !MoveConstructor->doesThisDeclarationHaveABody() && 15118 !MoveConstructor->isDeleted()) && 15119 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 15120 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 15121 return; 15122 15123 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 15124 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 15125 15126 SynthesizedFunctionScope Scope(*this, MoveConstructor); 15127 15128 // The exception specification is needed because we are defining the 15129 // function. 15130 ResolveExceptionSpec(CurrentLocation, 15131 MoveConstructor->getType()->castAs<FunctionProtoType>()); 15132 MarkVTableUsed(CurrentLocation, ClassDecl); 15133 15134 // Add a context note for diagnostics produced after this point. 15135 Scope.addContextNote(CurrentLocation); 15136 15137 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 15138 MoveConstructor->setInvalidDecl(); 15139 } else { 15140 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 15141 ? MoveConstructor->getEndLoc() 15142 : MoveConstructor->getLocation(); 15143 Sema::CompoundScopeRAII CompoundScope(*this); 15144 MoveConstructor->setBody(ActOnCompoundStmt( 15145 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 15146 MoveConstructor->markUsed(Context); 15147 } 15148 15149 if (ASTMutationListener *L = getASTMutationListener()) { 15150 L->CompletedImplicitDefinition(MoveConstructor); 15151 } 15152 } 15153 15154 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 15155 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 15156 } 15157 15158 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 15159 SourceLocation CurrentLocation, 15160 CXXConversionDecl *Conv) { 15161 SynthesizedFunctionScope Scope(*this, Conv); 15162 assert(!Conv->getReturnType()->isUndeducedType()); 15163 15164 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType(); 15165 CallingConv CC = 15166 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv(); 15167 15168 CXXRecordDecl *Lambda = Conv->getParent(); 15169 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 15170 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC); 15171 15172 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 15173 CallOp = InstantiateFunctionDeclaration( 15174 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 15175 if (!CallOp) 15176 return; 15177 15178 Invoker = InstantiateFunctionDeclaration( 15179 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 15180 if (!Invoker) 15181 return; 15182 } 15183 15184 if (CallOp->isInvalidDecl()) 15185 return; 15186 15187 // Mark the call operator referenced (and add to pending instantiations 15188 // if necessary). 15189 // For both the conversion and static-invoker template specializations 15190 // we construct their body's in this function, so no need to add them 15191 // to the PendingInstantiations. 15192 MarkFunctionReferenced(CurrentLocation, CallOp); 15193 15194 // Fill in the __invoke function with a dummy implementation. IR generation 15195 // will fill in the actual details. Update its type in case it contained 15196 // an 'auto'. 15197 Invoker->markUsed(Context); 15198 Invoker->setReferenced(); 15199 Invoker->setType(Conv->getReturnType()->getPointeeType()); 15200 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 15201 15202 // Construct the body of the conversion function { return __invoke; }. 15203 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 15204 VK_LValue, Conv->getLocation()); 15205 assert(FunctionRef && "Can't refer to __invoke function?"); 15206 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 15207 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 15208 Conv->getLocation())); 15209 Conv->markUsed(Context); 15210 Conv->setReferenced(); 15211 15212 if (ASTMutationListener *L = getASTMutationListener()) { 15213 L->CompletedImplicitDefinition(Conv); 15214 L->CompletedImplicitDefinition(Invoker); 15215 } 15216 } 15217 15218 15219 15220 void Sema::DefineImplicitLambdaToBlockPointerConversion( 15221 SourceLocation CurrentLocation, 15222 CXXConversionDecl *Conv) 15223 { 15224 assert(!Conv->getParent()->isGenericLambda()); 15225 15226 SynthesizedFunctionScope Scope(*this, Conv); 15227 15228 // Copy-initialize the lambda object as needed to capture it. 15229 Expr *This = ActOnCXXThis(CurrentLocation).get(); 15230 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 15231 15232 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 15233 Conv->getLocation(), 15234 Conv, DerefThis); 15235 15236 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 15237 // behavior. Note that only the general conversion function does this 15238 // (since it's unusable otherwise); in the case where we inline the 15239 // block literal, it has block literal lifetime semantics. 15240 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 15241 BuildBlock = ImplicitCastExpr::Create( 15242 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject, 15243 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride()); 15244 15245 if (BuildBlock.isInvalid()) { 15246 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15247 Conv->setInvalidDecl(); 15248 return; 15249 } 15250 15251 // Create the return statement that returns the block from the conversion 15252 // function. 15253 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 15254 if (Return.isInvalid()) { 15255 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15256 Conv->setInvalidDecl(); 15257 return; 15258 } 15259 15260 // Set the body of the conversion function. 15261 Stmt *ReturnS = Return.get(); 15262 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 15263 Conv->getLocation())); 15264 Conv->markUsed(Context); 15265 15266 // We're done; notify the mutation listener, if any. 15267 if (ASTMutationListener *L = getASTMutationListener()) { 15268 L->CompletedImplicitDefinition(Conv); 15269 } 15270 } 15271 15272 /// Determine whether the given list arguments contains exactly one 15273 /// "real" (non-default) argument. 15274 static bool hasOneRealArgument(MultiExprArg Args) { 15275 switch (Args.size()) { 15276 case 0: 15277 return false; 15278 15279 default: 15280 if (!Args[1]->isDefaultArgument()) 15281 return false; 15282 15283 LLVM_FALLTHROUGH; 15284 case 1: 15285 return !Args[0]->isDefaultArgument(); 15286 } 15287 15288 return false; 15289 } 15290 15291 ExprResult 15292 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15293 NamedDecl *FoundDecl, 15294 CXXConstructorDecl *Constructor, 15295 MultiExprArg ExprArgs, 15296 bool HadMultipleCandidates, 15297 bool IsListInitialization, 15298 bool IsStdInitListInitialization, 15299 bool RequiresZeroInit, 15300 unsigned ConstructKind, 15301 SourceRange ParenRange) { 15302 bool Elidable = false; 15303 15304 // C++0x [class.copy]p34: 15305 // When certain criteria are met, an implementation is allowed to 15306 // omit the copy/move construction of a class object, even if the 15307 // copy/move constructor and/or destructor for the object have 15308 // side effects. [...] 15309 // - when a temporary class object that has not been bound to a 15310 // reference (12.2) would be copied/moved to a class object 15311 // with the same cv-unqualified type, the copy/move operation 15312 // can be omitted by constructing the temporary object 15313 // directly into the target of the omitted copy/move 15314 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 15315 // FIXME: Converting constructors should also be accepted. 15316 // But to fix this, the logic that digs down into a CXXConstructExpr 15317 // to find the source object needs to handle it. 15318 // Right now it assumes the source object is passed directly as the 15319 // first argument. 15320 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 15321 Expr *SubExpr = ExprArgs[0]; 15322 // FIXME: Per above, this is also incorrect if we want to accept 15323 // converting constructors, as isTemporaryObject will 15324 // reject temporaries with different type from the 15325 // CXXRecord itself. 15326 Elidable = SubExpr->isTemporaryObject( 15327 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 15328 } 15329 15330 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 15331 FoundDecl, Constructor, 15332 Elidable, ExprArgs, HadMultipleCandidates, 15333 IsListInitialization, 15334 IsStdInitListInitialization, RequiresZeroInit, 15335 ConstructKind, ParenRange); 15336 } 15337 15338 ExprResult 15339 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15340 NamedDecl *FoundDecl, 15341 CXXConstructorDecl *Constructor, 15342 bool Elidable, 15343 MultiExprArg ExprArgs, 15344 bool HadMultipleCandidates, 15345 bool IsListInitialization, 15346 bool IsStdInitListInitialization, 15347 bool RequiresZeroInit, 15348 unsigned ConstructKind, 15349 SourceRange ParenRange) { 15350 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 15351 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 15352 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 15353 return ExprError(); 15354 } 15355 15356 return BuildCXXConstructExpr( 15357 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 15358 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 15359 RequiresZeroInit, ConstructKind, ParenRange); 15360 } 15361 15362 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 15363 /// including handling of its default argument expressions. 15364 ExprResult 15365 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15366 CXXConstructorDecl *Constructor, 15367 bool Elidable, 15368 MultiExprArg ExprArgs, 15369 bool HadMultipleCandidates, 15370 bool IsListInitialization, 15371 bool IsStdInitListInitialization, 15372 bool RequiresZeroInit, 15373 unsigned ConstructKind, 15374 SourceRange ParenRange) { 15375 assert(declaresSameEntity( 15376 Constructor->getParent(), 15377 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 15378 "given constructor for wrong type"); 15379 MarkFunctionReferenced(ConstructLoc, Constructor); 15380 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 15381 return ExprError(); 15382 if (getLangOpts().SYCLIsDevice && 15383 !checkSYCLDeviceFunction(ConstructLoc, Constructor)) 15384 return ExprError(); 15385 15386 return CheckForImmediateInvocation( 15387 CXXConstructExpr::Create( 15388 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 15389 HadMultipleCandidates, IsListInitialization, 15390 IsStdInitListInitialization, RequiresZeroInit, 15391 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 15392 ParenRange), 15393 Constructor); 15394 } 15395 15396 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 15397 assert(Field->hasInClassInitializer()); 15398 15399 // If we already have the in-class initializer nothing needs to be done. 15400 if (Field->getInClassInitializer()) 15401 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15402 15403 // If we might have already tried and failed to instantiate, don't try again. 15404 if (Field->isInvalidDecl()) 15405 return ExprError(); 15406 15407 // Maybe we haven't instantiated the in-class initializer. Go check the 15408 // pattern FieldDecl to see if it has one. 15409 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 15410 15411 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 15412 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 15413 DeclContext::lookup_result Lookup = 15414 ClassPattern->lookup(Field->getDeclName()); 15415 15416 FieldDecl *Pattern = nullptr; 15417 for (auto L : Lookup) { 15418 if (isa<FieldDecl>(L)) { 15419 Pattern = cast<FieldDecl>(L); 15420 break; 15421 } 15422 } 15423 assert(Pattern && "We must have set the Pattern!"); 15424 15425 if (!Pattern->hasInClassInitializer() || 15426 InstantiateInClassInitializer(Loc, Field, Pattern, 15427 getTemplateInstantiationArgs(Field))) { 15428 // Don't diagnose this again. 15429 Field->setInvalidDecl(); 15430 return ExprError(); 15431 } 15432 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15433 } 15434 15435 // DR1351: 15436 // If the brace-or-equal-initializer of a non-static data member 15437 // invokes a defaulted default constructor of its class or of an 15438 // enclosing class in a potentially evaluated subexpression, the 15439 // program is ill-formed. 15440 // 15441 // This resolution is unworkable: the exception specification of the 15442 // default constructor can be needed in an unevaluated context, in 15443 // particular, in the operand of a noexcept-expression, and we can be 15444 // unable to compute an exception specification for an enclosed class. 15445 // 15446 // Any attempt to resolve the exception specification of a defaulted default 15447 // constructor before the initializer is lexically complete will ultimately 15448 // come here at which point we can diagnose it. 15449 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 15450 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed) 15451 << OutermostClass << Field; 15452 Diag(Field->getEndLoc(), 15453 diag::note_default_member_initializer_not_yet_parsed); 15454 // Recover by marking the field invalid, unless we're in a SFINAE context. 15455 if (!isSFINAEContext()) 15456 Field->setInvalidDecl(); 15457 return ExprError(); 15458 } 15459 15460 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 15461 if (VD->isInvalidDecl()) return; 15462 // If initializing the variable failed, don't also diagnose problems with 15463 // the destructor, they're likely related. 15464 if (VD->getInit() && VD->getInit()->containsErrors()) 15465 return; 15466 15467 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 15468 if (ClassDecl->isInvalidDecl()) return; 15469 if (ClassDecl->hasIrrelevantDestructor()) return; 15470 if (ClassDecl->isDependentContext()) return; 15471 15472 if (VD->isNoDestroy(getASTContext())) 15473 return; 15474 15475 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15476 15477 // If this is an array, we'll require the destructor during initialization, so 15478 // we can skip over this. We still want to emit exit-time destructor warnings 15479 // though. 15480 if (!VD->getType()->isArrayType()) { 15481 MarkFunctionReferenced(VD->getLocation(), Destructor); 15482 CheckDestructorAccess(VD->getLocation(), Destructor, 15483 PDiag(diag::err_access_dtor_var) 15484 << VD->getDeclName() << VD->getType()); 15485 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 15486 } 15487 15488 if (Destructor->isTrivial()) return; 15489 15490 // If the destructor is constexpr, check whether the variable has constant 15491 // destruction now. 15492 if (Destructor->isConstexpr()) { 15493 bool HasConstantInit = false; 15494 if (VD->getInit() && !VD->getInit()->isValueDependent()) 15495 HasConstantInit = VD->evaluateValue(); 15496 SmallVector<PartialDiagnosticAt, 8> Notes; 15497 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && 15498 HasConstantInit) { 15499 Diag(VD->getLocation(), 15500 diag::err_constexpr_var_requires_const_destruction) << VD; 15501 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 15502 Diag(Notes[I].first, Notes[I].second); 15503 } 15504 } 15505 15506 if (!VD->hasGlobalStorage()) return; 15507 15508 // Emit warning for non-trivial dtor in global scope (a real global, 15509 // class-static, function-static). 15510 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 15511 15512 // TODO: this should be re-enabled for static locals by !CXAAtExit 15513 if (!VD->isStaticLocal()) 15514 Diag(VD->getLocation(), diag::warn_global_destructor); 15515 } 15516 15517 /// Given a constructor and the set of arguments provided for the 15518 /// constructor, convert the arguments and add any required default arguments 15519 /// to form a proper call to this constructor. 15520 /// 15521 /// \returns true if an error occurred, false otherwise. 15522 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 15523 QualType DeclInitType, MultiExprArg ArgsPtr, 15524 SourceLocation Loc, 15525 SmallVectorImpl<Expr *> &ConvertedArgs, 15526 bool AllowExplicit, 15527 bool IsListInitialization) { 15528 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 15529 unsigned NumArgs = ArgsPtr.size(); 15530 Expr **Args = ArgsPtr.data(); 15531 15532 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); 15533 unsigned NumParams = Proto->getNumParams(); 15534 15535 // If too few arguments are available, we'll fill in the rest with defaults. 15536 if (NumArgs < NumParams) 15537 ConvertedArgs.reserve(NumParams); 15538 else 15539 ConvertedArgs.reserve(NumArgs); 15540 15541 VariadicCallType CallType = 15542 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 15543 SmallVector<Expr *, 8> AllArgs; 15544 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 15545 Proto, 0, 15546 llvm::makeArrayRef(Args, NumArgs), 15547 AllArgs, 15548 CallType, AllowExplicit, 15549 IsListInitialization); 15550 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 15551 15552 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 15553 15554 CheckConstructorCall(Constructor, DeclInitType, 15555 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 15556 Proto, Loc); 15557 15558 return Invalid; 15559 } 15560 15561 static inline bool 15562 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 15563 const FunctionDecl *FnDecl) { 15564 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 15565 if (isa<NamespaceDecl>(DC)) { 15566 return SemaRef.Diag(FnDecl->getLocation(), 15567 diag::err_operator_new_delete_declared_in_namespace) 15568 << FnDecl->getDeclName(); 15569 } 15570 15571 if (isa<TranslationUnitDecl>(DC) && 15572 FnDecl->getStorageClass() == SC_Static) { 15573 return SemaRef.Diag(FnDecl->getLocation(), 15574 diag::err_operator_new_delete_declared_static) 15575 << FnDecl->getDeclName(); 15576 } 15577 15578 return false; 15579 } 15580 15581 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, 15582 const PointerType *PtrTy) { 15583 auto &Ctx = SemaRef.Context; 15584 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers(); 15585 PtrQuals.removeAddressSpace(); 15586 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType( 15587 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals))); 15588 } 15589 15590 static inline bool 15591 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 15592 CanQualType ExpectedResultType, 15593 CanQualType ExpectedFirstParamType, 15594 unsigned DependentParamTypeDiag, 15595 unsigned InvalidParamTypeDiag) { 15596 QualType ResultType = 15597 FnDecl->getType()->castAs<FunctionType>()->getReturnType(); 15598 15599 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15600 // The operator is valid on any address space for OpenCL. 15601 // Drop address space from actual and expected result types. 15602 if (const auto *PtrTy = ResultType->getAs<PointerType>()) 15603 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15604 15605 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>()) 15606 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15607 } 15608 15609 // Check that the result type is what we expect. 15610 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) { 15611 // Reject even if the type is dependent; an operator delete function is 15612 // required to have a non-dependent result type. 15613 return SemaRef.Diag( 15614 FnDecl->getLocation(), 15615 ResultType->isDependentType() 15616 ? diag::err_operator_new_delete_dependent_result_type 15617 : diag::err_operator_new_delete_invalid_result_type) 15618 << FnDecl->getDeclName() << ExpectedResultType; 15619 } 15620 15621 // A function template must have at least 2 parameters. 15622 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 15623 return SemaRef.Diag(FnDecl->getLocation(), 15624 diag::err_operator_new_delete_template_too_few_parameters) 15625 << FnDecl->getDeclName(); 15626 15627 // The function decl must have at least 1 parameter. 15628 if (FnDecl->getNumParams() == 0) 15629 return SemaRef.Diag(FnDecl->getLocation(), 15630 diag::err_operator_new_delete_too_few_parameters) 15631 << FnDecl->getDeclName(); 15632 15633 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 15634 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15635 // The operator is valid on any address space for OpenCL. 15636 // Drop address space from actual and expected first parameter types. 15637 if (const auto *PtrTy = 15638 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) 15639 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15640 15641 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>()) 15642 ExpectedFirstParamType = 15643 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15644 } 15645 15646 // Check that the first parameter type is what we expect. 15647 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 15648 ExpectedFirstParamType) { 15649 // The first parameter type is not allowed to be dependent. As a tentative 15650 // DR resolution, we allow a dependent parameter type if it is the right 15651 // type anyway, to allow destroying operator delete in class templates. 15652 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType() 15653 ? DependentParamTypeDiag 15654 : InvalidParamTypeDiag) 15655 << FnDecl->getDeclName() << ExpectedFirstParamType; 15656 } 15657 15658 return false; 15659 } 15660 15661 static bool 15662 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 15663 // C++ [basic.stc.dynamic.allocation]p1: 15664 // A program is ill-formed if an allocation function is declared in a 15665 // namespace scope other than global scope or declared static in global 15666 // scope. 15667 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15668 return true; 15669 15670 CanQualType SizeTy = 15671 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 15672 15673 // C++ [basic.stc.dynamic.allocation]p1: 15674 // The return type shall be void*. The first parameter shall have type 15675 // std::size_t. 15676 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 15677 SizeTy, 15678 diag::err_operator_new_dependent_param_type, 15679 diag::err_operator_new_param_type)) 15680 return true; 15681 15682 // C++ [basic.stc.dynamic.allocation]p1: 15683 // The first parameter shall not have an associated default argument. 15684 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 15685 return SemaRef.Diag(FnDecl->getLocation(), 15686 diag::err_operator_new_default_arg) 15687 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 15688 15689 return false; 15690 } 15691 15692 static bool 15693 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 15694 // C++ [basic.stc.dynamic.deallocation]p1: 15695 // A program is ill-formed if deallocation functions are declared in a 15696 // namespace scope other than global scope or declared static in global 15697 // scope. 15698 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15699 return true; 15700 15701 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 15702 15703 // C++ P0722: 15704 // Within a class C, the first parameter of a destroying operator delete 15705 // shall be of type C *. The first parameter of any other deallocation 15706 // function shall be of type void *. 15707 CanQualType ExpectedFirstParamType = 15708 MD && MD->isDestroyingOperatorDelete() 15709 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 15710 SemaRef.Context.getRecordType(MD->getParent()))) 15711 : SemaRef.Context.VoidPtrTy; 15712 15713 // C++ [basic.stc.dynamic.deallocation]p2: 15714 // Each deallocation function shall return void 15715 if (CheckOperatorNewDeleteTypes( 15716 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 15717 diag::err_operator_delete_dependent_param_type, 15718 diag::err_operator_delete_param_type)) 15719 return true; 15720 15721 // C++ P0722: 15722 // A destroying operator delete shall be a usual deallocation function. 15723 if (MD && !MD->getParent()->isDependentContext() && 15724 MD->isDestroyingOperatorDelete() && 15725 !SemaRef.isUsualDeallocationFunction(MD)) { 15726 SemaRef.Diag(MD->getLocation(), 15727 diag::err_destroying_operator_delete_not_usual); 15728 return true; 15729 } 15730 15731 return false; 15732 } 15733 15734 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 15735 /// of this overloaded operator is well-formed. If so, returns false; 15736 /// otherwise, emits appropriate diagnostics and returns true. 15737 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 15738 assert(FnDecl && FnDecl->isOverloadedOperator() && 15739 "Expected an overloaded operator declaration"); 15740 15741 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 15742 15743 // C++ [over.oper]p5: 15744 // The allocation and deallocation functions, operator new, 15745 // operator new[], operator delete and operator delete[], are 15746 // described completely in 3.7.3. The attributes and restrictions 15747 // found in the rest of this subclause do not apply to them unless 15748 // explicitly stated in 3.7.3. 15749 if (Op == OO_Delete || Op == OO_Array_Delete) 15750 return CheckOperatorDeleteDeclaration(*this, FnDecl); 15751 15752 if (Op == OO_New || Op == OO_Array_New) 15753 return CheckOperatorNewDeclaration(*this, FnDecl); 15754 15755 // C++ [over.oper]p6: 15756 // An operator function shall either be a non-static member 15757 // function or be a non-member function and have at least one 15758 // parameter whose type is a class, a reference to a class, an 15759 // enumeration, or a reference to an enumeration. 15760 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 15761 if (MethodDecl->isStatic()) 15762 return Diag(FnDecl->getLocation(), 15763 diag::err_operator_overload_static) << FnDecl->getDeclName(); 15764 } else { 15765 bool ClassOrEnumParam = false; 15766 for (auto Param : FnDecl->parameters()) { 15767 QualType ParamType = Param->getType().getNonReferenceType(); 15768 if (ParamType->isDependentType() || ParamType->isRecordType() || 15769 ParamType->isEnumeralType()) { 15770 ClassOrEnumParam = true; 15771 break; 15772 } 15773 } 15774 15775 if (!ClassOrEnumParam) 15776 return Diag(FnDecl->getLocation(), 15777 diag::err_operator_overload_needs_class_or_enum) 15778 << FnDecl->getDeclName(); 15779 } 15780 15781 // C++ [over.oper]p8: 15782 // An operator function cannot have default arguments (8.3.6), 15783 // except where explicitly stated below. 15784 // 15785 // Only the function-call operator allows default arguments 15786 // (C++ [over.call]p1). 15787 if (Op != OO_Call) { 15788 for (auto Param : FnDecl->parameters()) { 15789 if (Param->hasDefaultArg()) 15790 return Diag(Param->getLocation(), 15791 diag::err_operator_overload_default_arg) 15792 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 15793 } 15794 } 15795 15796 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 15797 { false, false, false } 15798 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 15799 , { Unary, Binary, MemberOnly } 15800 #include "clang/Basic/OperatorKinds.def" 15801 }; 15802 15803 bool CanBeUnaryOperator = OperatorUses[Op][0]; 15804 bool CanBeBinaryOperator = OperatorUses[Op][1]; 15805 bool MustBeMemberOperator = OperatorUses[Op][2]; 15806 15807 // C++ [over.oper]p8: 15808 // [...] Operator functions cannot have more or fewer parameters 15809 // than the number required for the corresponding operator, as 15810 // described in the rest of this subclause. 15811 unsigned NumParams = FnDecl->getNumParams() 15812 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 15813 if (Op != OO_Call && 15814 ((NumParams == 1 && !CanBeUnaryOperator) || 15815 (NumParams == 2 && !CanBeBinaryOperator) || 15816 (NumParams < 1) || (NumParams > 2))) { 15817 // We have the wrong number of parameters. 15818 unsigned ErrorKind; 15819 if (CanBeUnaryOperator && CanBeBinaryOperator) { 15820 ErrorKind = 2; // 2 -> unary or binary. 15821 } else if (CanBeUnaryOperator) { 15822 ErrorKind = 0; // 0 -> unary 15823 } else { 15824 assert(CanBeBinaryOperator && 15825 "All non-call overloaded operators are unary or binary!"); 15826 ErrorKind = 1; // 1 -> binary 15827 } 15828 15829 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 15830 << FnDecl->getDeclName() << NumParams << ErrorKind; 15831 } 15832 15833 // Overloaded operators other than operator() cannot be variadic. 15834 if (Op != OO_Call && 15835 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { 15836 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 15837 << FnDecl->getDeclName(); 15838 } 15839 15840 // Some operators must be non-static member functions. 15841 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 15842 return Diag(FnDecl->getLocation(), 15843 diag::err_operator_overload_must_be_member) 15844 << FnDecl->getDeclName(); 15845 } 15846 15847 // C++ [over.inc]p1: 15848 // The user-defined function called operator++ implements the 15849 // prefix and postfix ++ operator. If this function is a member 15850 // function with no parameters, or a non-member function with one 15851 // parameter of class or enumeration type, it defines the prefix 15852 // increment operator ++ for objects of that type. If the function 15853 // is a member function with one parameter (which shall be of type 15854 // int) or a non-member function with two parameters (the second 15855 // of which shall be of type int), it defines the postfix 15856 // increment operator ++ for objects of that type. 15857 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 15858 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 15859 QualType ParamType = LastParam->getType(); 15860 15861 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 15862 !ParamType->isDependentType()) 15863 return Diag(LastParam->getLocation(), 15864 diag::err_operator_overload_post_incdec_must_be_int) 15865 << LastParam->getType() << (Op == OO_MinusMinus); 15866 } 15867 15868 return false; 15869 } 15870 15871 static bool 15872 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 15873 FunctionTemplateDecl *TpDecl) { 15874 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 15875 15876 // Must have one or two template parameters. 15877 if (TemplateParams->size() == 1) { 15878 NonTypeTemplateParmDecl *PmDecl = 15879 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 15880 15881 // The template parameter must be a char parameter pack. 15882 if (PmDecl && PmDecl->isTemplateParameterPack() && 15883 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 15884 return false; 15885 15886 // C++20 [over.literal]p5: 15887 // A string literal operator template is a literal operator template 15888 // whose template-parameter-list comprises a single non-type 15889 // template-parameter of class type. 15890 // 15891 // As a DR resolution, we also allow placeholders for deduced class 15892 // template specializations. 15893 if (SemaRef.getLangOpts().CPlusPlus20 && 15894 !PmDecl->isTemplateParameterPack() && 15895 (PmDecl->getType()->isRecordType() || 15896 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>())) 15897 return false; 15898 } else if (TemplateParams->size() == 2) { 15899 TemplateTypeParmDecl *PmType = 15900 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 15901 NonTypeTemplateParmDecl *PmArgs = 15902 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 15903 15904 // The second template parameter must be a parameter pack with the 15905 // first template parameter as its type. 15906 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 15907 PmArgs->isTemplateParameterPack()) { 15908 const TemplateTypeParmType *TArgs = 15909 PmArgs->getType()->getAs<TemplateTypeParmType>(); 15910 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 15911 TArgs->getIndex() == PmType->getIndex()) { 15912 if (!SemaRef.inTemplateInstantiation()) 15913 SemaRef.Diag(TpDecl->getLocation(), 15914 diag::ext_string_literal_operator_template); 15915 return false; 15916 } 15917 } 15918 } 15919 15920 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 15921 diag::err_literal_operator_template) 15922 << TpDecl->getTemplateParameters()->getSourceRange(); 15923 return true; 15924 } 15925 15926 /// CheckLiteralOperatorDeclaration - Check whether the declaration 15927 /// of this literal operator function is well-formed. If so, returns 15928 /// false; otherwise, emits appropriate diagnostics and returns true. 15929 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 15930 if (isa<CXXMethodDecl>(FnDecl)) { 15931 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 15932 << FnDecl->getDeclName(); 15933 return true; 15934 } 15935 15936 if (FnDecl->isExternC()) { 15937 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 15938 if (const LinkageSpecDecl *LSD = 15939 FnDecl->getDeclContext()->getExternCContext()) 15940 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 15941 return true; 15942 } 15943 15944 // This might be the definition of a literal operator template. 15945 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 15946 15947 // This might be a specialization of a literal operator template. 15948 if (!TpDecl) 15949 TpDecl = FnDecl->getPrimaryTemplate(); 15950 15951 // template <char...> type operator "" name() and 15952 // template <class T, T...> type operator "" name() are the only valid 15953 // template signatures, and the only valid signatures with no parameters. 15954 // 15955 // C++20 also allows template <SomeClass T> type operator "" name(). 15956 if (TpDecl) { 15957 if (FnDecl->param_size() != 0) { 15958 Diag(FnDecl->getLocation(), 15959 diag::err_literal_operator_template_with_params); 15960 return true; 15961 } 15962 15963 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 15964 return true; 15965 15966 } else if (FnDecl->param_size() == 1) { 15967 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 15968 15969 QualType ParamType = Param->getType().getUnqualifiedType(); 15970 15971 // Only unsigned long long int, long double, any character type, and const 15972 // char * are allowed as the only parameters. 15973 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 15974 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 15975 Context.hasSameType(ParamType, Context.CharTy) || 15976 Context.hasSameType(ParamType, Context.WideCharTy) || 15977 Context.hasSameType(ParamType, Context.Char8Ty) || 15978 Context.hasSameType(ParamType, Context.Char16Ty) || 15979 Context.hasSameType(ParamType, Context.Char32Ty)) { 15980 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 15981 QualType InnerType = Ptr->getPointeeType(); 15982 15983 // Pointer parameter must be a const char *. 15984 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 15985 Context.CharTy) && 15986 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 15987 Diag(Param->getSourceRange().getBegin(), 15988 diag::err_literal_operator_param) 15989 << ParamType << "'const char *'" << Param->getSourceRange(); 15990 return true; 15991 } 15992 15993 } else if (ParamType->isRealFloatingType()) { 15994 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15995 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 15996 return true; 15997 15998 } else if (ParamType->isIntegerType()) { 15999 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 16000 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 16001 return true; 16002 16003 } else { 16004 Diag(Param->getSourceRange().getBegin(), 16005 diag::err_literal_operator_invalid_param) 16006 << ParamType << Param->getSourceRange(); 16007 return true; 16008 } 16009 16010 } else if (FnDecl->param_size() == 2) { 16011 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 16012 16013 // First, verify that the first parameter is correct. 16014 16015 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 16016 16017 // Two parameter function must have a pointer to const as a 16018 // first parameter; let's strip those qualifiers. 16019 const PointerType *PT = FirstParamType->getAs<PointerType>(); 16020 16021 if (!PT) { 16022 Diag((*Param)->getSourceRange().getBegin(), 16023 diag::err_literal_operator_param) 16024 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16025 return true; 16026 } 16027 16028 QualType PointeeType = PT->getPointeeType(); 16029 // First parameter must be const 16030 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 16031 Diag((*Param)->getSourceRange().getBegin(), 16032 diag::err_literal_operator_param) 16033 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16034 return true; 16035 } 16036 16037 QualType InnerType = PointeeType.getUnqualifiedType(); 16038 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 16039 // const char32_t* are allowed as the first parameter to a two-parameter 16040 // function 16041 if (!(Context.hasSameType(InnerType, Context.CharTy) || 16042 Context.hasSameType(InnerType, Context.WideCharTy) || 16043 Context.hasSameType(InnerType, Context.Char8Ty) || 16044 Context.hasSameType(InnerType, Context.Char16Ty) || 16045 Context.hasSameType(InnerType, Context.Char32Ty))) { 16046 Diag((*Param)->getSourceRange().getBegin(), 16047 diag::err_literal_operator_param) 16048 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16049 return true; 16050 } 16051 16052 // Move on to the second and final parameter. 16053 ++Param; 16054 16055 // The second parameter must be a std::size_t. 16056 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 16057 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 16058 Diag((*Param)->getSourceRange().getBegin(), 16059 diag::err_literal_operator_param) 16060 << SecondParamType << Context.getSizeType() 16061 << (*Param)->getSourceRange(); 16062 return true; 16063 } 16064 } else { 16065 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 16066 return true; 16067 } 16068 16069 // Parameters are good. 16070 16071 // A parameter-declaration-clause containing a default argument is not 16072 // equivalent to any of the permitted forms. 16073 for (auto Param : FnDecl->parameters()) { 16074 if (Param->hasDefaultArg()) { 16075 Diag(Param->getDefaultArgRange().getBegin(), 16076 diag::err_literal_operator_default_argument) 16077 << Param->getDefaultArgRange(); 16078 break; 16079 } 16080 } 16081 16082 StringRef LiteralName 16083 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 16084 if (LiteralName[0] != '_' && 16085 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 16086 // C++11 [usrlit.suffix]p1: 16087 // Literal suffix identifiers that do not start with an underscore 16088 // are reserved for future standardization. 16089 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 16090 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 16091 } 16092 16093 return false; 16094 } 16095 16096 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 16097 /// linkage specification, including the language and (if present) 16098 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 16099 /// language string literal. LBraceLoc, if valid, provides the location of 16100 /// the '{' brace. Otherwise, this linkage specification does not 16101 /// have any braces. 16102 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 16103 Expr *LangStr, 16104 SourceLocation LBraceLoc) { 16105 StringLiteral *Lit = cast<StringLiteral>(LangStr); 16106 if (!Lit->isAscii()) { 16107 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 16108 << LangStr->getSourceRange(); 16109 return nullptr; 16110 } 16111 16112 StringRef Lang = Lit->getString(); 16113 LinkageSpecDecl::LanguageIDs Language; 16114 if (Lang == "C") 16115 Language = LinkageSpecDecl::lang_c; 16116 else if (Lang == "C++") 16117 Language = LinkageSpecDecl::lang_cxx; 16118 else { 16119 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 16120 << LangStr->getSourceRange(); 16121 return nullptr; 16122 } 16123 16124 // FIXME: Add all the various semantics of linkage specifications 16125 16126 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 16127 LangStr->getExprLoc(), Language, 16128 LBraceLoc.isValid()); 16129 CurContext->addDecl(D); 16130 PushDeclContext(S, D); 16131 return D; 16132 } 16133 16134 /// ActOnFinishLinkageSpecification - Complete the definition of 16135 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 16136 /// valid, it's the position of the closing '}' brace in a linkage 16137 /// specification that uses braces. 16138 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 16139 Decl *LinkageSpec, 16140 SourceLocation RBraceLoc) { 16141 if (RBraceLoc.isValid()) { 16142 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 16143 LSDecl->setRBraceLoc(RBraceLoc); 16144 } 16145 PopDeclContext(); 16146 return LinkageSpec; 16147 } 16148 16149 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 16150 const ParsedAttributesView &AttrList, 16151 SourceLocation SemiLoc) { 16152 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 16153 // Attribute declarations appertain to empty declaration so we handle 16154 // them here. 16155 ProcessDeclAttributeList(S, ED, AttrList); 16156 16157 CurContext->addDecl(ED); 16158 return ED; 16159 } 16160 16161 /// Perform semantic analysis for the variable declaration that 16162 /// occurs within a C++ catch clause, returning the newly-created 16163 /// variable. 16164 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 16165 TypeSourceInfo *TInfo, 16166 SourceLocation StartLoc, 16167 SourceLocation Loc, 16168 IdentifierInfo *Name) { 16169 bool Invalid = false; 16170 QualType ExDeclType = TInfo->getType(); 16171 16172 // Arrays and functions decay. 16173 if (ExDeclType->isArrayType()) 16174 ExDeclType = Context.getArrayDecayedType(ExDeclType); 16175 else if (ExDeclType->isFunctionType()) 16176 ExDeclType = Context.getPointerType(ExDeclType); 16177 16178 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 16179 // The exception-declaration shall not denote a pointer or reference to an 16180 // incomplete type, other than [cv] void*. 16181 // N2844 forbids rvalue references. 16182 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 16183 Diag(Loc, diag::err_catch_rvalue_ref); 16184 Invalid = true; 16185 } 16186 16187 if (ExDeclType->isVariablyModifiedType()) { 16188 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 16189 Invalid = true; 16190 } 16191 16192 QualType BaseType = ExDeclType; 16193 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 16194 unsigned DK = diag::err_catch_incomplete; 16195 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 16196 BaseType = Ptr->getPointeeType(); 16197 Mode = 1; 16198 DK = diag::err_catch_incomplete_ptr; 16199 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 16200 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 16201 BaseType = Ref->getPointeeType(); 16202 Mode = 2; 16203 DK = diag::err_catch_incomplete_ref; 16204 } 16205 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 16206 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 16207 Invalid = true; 16208 16209 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) { 16210 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType; 16211 Invalid = true; 16212 } 16213 16214 if (!Invalid && !ExDeclType->isDependentType() && 16215 RequireNonAbstractType(Loc, ExDeclType, 16216 diag::err_abstract_type_in_decl, 16217 AbstractVariableType)) 16218 Invalid = true; 16219 16220 // Only the non-fragile NeXT runtime currently supports C++ catches 16221 // of ObjC types, and no runtime supports catching ObjC types by value. 16222 if (!Invalid && getLangOpts().ObjC) { 16223 QualType T = ExDeclType; 16224 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 16225 T = RT->getPointeeType(); 16226 16227 if (T->isObjCObjectType()) { 16228 Diag(Loc, diag::err_objc_object_catch); 16229 Invalid = true; 16230 } else if (T->isObjCObjectPointerType()) { 16231 // FIXME: should this be a test for macosx-fragile specifically? 16232 if (getLangOpts().ObjCRuntime.isFragile()) 16233 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 16234 } 16235 } 16236 16237 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 16238 ExDeclType, TInfo, SC_None); 16239 ExDecl->setExceptionVariable(true); 16240 16241 // In ARC, infer 'retaining' for variables of retainable type. 16242 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 16243 Invalid = true; 16244 16245 if (!Invalid && !ExDeclType->isDependentType()) { 16246 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 16247 // Insulate this from anything else we might currently be parsing. 16248 EnterExpressionEvaluationContext scope( 16249 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 16250 16251 // C++ [except.handle]p16: 16252 // The object declared in an exception-declaration or, if the 16253 // exception-declaration does not specify a name, a temporary (12.2) is 16254 // copy-initialized (8.5) from the exception object. [...] 16255 // The object is destroyed when the handler exits, after the destruction 16256 // of any automatic objects initialized within the handler. 16257 // 16258 // We just pretend to initialize the object with itself, then make sure 16259 // it can be destroyed later. 16260 QualType initType = Context.getExceptionObjectType(ExDeclType); 16261 16262 InitializedEntity entity = 16263 InitializedEntity::InitializeVariable(ExDecl); 16264 InitializationKind initKind = 16265 InitializationKind::CreateCopy(Loc, SourceLocation()); 16266 16267 Expr *opaqueValue = 16268 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 16269 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 16270 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 16271 if (result.isInvalid()) 16272 Invalid = true; 16273 else { 16274 // If the constructor used was non-trivial, set this as the 16275 // "initializer". 16276 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 16277 if (!construct->getConstructor()->isTrivial()) { 16278 Expr *init = MaybeCreateExprWithCleanups(construct); 16279 ExDecl->setInit(init); 16280 } 16281 16282 // And make sure it's destructable. 16283 FinalizeVarWithDestructor(ExDecl, recordType); 16284 } 16285 } 16286 } 16287 16288 if (Invalid) 16289 ExDecl->setInvalidDecl(); 16290 16291 return ExDecl; 16292 } 16293 16294 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 16295 /// handler. 16296 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 16297 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16298 bool Invalid = D.isInvalidType(); 16299 16300 // Check for unexpanded parameter packs. 16301 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16302 UPPC_ExceptionType)) { 16303 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 16304 D.getIdentifierLoc()); 16305 Invalid = true; 16306 } 16307 16308 IdentifierInfo *II = D.getIdentifier(); 16309 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 16310 LookupOrdinaryName, 16311 ForVisibleRedeclaration)) { 16312 // The scope should be freshly made just for us. There is just no way 16313 // it contains any previous declaration, except for function parameters in 16314 // a function-try-block's catch statement. 16315 assert(!S->isDeclScope(PrevDecl)); 16316 if (isDeclInScope(PrevDecl, CurContext, S)) { 16317 Diag(D.getIdentifierLoc(), diag::err_redefinition) 16318 << D.getIdentifier(); 16319 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 16320 Invalid = true; 16321 } else if (PrevDecl->isTemplateParameter()) 16322 // Maybe we will complain about the shadowed template parameter. 16323 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16324 } 16325 16326 if (D.getCXXScopeSpec().isSet() && !Invalid) { 16327 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 16328 << D.getCXXScopeSpec().getRange(); 16329 Invalid = true; 16330 } 16331 16332 VarDecl *ExDecl = BuildExceptionDeclaration( 16333 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 16334 if (Invalid) 16335 ExDecl->setInvalidDecl(); 16336 16337 // Add the exception declaration into this scope. 16338 if (II) 16339 PushOnScopeChains(ExDecl, S); 16340 else 16341 CurContext->addDecl(ExDecl); 16342 16343 ProcessDeclAttributes(S, ExDecl, D); 16344 return ExDecl; 16345 } 16346 16347 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16348 Expr *AssertExpr, 16349 Expr *AssertMessageExpr, 16350 SourceLocation RParenLoc) { 16351 StringLiteral *AssertMessage = 16352 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 16353 16354 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 16355 return nullptr; 16356 16357 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 16358 AssertMessage, RParenLoc, false); 16359 } 16360 16361 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16362 Expr *AssertExpr, 16363 StringLiteral *AssertMessage, 16364 SourceLocation RParenLoc, 16365 bool Failed) { 16366 assert(AssertExpr != nullptr && "Expected non-null condition"); 16367 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 16368 !Failed) { 16369 // In a static_assert-declaration, the constant-expression shall be a 16370 // constant expression that can be contextually converted to bool. 16371 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 16372 if (Converted.isInvalid()) 16373 Failed = true; 16374 16375 ExprResult FullAssertExpr = 16376 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 16377 /*DiscardedValue*/ false, 16378 /*IsConstexpr*/ true); 16379 if (FullAssertExpr.isInvalid()) 16380 Failed = true; 16381 else 16382 AssertExpr = FullAssertExpr.get(); 16383 16384 llvm::APSInt Cond; 16385 if (!Failed && VerifyIntegerConstantExpression( 16386 AssertExpr, &Cond, 16387 diag::err_static_assert_expression_is_not_constant) 16388 .isInvalid()) 16389 Failed = true; 16390 16391 if (!Failed && !Cond) { 16392 SmallString<256> MsgBuffer; 16393 llvm::raw_svector_ostream Msg(MsgBuffer); 16394 if (AssertMessage) 16395 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 16396 16397 Expr *InnerCond = nullptr; 16398 std::string InnerCondDescription; 16399 std::tie(InnerCond, InnerCondDescription) = 16400 findFailedBooleanCondition(Converted.get()); 16401 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 16402 // Drill down into concept specialization expressions to see why they 16403 // weren't satisfied. 16404 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16405 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16406 ConstraintSatisfaction Satisfaction; 16407 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 16408 DiagnoseUnsatisfiedConstraint(Satisfaction); 16409 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 16410 && !isa<IntegerLiteral>(InnerCond)) { 16411 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 16412 << InnerCondDescription << !AssertMessage 16413 << Msg.str() << InnerCond->getSourceRange(); 16414 } else { 16415 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16416 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16417 } 16418 Failed = true; 16419 } 16420 } else { 16421 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 16422 /*DiscardedValue*/false, 16423 /*IsConstexpr*/true); 16424 if (FullAssertExpr.isInvalid()) 16425 Failed = true; 16426 else 16427 AssertExpr = FullAssertExpr.get(); 16428 } 16429 16430 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 16431 AssertExpr, AssertMessage, RParenLoc, 16432 Failed); 16433 16434 CurContext->addDecl(Decl); 16435 return Decl; 16436 } 16437 16438 /// Perform semantic analysis of the given friend type declaration. 16439 /// 16440 /// \returns A friend declaration that. 16441 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 16442 SourceLocation FriendLoc, 16443 TypeSourceInfo *TSInfo) { 16444 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 16445 16446 QualType T = TSInfo->getType(); 16447 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 16448 16449 // C++03 [class.friend]p2: 16450 // An elaborated-type-specifier shall be used in a friend declaration 16451 // for a class.* 16452 // 16453 // * The class-key of the elaborated-type-specifier is required. 16454 if (!CodeSynthesisContexts.empty()) { 16455 // Do not complain about the form of friend template types during any kind 16456 // of code synthesis. For template instantiation, we will have complained 16457 // when the template was defined. 16458 } else { 16459 if (!T->isElaboratedTypeSpecifier()) { 16460 // If we evaluated the type to a record type, suggest putting 16461 // a tag in front. 16462 if (const RecordType *RT = T->getAs<RecordType>()) { 16463 RecordDecl *RD = RT->getDecl(); 16464 16465 SmallString<16> InsertionText(" "); 16466 InsertionText += RD->getKindName(); 16467 16468 Diag(TypeRange.getBegin(), 16469 getLangOpts().CPlusPlus11 ? 16470 diag::warn_cxx98_compat_unelaborated_friend_type : 16471 diag::ext_unelaborated_friend_type) 16472 << (unsigned) RD->getTagKind() 16473 << T 16474 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 16475 InsertionText); 16476 } else { 16477 Diag(FriendLoc, 16478 getLangOpts().CPlusPlus11 ? 16479 diag::warn_cxx98_compat_nonclass_type_friend : 16480 diag::ext_nonclass_type_friend) 16481 << T 16482 << TypeRange; 16483 } 16484 } else if (T->getAs<EnumType>()) { 16485 Diag(FriendLoc, 16486 getLangOpts().CPlusPlus11 ? 16487 diag::warn_cxx98_compat_enum_friend : 16488 diag::ext_enum_friend) 16489 << T 16490 << TypeRange; 16491 } 16492 16493 // C++11 [class.friend]p3: 16494 // A friend declaration that does not declare a function shall have one 16495 // of the following forms: 16496 // friend elaborated-type-specifier ; 16497 // friend simple-type-specifier ; 16498 // friend typename-specifier ; 16499 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 16500 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 16501 } 16502 16503 // If the type specifier in a friend declaration designates a (possibly 16504 // cv-qualified) class type, that class is declared as a friend; otherwise, 16505 // the friend declaration is ignored. 16506 return FriendDecl::Create(Context, CurContext, 16507 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 16508 FriendLoc); 16509 } 16510 16511 /// Handle a friend tag declaration where the scope specifier was 16512 /// templated. 16513 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 16514 unsigned TagSpec, SourceLocation TagLoc, 16515 CXXScopeSpec &SS, IdentifierInfo *Name, 16516 SourceLocation NameLoc, 16517 const ParsedAttributesView &Attr, 16518 MultiTemplateParamsArg TempParamLists) { 16519 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16520 16521 bool IsMemberSpecialization = false; 16522 bool Invalid = false; 16523 16524 if (TemplateParameterList *TemplateParams = 16525 MatchTemplateParametersToScopeSpecifier( 16526 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 16527 IsMemberSpecialization, Invalid)) { 16528 if (TemplateParams->size() > 0) { 16529 // This is a declaration of a class template. 16530 if (Invalid) 16531 return nullptr; 16532 16533 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 16534 NameLoc, Attr, TemplateParams, AS_public, 16535 /*ModulePrivateLoc=*/SourceLocation(), 16536 FriendLoc, TempParamLists.size() - 1, 16537 TempParamLists.data()).get(); 16538 } else { 16539 // The "template<>" header is extraneous. 16540 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16541 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16542 IsMemberSpecialization = true; 16543 } 16544 } 16545 16546 if (Invalid) return nullptr; 16547 16548 bool isAllExplicitSpecializations = true; 16549 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 16550 if (TempParamLists[I]->size()) { 16551 isAllExplicitSpecializations = false; 16552 break; 16553 } 16554 } 16555 16556 // FIXME: don't ignore attributes. 16557 16558 // If it's explicit specializations all the way down, just forget 16559 // about the template header and build an appropriate non-templated 16560 // friend. TODO: for source fidelity, remember the headers. 16561 if (isAllExplicitSpecializations) { 16562 if (SS.isEmpty()) { 16563 bool Owned = false; 16564 bool IsDependent = false; 16565 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 16566 Attr, AS_public, 16567 /*ModulePrivateLoc=*/SourceLocation(), 16568 MultiTemplateParamsArg(), Owned, IsDependent, 16569 /*ScopedEnumKWLoc=*/SourceLocation(), 16570 /*ScopedEnumUsesClassTag=*/false, 16571 /*UnderlyingType=*/TypeResult(), 16572 /*IsTypeSpecifier=*/false, 16573 /*IsTemplateParamOrArg=*/false); 16574 } 16575 16576 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 16577 ElaboratedTypeKeyword Keyword 16578 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16579 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 16580 *Name, NameLoc); 16581 if (T.isNull()) 16582 return nullptr; 16583 16584 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16585 if (isa<DependentNameType>(T)) { 16586 DependentNameTypeLoc TL = 16587 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16588 TL.setElaboratedKeywordLoc(TagLoc); 16589 TL.setQualifierLoc(QualifierLoc); 16590 TL.setNameLoc(NameLoc); 16591 } else { 16592 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 16593 TL.setElaboratedKeywordLoc(TagLoc); 16594 TL.setQualifierLoc(QualifierLoc); 16595 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 16596 } 16597 16598 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16599 TSI, FriendLoc, TempParamLists); 16600 Friend->setAccess(AS_public); 16601 CurContext->addDecl(Friend); 16602 return Friend; 16603 } 16604 16605 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 16606 16607 16608 16609 // Handle the case of a templated-scope friend class. e.g. 16610 // template <class T> class A<T>::B; 16611 // FIXME: we don't support these right now. 16612 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 16613 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 16614 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16615 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 16616 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16617 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16618 TL.setElaboratedKeywordLoc(TagLoc); 16619 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 16620 TL.setNameLoc(NameLoc); 16621 16622 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16623 TSI, FriendLoc, TempParamLists); 16624 Friend->setAccess(AS_public); 16625 Friend->setUnsupportedFriend(true); 16626 CurContext->addDecl(Friend); 16627 return Friend; 16628 } 16629 16630 /// Handle a friend type declaration. This works in tandem with 16631 /// ActOnTag. 16632 /// 16633 /// Notes on friend class templates: 16634 /// 16635 /// We generally treat friend class declarations as if they were 16636 /// declaring a class. So, for example, the elaborated type specifier 16637 /// in a friend declaration is required to obey the restrictions of a 16638 /// class-head (i.e. no typedefs in the scope chain), template 16639 /// parameters are required to match up with simple template-ids, &c. 16640 /// However, unlike when declaring a template specialization, it's 16641 /// okay to refer to a template specialization without an empty 16642 /// template parameter declaration, e.g. 16643 /// friend class A<T>::B<unsigned>; 16644 /// We permit this as a special case; if there are any template 16645 /// parameters present at all, require proper matching, i.e. 16646 /// template <> template \<class T> friend class A<int>::B; 16647 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 16648 MultiTemplateParamsArg TempParams) { 16649 SourceLocation Loc = DS.getBeginLoc(); 16650 16651 assert(DS.isFriendSpecified()); 16652 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16653 16654 // C++ [class.friend]p3: 16655 // A friend declaration that does not declare a function shall have one of 16656 // the following forms: 16657 // friend elaborated-type-specifier ; 16658 // friend simple-type-specifier ; 16659 // friend typename-specifier ; 16660 // 16661 // Any declaration with a type qualifier does not have that form. (It's 16662 // legal to specify a qualified type as a friend, you just can't write the 16663 // keywords.) 16664 if (DS.getTypeQualifiers()) { 16665 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 16666 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 16667 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 16668 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 16669 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 16670 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 16671 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 16672 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 16673 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 16674 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 16675 } 16676 16677 // Try to convert the decl specifier to a type. This works for 16678 // friend templates because ActOnTag never produces a ClassTemplateDecl 16679 // for a TUK_Friend. 16680 Declarator TheDeclarator(DS, DeclaratorContext::Member); 16681 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 16682 QualType T = TSI->getType(); 16683 if (TheDeclarator.isInvalidType()) 16684 return nullptr; 16685 16686 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 16687 return nullptr; 16688 16689 // This is definitely an error in C++98. It's probably meant to 16690 // be forbidden in C++0x, too, but the specification is just 16691 // poorly written. 16692 // 16693 // The problem is with declarations like the following: 16694 // template <T> friend A<T>::foo; 16695 // where deciding whether a class C is a friend or not now hinges 16696 // on whether there exists an instantiation of A that causes 16697 // 'foo' to equal C. There are restrictions on class-heads 16698 // (which we declare (by fiat) elaborated friend declarations to 16699 // be) that makes this tractable. 16700 // 16701 // FIXME: handle "template <> friend class A<T>;", which 16702 // is possibly well-formed? Who even knows? 16703 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 16704 Diag(Loc, diag::err_tagless_friend_type_template) 16705 << DS.getSourceRange(); 16706 return nullptr; 16707 } 16708 16709 // C++98 [class.friend]p1: A friend of a class is a function 16710 // or class that is not a member of the class . . . 16711 // This is fixed in DR77, which just barely didn't make the C++03 16712 // deadline. It's also a very silly restriction that seriously 16713 // affects inner classes and which nobody else seems to implement; 16714 // thus we never diagnose it, not even in -pedantic. 16715 // 16716 // But note that we could warn about it: it's always useless to 16717 // friend one of your own members (it's not, however, worthless to 16718 // friend a member of an arbitrary specialization of your template). 16719 16720 Decl *D; 16721 if (!TempParams.empty()) 16722 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 16723 TempParams, 16724 TSI, 16725 DS.getFriendSpecLoc()); 16726 else 16727 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 16728 16729 if (!D) 16730 return nullptr; 16731 16732 D->setAccess(AS_public); 16733 CurContext->addDecl(D); 16734 16735 return D; 16736 } 16737 16738 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 16739 MultiTemplateParamsArg TemplateParams) { 16740 const DeclSpec &DS = D.getDeclSpec(); 16741 16742 assert(DS.isFriendSpecified()); 16743 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16744 16745 SourceLocation Loc = D.getIdentifierLoc(); 16746 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16747 16748 // C++ [class.friend]p1 16749 // A friend of a class is a function or class.... 16750 // Note that this sees through typedefs, which is intended. 16751 // It *doesn't* see through dependent types, which is correct 16752 // according to [temp.arg.type]p3: 16753 // If a declaration acquires a function type through a 16754 // type dependent on a template-parameter and this causes 16755 // a declaration that does not use the syntactic form of a 16756 // function declarator to have a function type, the program 16757 // is ill-formed. 16758 if (!TInfo->getType()->isFunctionType()) { 16759 Diag(Loc, diag::err_unexpected_friend); 16760 16761 // It might be worthwhile to try to recover by creating an 16762 // appropriate declaration. 16763 return nullptr; 16764 } 16765 16766 // C++ [namespace.memdef]p3 16767 // - If a friend declaration in a non-local class first declares a 16768 // class or function, the friend class or function is a member 16769 // of the innermost enclosing namespace. 16770 // - The name of the friend is not found by simple name lookup 16771 // until a matching declaration is provided in that namespace 16772 // scope (either before or after the class declaration granting 16773 // friendship). 16774 // - If a friend function is called, its name may be found by the 16775 // name lookup that considers functions from namespaces and 16776 // classes associated with the types of the function arguments. 16777 // - When looking for a prior declaration of a class or a function 16778 // declared as a friend, scopes outside the innermost enclosing 16779 // namespace scope are not considered. 16780 16781 CXXScopeSpec &SS = D.getCXXScopeSpec(); 16782 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 16783 assert(NameInfo.getName()); 16784 16785 // Check for unexpanded parameter packs. 16786 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 16787 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 16788 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 16789 return nullptr; 16790 16791 // The context we found the declaration in, or in which we should 16792 // create the declaration. 16793 DeclContext *DC; 16794 Scope *DCScope = S; 16795 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 16796 ForExternalRedeclaration); 16797 16798 // There are five cases here. 16799 // - There's no scope specifier and we're in a local class. Only look 16800 // for functions declared in the immediately-enclosing block scope. 16801 // We recover from invalid scope qualifiers as if they just weren't there. 16802 FunctionDecl *FunctionContainingLocalClass = nullptr; 16803 if ((SS.isInvalid() || !SS.isSet()) && 16804 (FunctionContainingLocalClass = 16805 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 16806 // C++11 [class.friend]p11: 16807 // If a friend declaration appears in a local class and the name 16808 // specified is an unqualified name, a prior declaration is 16809 // looked up without considering scopes that are outside the 16810 // innermost enclosing non-class scope. For a friend function 16811 // declaration, if there is no prior declaration, the program is 16812 // ill-formed. 16813 16814 // Find the innermost enclosing non-class scope. This is the block 16815 // scope containing the local class definition (or for a nested class, 16816 // the outer local class). 16817 DCScope = S->getFnParent(); 16818 16819 // Look up the function name in the scope. 16820 Previous.clear(LookupLocalFriendName); 16821 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 16822 16823 if (!Previous.empty()) { 16824 // All possible previous declarations must have the same context: 16825 // either they were declared at block scope or they are members of 16826 // one of the enclosing local classes. 16827 DC = Previous.getRepresentativeDecl()->getDeclContext(); 16828 } else { 16829 // This is ill-formed, but provide the context that we would have 16830 // declared the function in, if we were permitted to, for error recovery. 16831 DC = FunctionContainingLocalClass; 16832 } 16833 adjustContextForLocalExternDecl(DC); 16834 16835 // C++ [class.friend]p6: 16836 // A function can be defined in a friend declaration of a class if and 16837 // only if the class is a non-local class (9.8), the function name is 16838 // unqualified, and the function has namespace scope. 16839 if (D.isFunctionDefinition()) { 16840 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 16841 } 16842 16843 // - There's no scope specifier, in which case we just go to the 16844 // appropriate scope and look for a function or function template 16845 // there as appropriate. 16846 } else if (SS.isInvalid() || !SS.isSet()) { 16847 // C++11 [namespace.memdef]p3: 16848 // If the name in a friend declaration is neither qualified nor 16849 // a template-id and the declaration is a function or an 16850 // elaborated-type-specifier, the lookup to determine whether 16851 // the entity has been previously declared shall not consider 16852 // any scopes outside the innermost enclosing namespace. 16853 bool isTemplateId = 16854 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 16855 16856 // Find the appropriate context according to the above. 16857 DC = CurContext; 16858 16859 // Skip class contexts. If someone can cite chapter and verse 16860 // for this behavior, that would be nice --- it's what GCC and 16861 // EDG do, and it seems like a reasonable intent, but the spec 16862 // really only says that checks for unqualified existing 16863 // declarations should stop at the nearest enclosing namespace, 16864 // not that they should only consider the nearest enclosing 16865 // namespace. 16866 while (DC->isRecord()) 16867 DC = DC->getParent(); 16868 16869 DeclContext *LookupDC = DC->getNonTransparentContext(); 16870 while (true) { 16871 LookupQualifiedName(Previous, LookupDC); 16872 16873 if (!Previous.empty()) { 16874 DC = LookupDC; 16875 break; 16876 } 16877 16878 if (isTemplateId) { 16879 if (isa<TranslationUnitDecl>(LookupDC)) break; 16880 } else { 16881 if (LookupDC->isFileContext()) break; 16882 } 16883 LookupDC = LookupDC->getParent(); 16884 } 16885 16886 DCScope = getScopeForDeclContext(S, DC); 16887 16888 // - There's a non-dependent scope specifier, in which case we 16889 // compute it and do a previous lookup there for a function 16890 // or function template. 16891 } else if (!SS.getScopeRep()->isDependent()) { 16892 DC = computeDeclContext(SS); 16893 if (!DC) return nullptr; 16894 16895 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 16896 16897 LookupQualifiedName(Previous, DC); 16898 16899 // C++ [class.friend]p1: A friend of a class is a function or 16900 // class that is not a member of the class . . . 16901 if (DC->Equals(CurContext)) 16902 Diag(DS.getFriendSpecLoc(), 16903 getLangOpts().CPlusPlus11 ? 16904 diag::warn_cxx98_compat_friend_is_member : 16905 diag::err_friend_is_member); 16906 16907 if (D.isFunctionDefinition()) { 16908 // C++ [class.friend]p6: 16909 // A function can be defined in a friend declaration of a class if and 16910 // only if the class is a non-local class (9.8), the function name is 16911 // unqualified, and the function has namespace scope. 16912 // 16913 // FIXME: We should only do this if the scope specifier names the 16914 // innermost enclosing namespace; otherwise the fixit changes the 16915 // meaning of the code. 16916 SemaDiagnosticBuilder DB 16917 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 16918 16919 DB << SS.getScopeRep(); 16920 if (DC->isFileContext()) 16921 DB << FixItHint::CreateRemoval(SS.getRange()); 16922 SS.clear(); 16923 } 16924 16925 // - There's a scope specifier that does not match any template 16926 // parameter lists, in which case we use some arbitrary context, 16927 // create a method or method template, and wait for instantiation. 16928 // - There's a scope specifier that does match some template 16929 // parameter lists, which we don't handle right now. 16930 } else { 16931 if (D.isFunctionDefinition()) { 16932 // C++ [class.friend]p6: 16933 // A function can be defined in a friend declaration of a class if and 16934 // only if the class is a non-local class (9.8), the function name is 16935 // unqualified, and the function has namespace scope. 16936 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 16937 << SS.getScopeRep(); 16938 } 16939 16940 DC = CurContext; 16941 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 16942 } 16943 16944 if (!DC->isRecord()) { 16945 int DiagArg = -1; 16946 switch (D.getName().getKind()) { 16947 case UnqualifiedIdKind::IK_ConstructorTemplateId: 16948 case UnqualifiedIdKind::IK_ConstructorName: 16949 DiagArg = 0; 16950 break; 16951 case UnqualifiedIdKind::IK_DestructorName: 16952 DiagArg = 1; 16953 break; 16954 case UnqualifiedIdKind::IK_ConversionFunctionId: 16955 DiagArg = 2; 16956 break; 16957 case UnqualifiedIdKind::IK_DeductionGuideName: 16958 DiagArg = 3; 16959 break; 16960 case UnqualifiedIdKind::IK_Identifier: 16961 case UnqualifiedIdKind::IK_ImplicitSelfParam: 16962 case UnqualifiedIdKind::IK_LiteralOperatorId: 16963 case UnqualifiedIdKind::IK_OperatorFunctionId: 16964 case UnqualifiedIdKind::IK_TemplateId: 16965 break; 16966 } 16967 // This implies that it has to be an operator or function. 16968 if (DiagArg >= 0) { 16969 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 16970 return nullptr; 16971 } 16972 } 16973 16974 // FIXME: This is an egregious hack to cope with cases where the scope stack 16975 // does not contain the declaration context, i.e., in an out-of-line 16976 // definition of a class. 16977 Scope FakeDCScope(S, Scope::DeclScope, Diags); 16978 if (!DCScope) { 16979 FakeDCScope.setEntity(DC); 16980 DCScope = &FakeDCScope; 16981 } 16982 16983 bool AddToScope = true; 16984 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 16985 TemplateParams, AddToScope); 16986 if (!ND) return nullptr; 16987 16988 assert(ND->getLexicalDeclContext() == CurContext); 16989 16990 // If we performed typo correction, we might have added a scope specifier 16991 // and changed the decl context. 16992 DC = ND->getDeclContext(); 16993 16994 // Add the function declaration to the appropriate lookup tables, 16995 // adjusting the redeclarations list as necessary. We don't 16996 // want to do this yet if the friending class is dependent. 16997 // 16998 // Also update the scope-based lookup if the target context's 16999 // lookup context is in lexical scope. 17000 if (!CurContext->isDependentContext()) { 17001 DC = DC->getRedeclContext(); 17002 DC->makeDeclVisibleInContext(ND); 17003 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 17004 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 17005 } 17006 17007 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 17008 D.getIdentifierLoc(), ND, 17009 DS.getFriendSpecLoc()); 17010 FrD->setAccess(AS_public); 17011 CurContext->addDecl(FrD); 17012 17013 if (ND->isInvalidDecl()) { 17014 FrD->setInvalidDecl(); 17015 } else { 17016 if (DC->isRecord()) CheckFriendAccess(ND); 17017 17018 FunctionDecl *FD; 17019 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 17020 FD = FTD->getTemplatedDecl(); 17021 else 17022 FD = cast<FunctionDecl>(ND); 17023 17024 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 17025 // default argument expression, that declaration shall be a definition 17026 // and shall be the only declaration of the function or function 17027 // template in the translation unit. 17028 if (functionDeclHasDefaultArgument(FD)) { 17029 // We can't look at FD->getPreviousDecl() because it may not have been set 17030 // if we're in a dependent context. If the function is known to be a 17031 // redeclaration, we will have narrowed Previous down to the right decl. 17032 if (D.isRedeclaration()) { 17033 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 17034 Diag(Previous.getRepresentativeDecl()->getLocation(), 17035 diag::note_previous_declaration); 17036 } else if (!D.isFunctionDefinition()) 17037 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 17038 } 17039 17040 // Mark templated-scope function declarations as unsupported. 17041 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 17042 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 17043 << SS.getScopeRep() << SS.getRange() 17044 << cast<CXXRecordDecl>(CurContext); 17045 FrD->setUnsupportedFriend(true); 17046 } 17047 } 17048 17049 warnOnReservedIdentifier(ND); 17050 17051 return ND; 17052 } 17053 17054 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 17055 AdjustDeclIfTemplate(Dcl); 17056 17057 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 17058 if (!Fn) { 17059 Diag(DelLoc, diag::err_deleted_non_function); 17060 return; 17061 } 17062 17063 // Deleted function does not have a body. 17064 Fn->setWillHaveBody(false); 17065 17066 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 17067 // Don't consider the implicit declaration we generate for explicit 17068 // specializations. FIXME: Do not generate these implicit declarations. 17069 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 17070 Prev->getPreviousDecl()) && 17071 !Prev->isDefined()) { 17072 Diag(DelLoc, diag::err_deleted_decl_not_first); 17073 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 17074 Prev->isImplicit() ? diag::note_previous_implicit_declaration 17075 : diag::note_previous_declaration); 17076 // We can't recover from this; the declaration might have already 17077 // been used. 17078 Fn->setInvalidDecl(); 17079 return; 17080 } 17081 17082 // To maintain the invariant that functions are only deleted on their first 17083 // declaration, mark the implicitly-instantiated declaration of the 17084 // explicitly-specialized function as deleted instead of marking the 17085 // instantiated redeclaration. 17086 Fn = Fn->getCanonicalDecl(); 17087 } 17088 17089 // dllimport/dllexport cannot be deleted. 17090 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 17091 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 17092 Fn->setInvalidDecl(); 17093 } 17094 17095 // C++11 [basic.start.main]p3: 17096 // A program that defines main as deleted [...] is ill-formed. 17097 if (Fn->isMain()) 17098 Diag(DelLoc, diag::err_deleted_main); 17099 17100 // C++11 [dcl.fct.def.delete]p4: 17101 // A deleted function is implicitly inline. 17102 Fn->setImplicitlyInline(); 17103 Fn->setDeletedAsWritten(); 17104 } 17105 17106 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 17107 if (!Dcl || Dcl->isInvalidDecl()) 17108 return; 17109 17110 auto *FD = dyn_cast<FunctionDecl>(Dcl); 17111 if (!FD) { 17112 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 17113 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 17114 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 17115 return; 17116 } 17117 } 17118 17119 Diag(DefaultLoc, diag::err_default_special_members) 17120 << getLangOpts().CPlusPlus20; 17121 return; 17122 } 17123 17124 // Reject if this can't possibly be a defaultable function. 17125 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 17126 if (!DefKind && 17127 // A dependent function that doesn't locally look defaultable can 17128 // still instantiate to a defaultable function if it's a constructor 17129 // or assignment operator. 17130 (!FD->isDependentContext() || 17131 (!isa<CXXConstructorDecl>(FD) && 17132 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 17133 Diag(DefaultLoc, diag::err_default_special_members) 17134 << getLangOpts().CPlusPlus20; 17135 return; 17136 } 17137 17138 if (DefKind.isComparison() && 17139 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 17140 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class) 17141 << (int)DefKind.asComparison(); 17142 return; 17143 } 17144 17145 // Issue compatibility warning. We already warned if the operator is 17146 // 'operator<=>' when parsing the '<=>' token. 17147 if (DefKind.isComparison() && 17148 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 17149 Diag(DefaultLoc, getLangOpts().CPlusPlus20 17150 ? diag::warn_cxx17_compat_defaulted_comparison 17151 : diag::ext_defaulted_comparison); 17152 } 17153 17154 FD->setDefaulted(); 17155 FD->setExplicitlyDefaulted(); 17156 17157 // Defer checking functions that are defaulted in a dependent context. 17158 if (FD->isDependentContext()) 17159 return; 17160 17161 // Unset that we will have a body for this function. We might not, 17162 // if it turns out to be trivial, and we don't need this marking now 17163 // that we've marked it as defaulted. 17164 FD->setWillHaveBody(false); 17165 17166 // If this definition appears within the record, do the checking when 17167 // the record is complete. This is always the case for a defaulted 17168 // comparison. 17169 if (DefKind.isComparison()) 17170 return; 17171 auto *MD = cast<CXXMethodDecl>(FD); 17172 17173 const FunctionDecl *Primary = FD; 17174 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 17175 // Ask the template instantiation pattern that actually had the 17176 // '= default' on it. 17177 Primary = Pattern; 17178 17179 // If the method was defaulted on its first declaration, we will have 17180 // already performed the checking in CheckCompletedCXXClass. Such a 17181 // declaration doesn't trigger an implicit definition. 17182 if (Primary->getCanonicalDecl()->isDefaulted()) 17183 return; 17184 17185 // FIXME: Once we support defining comparisons out of class, check for a 17186 // defaulted comparison here. 17187 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 17188 MD->setInvalidDecl(); 17189 else 17190 DefineDefaultedFunction(*this, MD, DefaultLoc); 17191 } 17192 17193 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 17194 for (Stmt *SubStmt : S->children()) { 17195 if (!SubStmt) 17196 continue; 17197 if (isa<ReturnStmt>(SubStmt)) 17198 Self.Diag(SubStmt->getBeginLoc(), 17199 diag::err_return_in_constructor_handler); 17200 if (!isa<Expr>(SubStmt)) 17201 SearchForReturnInStmt(Self, SubStmt); 17202 } 17203 } 17204 17205 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 17206 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 17207 CXXCatchStmt *Handler = TryBlock->getHandler(I); 17208 SearchForReturnInStmt(*this, Handler); 17209 } 17210 } 17211 17212 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 17213 const CXXMethodDecl *Old) { 17214 const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); 17215 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); 17216 17217 if (OldFT->hasExtParameterInfos()) { 17218 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 17219 // A parameter of the overriding method should be annotated with noescape 17220 // if the corresponding parameter of the overridden method is annotated. 17221 if (OldFT->getExtParameterInfo(I).isNoEscape() && 17222 !NewFT->getExtParameterInfo(I).isNoEscape()) { 17223 Diag(New->getParamDecl(I)->getLocation(), 17224 diag::warn_overriding_method_missing_noescape); 17225 Diag(Old->getParamDecl(I)->getLocation(), 17226 diag::note_overridden_marked_noescape); 17227 } 17228 } 17229 17230 // Virtual overrides must have the same code_seg. 17231 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 17232 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 17233 if ((NewCSA || OldCSA) && 17234 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 17235 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 17236 Diag(Old->getLocation(), diag::note_previous_declaration); 17237 return true; 17238 } 17239 17240 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 17241 17242 // If the calling conventions match, everything is fine 17243 if (NewCC == OldCC) 17244 return false; 17245 17246 // If the calling conventions mismatch because the new function is static, 17247 // suppress the calling convention mismatch error; the error about static 17248 // function override (err_static_overrides_virtual from 17249 // Sema::CheckFunctionDeclaration) is more clear. 17250 if (New->getStorageClass() == SC_Static) 17251 return false; 17252 17253 Diag(New->getLocation(), 17254 diag::err_conflicting_overriding_cc_attributes) 17255 << New->getDeclName() << New->getType() << Old->getType(); 17256 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 17257 return true; 17258 } 17259 17260 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 17261 const CXXMethodDecl *Old) { 17262 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); 17263 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); 17264 17265 if (Context.hasSameType(NewTy, OldTy) || 17266 NewTy->isDependentType() || OldTy->isDependentType()) 17267 return false; 17268 17269 // Check if the return types are covariant 17270 QualType NewClassTy, OldClassTy; 17271 17272 /// Both types must be pointers or references to classes. 17273 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 17274 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 17275 NewClassTy = NewPT->getPointeeType(); 17276 OldClassTy = OldPT->getPointeeType(); 17277 } 17278 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 17279 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 17280 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 17281 NewClassTy = NewRT->getPointeeType(); 17282 OldClassTy = OldRT->getPointeeType(); 17283 } 17284 } 17285 } 17286 17287 // The return types aren't either both pointers or references to a class type. 17288 if (NewClassTy.isNull()) { 17289 Diag(New->getLocation(), 17290 diag::err_different_return_type_for_overriding_virtual_function) 17291 << New->getDeclName() << NewTy << OldTy 17292 << New->getReturnTypeSourceRange(); 17293 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17294 << Old->getReturnTypeSourceRange(); 17295 17296 return true; 17297 } 17298 17299 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 17300 // C++14 [class.virtual]p8: 17301 // If the class type in the covariant return type of D::f differs from 17302 // that of B::f, the class type in the return type of D::f shall be 17303 // complete at the point of declaration of D::f or shall be the class 17304 // type D. 17305 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 17306 if (!RT->isBeingDefined() && 17307 RequireCompleteType(New->getLocation(), NewClassTy, 17308 diag::err_covariant_return_incomplete, 17309 New->getDeclName())) 17310 return true; 17311 } 17312 17313 // Check if the new class derives from the old class. 17314 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 17315 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 17316 << New->getDeclName() << NewTy << OldTy 17317 << New->getReturnTypeSourceRange(); 17318 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17319 << Old->getReturnTypeSourceRange(); 17320 return true; 17321 } 17322 17323 // Check if we the conversion from derived to base is valid. 17324 if (CheckDerivedToBaseConversion( 17325 NewClassTy, OldClassTy, 17326 diag::err_covariant_return_inaccessible_base, 17327 diag::err_covariant_return_ambiguous_derived_to_base_conv, 17328 New->getLocation(), New->getReturnTypeSourceRange(), 17329 New->getDeclName(), nullptr)) { 17330 // FIXME: this note won't trigger for delayed access control 17331 // diagnostics, and it's impossible to get an undelayed error 17332 // here from access control during the original parse because 17333 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 17334 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17335 << Old->getReturnTypeSourceRange(); 17336 return true; 17337 } 17338 } 17339 17340 // The qualifiers of the return types must be the same. 17341 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 17342 Diag(New->getLocation(), 17343 diag::err_covariant_return_type_different_qualifications) 17344 << New->getDeclName() << NewTy << OldTy 17345 << New->getReturnTypeSourceRange(); 17346 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17347 << Old->getReturnTypeSourceRange(); 17348 return true; 17349 } 17350 17351 17352 // The new class type must have the same or less qualifiers as the old type. 17353 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 17354 Diag(New->getLocation(), 17355 diag::err_covariant_return_type_class_type_more_qualified) 17356 << New->getDeclName() << NewTy << OldTy 17357 << New->getReturnTypeSourceRange(); 17358 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17359 << Old->getReturnTypeSourceRange(); 17360 return true; 17361 } 17362 17363 return false; 17364 } 17365 17366 /// Mark the given method pure. 17367 /// 17368 /// \param Method the method to be marked pure. 17369 /// 17370 /// \param InitRange the source range that covers the "0" initializer. 17371 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 17372 SourceLocation EndLoc = InitRange.getEnd(); 17373 if (EndLoc.isValid()) 17374 Method->setRangeEnd(EndLoc); 17375 17376 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 17377 Method->setPure(); 17378 return false; 17379 } 17380 17381 if (!Method->isInvalidDecl()) 17382 Diag(Method->getLocation(), diag::err_non_virtual_pure) 17383 << Method->getDeclName() << InitRange; 17384 return true; 17385 } 17386 17387 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 17388 if (D->getFriendObjectKind()) 17389 Diag(D->getLocation(), diag::err_pure_friend); 17390 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 17391 CheckPureMethod(M, ZeroLoc); 17392 else 17393 Diag(D->getLocation(), diag::err_illegal_initializer); 17394 } 17395 17396 /// Determine whether the given declaration is a global variable or 17397 /// static data member. 17398 static bool isNonlocalVariable(const Decl *D) { 17399 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 17400 return Var->hasGlobalStorage(); 17401 17402 return false; 17403 } 17404 17405 /// Invoked when we are about to parse an initializer for the declaration 17406 /// 'Dcl'. 17407 /// 17408 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 17409 /// static data member of class X, names should be looked up in the scope of 17410 /// class X. If the declaration had a scope specifier, a scope will have 17411 /// been created and passed in for this purpose. Otherwise, S will be null. 17412 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 17413 // If there is no declaration, there was an error parsing it. 17414 if (!D || D->isInvalidDecl()) 17415 return; 17416 17417 // We will always have a nested name specifier here, but this declaration 17418 // might not be out of line if the specifier names the current namespace: 17419 // extern int n; 17420 // int ::n = 0; 17421 if (S && D->isOutOfLine()) 17422 EnterDeclaratorContext(S, D->getDeclContext()); 17423 17424 // If we are parsing the initializer for a static data member, push a 17425 // new expression evaluation context that is associated with this static 17426 // data member. 17427 if (isNonlocalVariable(D)) 17428 PushExpressionEvaluationContext( 17429 ExpressionEvaluationContext::PotentiallyEvaluated, D); 17430 } 17431 17432 /// Invoked after we are finished parsing an initializer for the declaration D. 17433 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 17434 // If there is no declaration, there was an error parsing it. 17435 if (!D || D->isInvalidDecl()) 17436 return; 17437 17438 if (isNonlocalVariable(D)) 17439 PopExpressionEvaluationContext(); 17440 17441 if (S && D->isOutOfLine()) 17442 ExitDeclaratorContext(S); 17443 } 17444 17445 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 17446 /// C++ if/switch/while/for statement. 17447 /// e.g: "if (int x = f()) {...}" 17448 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 17449 // C++ 6.4p2: 17450 // The declarator shall not specify a function or an array. 17451 // The type-specifier-seq shall not contain typedef and shall not declare a 17452 // new class or enumeration. 17453 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 17454 "Parser allowed 'typedef' as storage class of condition decl."); 17455 17456 Decl *Dcl = ActOnDeclarator(S, D); 17457 if (!Dcl) 17458 return true; 17459 17460 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 17461 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 17462 << D.getSourceRange(); 17463 return true; 17464 } 17465 17466 return Dcl; 17467 } 17468 17469 void Sema::LoadExternalVTableUses() { 17470 if (!ExternalSource) 17471 return; 17472 17473 SmallVector<ExternalVTableUse, 4> VTables; 17474 ExternalSource->ReadUsedVTables(VTables); 17475 SmallVector<VTableUse, 4> NewUses; 17476 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 17477 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 17478 = VTablesUsed.find(VTables[I].Record); 17479 // Even if a definition wasn't required before, it may be required now. 17480 if (Pos != VTablesUsed.end()) { 17481 if (!Pos->second && VTables[I].DefinitionRequired) 17482 Pos->second = true; 17483 continue; 17484 } 17485 17486 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 17487 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 17488 } 17489 17490 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 17491 } 17492 17493 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 17494 bool DefinitionRequired) { 17495 // Ignore any vtable uses in unevaluated operands or for classes that do 17496 // not have a vtable. 17497 if (!Class->isDynamicClass() || Class->isDependentContext() || 17498 CurContext->isDependentContext() || isUnevaluatedContext()) 17499 return; 17500 // Do not mark as used if compiling for the device outside of the target 17501 // region. 17502 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 17503 !isInOpenMPDeclareTargetContext() && 17504 !isInOpenMPTargetExecutionDirective()) { 17505 if (!DefinitionRequired) 17506 MarkVirtualMembersReferenced(Loc, Class); 17507 return; 17508 } 17509 17510 // Try to insert this class into the map. 17511 LoadExternalVTableUses(); 17512 Class = Class->getCanonicalDecl(); 17513 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 17514 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 17515 if (!Pos.second) { 17516 // If we already had an entry, check to see if we are promoting this vtable 17517 // to require a definition. If so, we need to reappend to the VTableUses 17518 // list, since we may have already processed the first entry. 17519 if (DefinitionRequired && !Pos.first->second) { 17520 Pos.first->second = true; 17521 } else { 17522 // Otherwise, we can early exit. 17523 return; 17524 } 17525 } else { 17526 // The Microsoft ABI requires that we perform the destructor body 17527 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 17528 // the deleting destructor is emitted with the vtable, not with the 17529 // destructor definition as in the Itanium ABI. 17530 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17531 CXXDestructorDecl *DD = Class->getDestructor(); 17532 if (DD && DD->isVirtual() && !DD->isDeleted()) { 17533 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 17534 // If this is an out-of-line declaration, marking it referenced will 17535 // not do anything. Manually call CheckDestructor to look up operator 17536 // delete(). 17537 ContextRAII SavedContext(*this, DD); 17538 CheckDestructor(DD); 17539 } else { 17540 MarkFunctionReferenced(Loc, Class->getDestructor()); 17541 } 17542 } 17543 } 17544 } 17545 17546 // Local classes need to have their virtual members marked 17547 // immediately. For all other classes, we mark their virtual members 17548 // at the end of the translation unit. 17549 if (Class->isLocalClass()) 17550 MarkVirtualMembersReferenced(Loc, Class); 17551 else 17552 VTableUses.push_back(std::make_pair(Class, Loc)); 17553 } 17554 17555 bool Sema::DefineUsedVTables() { 17556 LoadExternalVTableUses(); 17557 if (VTableUses.empty()) 17558 return false; 17559 17560 // Note: The VTableUses vector could grow as a result of marking 17561 // the members of a class as "used", so we check the size each 17562 // time through the loop and prefer indices (which are stable) to 17563 // iterators (which are not). 17564 bool DefinedAnything = false; 17565 for (unsigned I = 0; I != VTableUses.size(); ++I) { 17566 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 17567 if (!Class) 17568 continue; 17569 TemplateSpecializationKind ClassTSK = 17570 Class->getTemplateSpecializationKind(); 17571 17572 SourceLocation Loc = VTableUses[I].second; 17573 17574 bool DefineVTable = true; 17575 17576 // If this class has a key function, but that key function is 17577 // defined in another translation unit, we don't need to emit the 17578 // vtable even though we're using it. 17579 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 17580 if (KeyFunction && !KeyFunction->hasBody()) { 17581 // The key function is in another translation unit. 17582 DefineVTable = false; 17583 TemplateSpecializationKind TSK = 17584 KeyFunction->getTemplateSpecializationKind(); 17585 assert(TSK != TSK_ExplicitInstantiationDefinition && 17586 TSK != TSK_ImplicitInstantiation && 17587 "Instantiations don't have key functions"); 17588 (void)TSK; 17589 } else if (!KeyFunction) { 17590 // If we have a class with no key function that is the subject 17591 // of an explicit instantiation declaration, suppress the 17592 // vtable; it will live with the explicit instantiation 17593 // definition. 17594 bool IsExplicitInstantiationDeclaration = 17595 ClassTSK == TSK_ExplicitInstantiationDeclaration; 17596 for (auto R : Class->redecls()) { 17597 TemplateSpecializationKind TSK 17598 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 17599 if (TSK == TSK_ExplicitInstantiationDeclaration) 17600 IsExplicitInstantiationDeclaration = true; 17601 else if (TSK == TSK_ExplicitInstantiationDefinition) { 17602 IsExplicitInstantiationDeclaration = false; 17603 break; 17604 } 17605 } 17606 17607 if (IsExplicitInstantiationDeclaration) 17608 DefineVTable = false; 17609 } 17610 17611 // The exception specifications for all virtual members may be needed even 17612 // if we are not providing an authoritative form of the vtable in this TU. 17613 // We may choose to emit it available_externally anyway. 17614 if (!DefineVTable) { 17615 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 17616 continue; 17617 } 17618 17619 // Mark all of the virtual members of this class as referenced, so 17620 // that we can build a vtable. Then, tell the AST consumer that a 17621 // vtable for this class is required. 17622 DefinedAnything = true; 17623 MarkVirtualMembersReferenced(Loc, Class); 17624 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 17625 if (VTablesUsed[Canonical]) 17626 Consumer.HandleVTable(Class); 17627 17628 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 17629 // no key function or the key function is inlined. Don't warn in C++ ABIs 17630 // that lack key functions, since the user won't be able to make one. 17631 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 17632 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 17633 const FunctionDecl *KeyFunctionDef = nullptr; 17634 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 17635 KeyFunctionDef->isInlined())) { 17636 Diag(Class->getLocation(), 17637 ClassTSK == TSK_ExplicitInstantiationDefinition 17638 ? diag::warn_weak_template_vtable 17639 : diag::warn_weak_vtable) 17640 << Class; 17641 } 17642 } 17643 } 17644 VTableUses.clear(); 17645 17646 return DefinedAnything; 17647 } 17648 17649 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 17650 const CXXRecordDecl *RD) { 17651 for (const auto *I : RD->methods()) 17652 if (I->isVirtual() && !I->isPure()) 17653 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 17654 } 17655 17656 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 17657 const CXXRecordDecl *RD, 17658 bool ConstexprOnly) { 17659 // Mark all functions which will appear in RD's vtable as used. 17660 CXXFinalOverriderMap FinalOverriders; 17661 RD->getFinalOverriders(FinalOverriders); 17662 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 17663 E = FinalOverriders.end(); 17664 I != E; ++I) { 17665 for (OverridingMethods::const_iterator OI = I->second.begin(), 17666 OE = I->second.end(); 17667 OI != OE; ++OI) { 17668 assert(OI->second.size() > 0 && "no final overrider"); 17669 CXXMethodDecl *Overrider = OI->second.front().Method; 17670 17671 // C++ [basic.def.odr]p2: 17672 // [...] A virtual member function is used if it is not pure. [...] 17673 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 17674 MarkFunctionReferenced(Loc, Overrider); 17675 } 17676 } 17677 17678 // Only classes that have virtual bases need a VTT. 17679 if (RD->getNumVBases() == 0) 17680 return; 17681 17682 for (const auto &I : RD->bases()) { 17683 const auto *Base = 17684 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 17685 if (Base->getNumVBases() == 0) 17686 continue; 17687 MarkVirtualMembersReferenced(Loc, Base); 17688 } 17689 } 17690 17691 /// SetIvarInitializers - This routine builds initialization ASTs for the 17692 /// Objective-C implementation whose ivars need be initialized. 17693 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 17694 if (!getLangOpts().CPlusPlus) 17695 return; 17696 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 17697 SmallVector<ObjCIvarDecl*, 8> ivars; 17698 CollectIvarsToConstructOrDestruct(OID, ivars); 17699 if (ivars.empty()) 17700 return; 17701 SmallVector<CXXCtorInitializer*, 32> AllToInit; 17702 for (unsigned i = 0; i < ivars.size(); i++) { 17703 FieldDecl *Field = ivars[i]; 17704 if (Field->isInvalidDecl()) 17705 continue; 17706 17707 CXXCtorInitializer *Member; 17708 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 17709 InitializationKind InitKind = 17710 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 17711 17712 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 17713 ExprResult MemberInit = 17714 InitSeq.Perform(*this, InitEntity, InitKind, None); 17715 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 17716 // Note, MemberInit could actually come back empty if no initialization 17717 // is required (e.g., because it would call a trivial default constructor) 17718 if (!MemberInit.get() || MemberInit.isInvalid()) 17719 continue; 17720 17721 Member = 17722 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 17723 SourceLocation(), 17724 MemberInit.getAs<Expr>(), 17725 SourceLocation()); 17726 AllToInit.push_back(Member); 17727 17728 // Be sure that the destructor is accessible and is marked as referenced. 17729 if (const RecordType *RecordTy = 17730 Context.getBaseElementType(Field->getType()) 17731 ->getAs<RecordType>()) { 17732 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 17733 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 17734 MarkFunctionReferenced(Field->getLocation(), Destructor); 17735 CheckDestructorAccess(Field->getLocation(), Destructor, 17736 PDiag(diag::err_access_dtor_ivar) 17737 << Context.getBaseElementType(Field->getType())); 17738 } 17739 } 17740 } 17741 ObjCImplementation->setIvarInitializers(Context, 17742 AllToInit.data(), AllToInit.size()); 17743 } 17744 } 17745 17746 static 17747 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 17748 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 17749 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 17750 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 17751 Sema &S) { 17752 if (Ctor->isInvalidDecl()) 17753 return; 17754 17755 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 17756 17757 // Target may not be determinable yet, for instance if this is a dependent 17758 // call in an uninstantiated template. 17759 if (Target) { 17760 const FunctionDecl *FNTarget = nullptr; 17761 (void)Target->hasBody(FNTarget); 17762 Target = const_cast<CXXConstructorDecl*>( 17763 cast_or_null<CXXConstructorDecl>(FNTarget)); 17764 } 17765 17766 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 17767 // Avoid dereferencing a null pointer here. 17768 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 17769 17770 if (!Current.insert(Canonical).second) 17771 return; 17772 17773 // We know that beyond here, we aren't chaining into a cycle. 17774 if (!Target || !Target->isDelegatingConstructor() || 17775 Target->isInvalidDecl() || Valid.count(TCanonical)) { 17776 Valid.insert(Current.begin(), Current.end()); 17777 Current.clear(); 17778 // We've hit a cycle. 17779 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 17780 Current.count(TCanonical)) { 17781 // If we haven't diagnosed this cycle yet, do so now. 17782 if (!Invalid.count(TCanonical)) { 17783 S.Diag((*Ctor->init_begin())->getSourceLocation(), 17784 diag::warn_delegating_ctor_cycle) 17785 << Ctor; 17786 17787 // Don't add a note for a function delegating directly to itself. 17788 if (TCanonical != Canonical) 17789 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 17790 17791 CXXConstructorDecl *C = Target; 17792 while (C->getCanonicalDecl() != Canonical) { 17793 const FunctionDecl *FNTarget = nullptr; 17794 (void)C->getTargetConstructor()->hasBody(FNTarget); 17795 assert(FNTarget && "Ctor cycle through bodiless function"); 17796 17797 C = const_cast<CXXConstructorDecl*>( 17798 cast<CXXConstructorDecl>(FNTarget)); 17799 S.Diag(C->getLocation(), diag::note_which_delegates_to); 17800 } 17801 } 17802 17803 Invalid.insert(Current.begin(), Current.end()); 17804 Current.clear(); 17805 } else { 17806 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 17807 } 17808 } 17809 17810 17811 void Sema::CheckDelegatingCtorCycles() { 17812 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 17813 17814 for (DelegatingCtorDeclsType::iterator 17815 I = DelegatingCtorDecls.begin(ExternalSource), 17816 E = DelegatingCtorDecls.end(); 17817 I != E; ++I) 17818 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 17819 17820 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 17821 (*CI)->setInvalidDecl(); 17822 } 17823 17824 namespace { 17825 /// AST visitor that finds references to the 'this' expression. 17826 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 17827 Sema &S; 17828 17829 public: 17830 explicit FindCXXThisExpr(Sema &S) : S(S) { } 17831 17832 bool VisitCXXThisExpr(CXXThisExpr *E) { 17833 S.Diag(E->getLocation(), diag::err_this_static_member_func) 17834 << E->isImplicit(); 17835 return false; 17836 } 17837 }; 17838 } 17839 17840 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 17841 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17842 if (!TSInfo) 17843 return false; 17844 17845 TypeLoc TL = TSInfo->getTypeLoc(); 17846 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17847 if (!ProtoTL) 17848 return false; 17849 17850 // C++11 [expr.prim.general]p3: 17851 // [The expression this] shall not appear before the optional 17852 // cv-qualifier-seq and it shall not appear within the declaration of a 17853 // static member function (although its type and value category are defined 17854 // within a static member function as they are within a non-static member 17855 // function). [ Note: this is because declaration matching does not occur 17856 // until the complete declarator is known. - end note ] 17857 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17858 FindCXXThisExpr Finder(*this); 17859 17860 // If the return type came after the cv-qualifier-seq, check it now. 17861 if (Proto->hasTrailingReturn() && 17862 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 17863 return true; 17864 17865 // Check the exception specification. 17866 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 17867 return true; 17868 17869 // Check the trailing requires clause 17870 if (Expr *E = Method->getTrailingRequiresClause()) 17871 if (!Finder.TraverseStmt(E)) 17872 return true; 17873 17874 return checkThisInStaticMemberFunctionAttributes(Method); 17875 } 17876 17877 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 17878 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17879 if (!TSInfo) 17880 return false; 17881 17882 TypeLoc TL = TSInfo->getTypeLoc(); 17883 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17884 if (!ProtoTL) 17885 return false; 17886 17887 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17888 FindCXXThisExpr Finder(*this); 17889 17890 switch (Proto->getExceptionSpecType()) { 17891 case EST_Unparsed: 17892 case EST_Uninstantiated: 17893 case EST_Unevaluated: 17894 case EST_BasicNoexcept: 17895 case EST_NoThrow: 17896 case EST_DynamicNone: 17897 case EST_MSAny: 17898 case EST_None: 17899 break; 17900 17901 case EST_DependentNoexcept: 17902 case EST_NoexceptFalse: 17903 case EST_NoexceptTrue: 17904 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 17905 return true; 17906 LLVM_FALLTHROUGH; 17907 17908 case EST_Dynamic: 17909 for (const auto &E : Proto->exceptions()) { 17910 if (!Finder.TraverseType(E)) 17911 return true; 17912 } 17913 break; 17914 } 17915 17916 return false; 17917 } 17918 17919 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 17920 FindCXXThisExpr Finder(*this); 17921 17922 // Check attributes. 17923 for (const auto *A : Method->attrs()) { 17924 // FIXME: This should be emitted by tblgen. 17925 Expr *Arg = nullptr; 17926 ArrayRef<Expr *> Args; 17927 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 17928 Arg = G->getArg(); 17929 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 17930 Arg = G->getArg(); 17931 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 17932 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 17933 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 17934 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 17935 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 17936 Arg = ETLF->getSuccessValue(); 17937 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 17938 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 17939 Arg = STLF->getSuccessValue(); 17940 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 17941 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 17942 Arg = LR->getArg(); 17943 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 17944 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 17945 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 17946 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17947 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 17948 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17949 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 17950 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17951 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 17952 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17953 17954 if (Arg && !Finder.TraverseStmt(Arg)) 17955 return true; 17956 17957 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 17958 if (!Finder.TraverseStmt(Args[I])) 17959 return true; 17960 } 17961 } 17962 17963 return false; 17964 } 17965 17966 void Sema::checkExceptionSpecification( 17967 bool IsTopLevel, ExceptionSpecificationType EST, 17968 ArrayRef<ParsedType> DynamicExceptions, 17969 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 17970 SmallVectorImpl<QualType> &Exceptions, 17971 FunctionProtoType::ExceptionSpecInfo &ESI) { 17972 Exceptions.clear(); 17973 ESI.Type = EST; 17974 if (EST == EST_Dynamic) { 17975 Exceptions.reserve(DynamicExceptions.size()); 17976 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 17977 // FIXME: Preserve type source info. 17978 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 17979 17980 if (IsTopLevel) { 17981 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 17982 collectUnexpandedParameterPacks(ET, Unexpanded); 17983 if (!Unexpanded.empty()) { 17984 DiagnoseUnexpandedParameterPacks( 17985 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 17986 Unexpanded); 17987 continue; 17988 } 17989 } 17990 17991 // Check that the type is valid for an exception spec, and 17992 // drop it if not. 17993 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 17994 Exceptions.push_back(ET); 17995 } 17996 ESI.Exceptions = Exceptions; 17997 return; 17998 } 17999 18000 if (isComputedNoexcept(EST)) { 18001 assert((NoexceptExpr->isTypeDependent() || 18002 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 18003 Context.BoolTy) && 18004 "Parser should have made sure that the expression is boolean"); 18005 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 18006 ESI.Type = EST_BasicNoexcept; 18007 return; 18008 } 18009 18010 ESI.NoexceptExpr = NoexceptExpr; 18011 return; 18012 } 18013 } 18014 18015 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 18016 ExceptionSpecificationType EST, 18017 SourceRange SpecificationRange, 18018 ArrayRef<ParsedType> DynamicExceptions, 18019 ArrayRef<SourceRange> DynamicExceptionRanges, 18020 Expr *NoexceptExpr) { 18021 if (!MethodD) 18022 return; 18023 18024 // Dig out the method we're referring to. 18025 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 18026 MethodD = FunTmpl->getTemplatedDecl(); 18027 18028 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 18029 if (!Method) 18030 return; 18031 18032 // Check the exception specification. 18033 llvm::SmallVector<QualType, 4> Exceptions; 18034 FunctionProtoType::ExceptionSpecInfo ESI; 18035 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 18036 DynamicExceptionRanges, NoexceptExpr, Exceptions, 18037 ESI); 18038 18039 // Update the exception specification on the function type. 18040 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 18041 18042 if (Method->isStatic()) 18043 checkThisInStaticMemberFunctionExceptionSpec(Method); 18044 18045 if (Method->isVirtual()) { 18046 // Check overrides, which we previously had to delay. 18047 for (const CXXMethodDecl *O : Method->overridden_methods()) 18048 CheckOverridingFunctionExceptionSpec(Method, O); 18049 } 18050 } 18051 18052 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 18053 /// 18054 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 18055 SourceLocation DeclStart, Declarator &D, 18056 Expr *BitWidth, 18057 InClassInitStyle InitStyle, 18058 AccessSpecifier AS, 18059 const ParsedAttr &MSPropertyAttr) { 18060 IdentifierInfo *II = D.getIdentifier(); 18061 if (!II) { 18062 Diag(DeclStart, diag::err_anonymous_property); 18063 return nullptr; 18064 } 18065 SourceLocation Loc = D.getIdentifierLoc(); 18066 18067 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 18068 QualType T = TInfo->getType(); 18069 if (getLangOpts().CPlusPlus) { 18070 CheckExtraCXXDefaultArguments(D); 18071 18072 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 18073 UPPC_DataMemberType)) { 18074 D.setInvalidType(); 18075 T = Context.IntTy; 18076 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 18077 } 18078 } 18079 18080 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 18081 18082 if (D.getDeclSpec().isInlineSpecified()) 18083 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 18084 << getLangOpts().CPlusPlus17; 18085 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 18086 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 18087 diag::err_invalid_thread) 18088 << DeclSpec::getSpecifierName(TSCS); 18089 18090 // Check to see if this name was declared as a member previously 18091 NamedDecl *PrevDecl = nullptr; 18092 LookupResult Previous(*this, II, Loc, LookupMemberName, 18093 ForVisibleRedeclaration); 18094 LookupName(Previous, S); 18095 switch (Previous.getResultKind()) { 18096 case LookupResult::Found: 18097 case LookupResult::FoundUnresolvedValue: 18098 PrevDecl = Previous.getAsSingle<NamedDecl>(); 18099 break; 18100 18101 case LookupResult::FoundOverloaded: 18102 PrevDecl = Previous.getRepresentativeDecl(); 18103 break; 18104 18105 case LookupResult::NotFound: 18106 case LookupResult::NotFoundInCurrentInstantiation: 18107 case LookupResult::Ambiguous: 18108 break; 18109 } 18110 18111 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18112 // Maybe we will complain about the shadowed template parameter. 18113 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 18114 // Just pretend that we didn't see the previous declaration. 18115 PrevDecl = nullptr; 18116 } 18117 18118 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 18119 PrevDecl = nullptr; 18120 18121 SourceLocation TSSL = D.getBeginLoc(); 18122 MSPropertyDecl *NewPD = 18123 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 18124 MSPropertyAttr.getPropertyDataGetter(), 18125 MSPropertyAttr.getPropertyDataSetter()); 18126 ProcessDeclAttributes(TUScope, NewPD, D); 18127 NewPD->setAccess(AS); 18128 18129 if (NewPD->isInvalidDecl()) 18130 Record->setInvalidDecl(); 18131 18132 if (D.getDeclSpec().isModulePrivateSpecified()) 18133 NewPD->setModulePrivate(); 18134 18135 if (NewPD->isInvalidDecl() && PrevDecl) { 18136 // Don't introduce NewFD into scope; there's already something 18137 // with the same name in the same scope. 18138 } else if (II) { 18139 PushOnScopeChains(NewPD, S); 18140 } else 18141 Record->addDecl(NewPD); 18142 18143 return NewPD; 18144 } 18145 18146 void Sema::ActOnStartFunctionDeclarationDeclarator( 18147 Declarator &Declarator, unsigned TemplateParameterDepth) { 18148 auto &Info = InventedParameterInfos.emplace_back(); 18149 TemplateParameterList *ExplicitParams = nullptr; 18150 ArrayRef<TemplateParameterList *> ExplicitLists = 18151 Declarator.getTemplateParameterLists(); 18152 if (!ExplicitLists.empty()) { 18153 bool IsMemberSpecialization, IsInvalid; 18154 ExplicitParams = MatchTemplateParametersToScopeSpecifier( 18155 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), 18156 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, 18157 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, 18158 /*SuppressDiagnostic=*/true); 18159 } 18160 if (ExplicitParams) { 18161 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); 18162 for (NamedDecl *Param : *ExplicitParams) 18163 Info.TemplateParams.push_back(Param); 18164 Info.NumExplicitTemplateParams = ExplicitParams->size(); 18165 } else { 18166 Info.AutoTemplateParameterDepth = TemplateParameterDepth; 18167 Info.NumExplicitTemplateParams = 0; 18168 } 18169 } 18170 18171 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { 18172 auto &FSI = InventedParameterInfos.back(); 18173 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { 18174 if (FSI.NumExplicitTemplateParams != 0) { 18175 TemplateParameterList *ExplicitParams = 18176 Declarator.getTemplateParameterLists().back(); 18177 Declarator.setInventedTemplateParameterList( 18178 TemplateParameterList::Create( 18179 Context, ExplicitParams->getTemplateLoc(), 18180 ExplicitParams->getLAngleLoc(), FSI.TemplateParams, 18181 ExplicitParams->getRAngleLoc(), 18182 ExplicitParams->getRequiresClause())); 18183 } else { 18184 Declarator.setInventedTemplateParameterList( 18185 TemplateParameterList::Create( 18186 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, 18187 SourceLocation(), /*RequiresClause=*/nullptr)); 18188 } 18189 } 18190 InventedParameterInfos.pop_back(); 18191 } 18192