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::AttributedStmtClass: 2054 // Attributes on a statement don't affect its formal kind and hence don't 2055 // affect its validity in a constexpr function. 2056 return CheckConstexprFunctionStmt(SemaRef, Dcl, 2057 cast<AttributedStmt>(S)->getSubStmt(), 2058 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind); 2059 2060 case Stmt::CompoundStmtClass: { 2061 // C++1y allows compound-statements. 2062 if (!Cxx1yLoc.isValid()) 2063 Cxx1yLoc = S->getBeginLoc(); 2064 2065 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2066 for (auto *BodyIt : CompStmt->body()) { 2067 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2068 Cxx1yLoc, Cxx2aLoc, Kind)) 2069 return false; 2070 } 2071 return true; 2072 } 2073 2074 case Stmt::IfStmtClass: { 2075 // C++1y allows if-statements. 2076 if (!Cxx1yLoc.isValid()) 2077 Cxx1yLoc = S->getBeginLoc(); 2078 2079 IfStmt *If = cast<IfStmt>(S); 2080 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2081 Cxx1yLoc, Cxx2aLoc, Kind)) 2082 return false; 2083 if (If->getElse() && 2084 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2085 Cxx1yLoc, Cxx2aLoc, Kind)) 2086 return false; 2087 return true; 2088 } 2089 2090 case Stmt::WhileStmtClass: 2091 case Stmt::DoStmtClass: 2092 case Stmt::ForStmtClass: 2093 case Stmt::CXXForRangeStmtClass: 2094 case Stmt::ContinueStmtClass: 2095 // C++1y allows all of these. We don't allow them as extensions in C++11, 2096 // because they don't make sense without variable mutation. 2097 if (!SemaRef.getLangOpts().CPlusPlus14) 2098 break; 2099 if (!Cxx1yLoc.isValid()) 2100 Cxx1yLoc = S->getBeginLoc(); 2101 for (Stmt *SubStmt : S->children()) 2102 if (SubStmt && 2103 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2104 Cxx1yLoc, Cxx2aLoc, Kind)) 2105 return false; 2106 return true; 2107 2108 case Stmt::SwitchStmtClass: 2109 case Stmt::CaseStmtClass: 2110 case Stmt::DefaultStmtClass: 2111 case Stmt::BreakStmtClass: 2112 // C++1y allows switch-statements, and since they don't need variable 2113 // mutation, we can reasonably allow them in C++11 as an extension. 2114 if (!Cxx1yLoc.isValid()) 2115 Cxx1yLoc = S->getBeginLoc(); 2116 for (Stmt *SubStmt : S->children()) 2117 if (SubStmt && 2118 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2119 Cxx1yLoc, Cxx2aLoc, Kind)) 2120 return false; 2121 return true; 2122 2123 case Stmt::GCCAsmStmtClass: 2124 case Stmt::MSAsmStmtClass: 2125 // C++2a allows inline assembly statements. 2126 case Stmt::CXXTryStmtClass: 2127 if (Cxx2aLoc.isInvalid()) 2128 Cxx2aLoc = S->getBeginLoc(); 2129 for (Stmt *SubStmt : S->children()) { 2130 if (SubStmt && 2131 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2132 Cxx1yLoc, Cxx2aLoc, Kind)) 2133 return false; 2134 } 2135 return true; 2136 2137 case Stmt::CXXCatchStmtClass: 2138 // Do not bother checking the language mode (already covered by the 2139 // try block check). 2140 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2141 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2142 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2143 return false; 2144 return true; 2145 2146 default: 2147 if (!isa<Expr>(S)) 2148 break; 2149 2150 // C++1y allows expression-statements. 2151 if (!Cxx1yLoc.isValid()) 2152 Cxx1yLoc = S->getBeginLoc(); 2153 return true; 2154 } 2155 2156 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2157 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2158 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2159 } 2160 return false; 2161 } 2162 2163 /// Check the body for the given constexpr function declaration only contains 2164 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2165 /// 2166 /// \return true if the body is OK, false if we have found or diagnosed a 2167 /// problem. 2168 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2169 Stmt *Body, 2170 Sema::CheckConstexprKind Kind) { 2171 SmallVector<SourceLocation, 4> ReturnStmts; 2172 2173 if (isa<CXXTryStmt>(Body)) { 2174 // C++11 [dcl.constexpr]p3: 2175 // The definition of a constexpr function shall satisfy the following 2176 // constraints: [...] 2177 // - its function-body shall be = delete, = default, or a 2178 // compound-statement 2179 // 2180 // C++11 [dcl.constexpr]p4: 2181 // In the definition of a constexpr constructor, [...] 2182 // - its function-body shall not be a function-try-block; 2183 // 2184 // This restriction is lifted in C++2a, as long as inner statements also 2185 // apply the general constexpr rules. 2186 switch (Kind) { 2187 case Sema::CheckConstexprKind::CheckValid: 2188 if (!SemaRef.getLangOpts().CPlusPlus20) 2189 return false; 2190 break; 2191 2192 case Sema::CheckConstexprKind::Diagnose: 2193 SemaRef.Diag(Body->getBeginLoc(), 2194 !SemaRef.getLangOpts().CPlusPlus20 2195 ? diag::ext_constexpr_function_try_block_cxx20 2196 : diag::warn_cxx17_compat_constexpr_function_try_block) 2197 << isa<CXXConstructorDecl>(Dcl); 2198 break; 2199 } 2200 } 2201 2202 // - its function-body shall be [...] a compound-statement that contains only 2203 // [... list of cases ...] 2204 // 2205 // Note that walking the children here is enough to properly check for 2206 // CompoundStmt and CXXTryStmt body. 2207 SourceLocation Cxx1yLoc, Cxx2aLoc; 2208 for (Stmt *SubStmt : Body->children()) { 2209 if (SubStmt && 2210 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2211 Cxx1yLoc, Cxx2aLoc, Kind)) 2212 return false; 2213 } 2214 2215 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2216 // If this is only valid as an extension, report that we don't satisfy the 2217 // constraints of the current language. 2218 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) || 2219 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2220 return false; 2221 } else if (Cxx2aLoc.isValid()) { 2222 SemaRef.Diag(Cxx2aLoc, 2223 SemaRef.getLangOpts().CPlusPlus20 2224 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2225 : diag::ext_constexpr_body_invalid_stmt_cxx20) 2226 << isa<CXXConstructorDecl>(Dcl); 2227 } else if (Cxx1yLoc.isValid()) { 2228 SemaRef.Diag(Cxx1yLoc, 2229 SemaRef.getLangOpts().CPlusPlus14 2230 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2231 : diag::ext_constexpr_body_invalid_stmt) 2232 << isa<CXXConstructorDecl>(Dcl); 2233 } 2234 2235 if (const CXXConstructorDecl *Constructor 2236 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2237 const CXXRecordDecl *RD = Constructor->getParent(); 2238 // DR1359: 2239 // - every non-variant non-static data member and base class sub-object 2240 // shall be initialized; 2241 // DR1460: 2242 // - if the class is a union having variant members, exactly one of them 2243 // shall be initialized; 2244 if (RD->isUnion()) { 2245 if (Constructor->getNumCtorInitializers() == 0 && 2246 RD->hasVariantMembers()) { 2247 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2248 SemaRef.Diag( 2249 Dcl->getLocation(), 2250 SemaRef.getLangOpts().CPlusPlus20 2251 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2252 : diag::ext_constexpr_union_ctor_no_init); 2253 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2254 return false; 2255 } 2256 } 2257 } else if (!Constructor->isDependentContext() && 2258 !Constructor->isDelegatingConstructor()) { 2259 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2260 2261 // Skip detailed checking if we have enough initializers, and we would 2262 // allow at most one initializer per member. 2263 bool AnyAnonStructUnionMembers = false; 2264 unsigned Fields = 0; 2265 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2266 E = RD->field_end(); I != E; ++I, ++Fields) { 2267 if (I->isAnonymousStructOrUnion()) { 2268 AnyAnonStructUnionMembers = true; 2269 break; 2270 } 2271 } 2272 // DR1460: 2273 // - if the class is a union-like class, but is not a union, for each of 2274 // its anonymous union members having variant members, exactly one of 2275 // them shall be initialized; 2276 if (AnyAnonStructUnionMembers || 2277 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2278 // Check initialization of non-static data members. Base classes are 2279 // always initialized so do not need to be checked. Dependent bases 2280 // might not have initializers in the member initializer list. 2281 llvm::SmallSet<Decl*, 16> Inits; 2282 for (const auto *I: Constructor->inits()) { 2283 if (FieldDecl *FD = I->getMember()) 2284 Inits.insert(FD); 2285 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2286 Inits.insert(ID->chain_begin(), ID->chain_end()); 2287 } 2288 2289 bool Diagnosed = false; 2290 for (auto *I : RD->fields()) 2291 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2292 Kind)) 2293 return false; 2294 } 2295 } 2296 } else { 2297 if (ReturnStmts.empty()) { 2298 // C++1y doesn't require constexpr functions to contain a 'return' 2299 // statement. We still do, unless the return type might be void, because 2300 // otherwise if there's no return statement, the function cannot 2301 // be used in a core constant expression. 2302 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2303 (Dcl->getReturnType()->isVoidType() || 2304 Dcl->getReturnType()->isDependentType()); 2305 switch (Kind) { 2306 case Sema::CheckConstexprKind::Diagnose: 2307 SemaRef.Diag(Dcl->getLocation(), 2308 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2309 : diag::err_constexpr_body_no_return) 2310 << Dcl->isConsteval(); 2311 if (!OK) 2312 return false; 2313 break; 2314 2315 case Sema::CheckConstexprKind::CheckValid: 2316 // The formal requirements don't include this rule in C++14, even 2317 // though the "must be able to produce a constant expression" rules 2318 // still imply it in some cases. 2319 if (!SemaRef.getLangOpts().CPlusPlus14) 2320 return false; 2321 break; 2322 } 2323 } else if (ReturnStmts.size() > 1) { 2324 switch (Kind) { 2325 case Sema::CheckConstexprKind::Diagnose: 2326 SemaRef.Diag( 2327 ReturnStmts.back(), 2328 SemaRef.getLangOpts().CPlusPlus14 2329 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2330 : diag::ext_constexpr_body_multiple_return); 2331 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2332 SemaRef.Diag(ReturnStmts[I], 2333 diag::note_constexpr_body_previous_return); 2334 break; 2335 2336 case Sema::CheckConstexprKind::CheckValid: 2337 if (!SemaRef.getLangOpts().CPlusPlus14) 2338 return false; 2339 break; 2340 } 2341 } 2342 } 2343 2344 // C++11 [dcl.constexpr]p5: 2345 // if no function argument values exist such that the function invocation 2346 // substitution would produce a constant expression, the program is 2347 // ill-formed; no diagnostic required. 2348 // C++11 [dcl.constexpr]p3: 2349 // - every constructor call and implicit conversion used in initializing the 2350 // return value shall be one of those allowed in a constant expression. 2351 // C++11 [dcl.constexpr]p4: 2352 // - every constructor involved in initializing non-static data members and 2353 // base class sub-objects shall be a constexpr constructor. 2354 // 2355 // Note that this rule is distinct from the "requirements for a constexpr 2356 // function", so is not checked in CheckValid mode. 2357 SmallVector<PartialDiagnosticAt, 8> Diags; 2358 if (Kind == Sema::CheckConstexprKind::Diagnose && 2359 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2360 SemaRef.Diag(Dcl->getLocation(), 2361 diag::ext_constexpr_function_never_constant_expr) 2362 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2363 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2364 SemaRef.Diag(Diags[I].first, Diags[I].second); 2365 // Don't return false here: we allow this for compatibility in 2366 // system headers. 2367 } 2368 2369 return true; 2370 } 2371 2372 /// Get the class that is directly named by the current context. This is the 2373 /// class for which an unqualified-id in this scope could name a constructor 2374 /// or destructor. 2375 /// 2376 /// If the scope specifier denotes a class, this will be that class. 2377 /// If the scope specifier is empty, this will be the class whose 2378 /// member-specification we are currently within. Otherwise, there 2379 /// is no such class. 2380 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2381 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2382 2383 if (SS && SS->isInvalid()) 2384 return nullptr; 2385 2386 if (SS && SS->isNotEmpty()) { 2387 DeclContext *DC = computeDeclContext(*SS, true); 2388 return dyn_cast_or_null<CXXRecordDecl>(DC); 2389 } 2390 2391 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2392 } 2393 2394 /// isCurrentClassName - Determine whether the identifier II is the 2395 /// name of the class type currently being defined. In the case of 2396 /// nested classes, this will only return true if II is the name of 2397 /// the innermost class. 2398 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2399 const CXXScopeSpec *SS) { 2400 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2401 return CurDecl && &II == CurDecl->getIdentifier(); 2402 } 2403 2404 /// Determine whether the identifier II is a typo for the name of 2405 /// the class type currently being defined. If so, update it to the identifier 2406 /// that should have been used. 2407 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2408 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2409 2410 if (!getLangOpts().SpellChecking) 2411 return false; 2412 2413 CXXRecordDecl *CurDecl; 2414 if (SS && SS->isSet() && !SS->isInvalid()) { 2415 DeclContext *DC = computeDeclContext(*SS, true); 2416 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2417 } else 2418 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2419 2420 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2421 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2422 < II->getLength()) { 2423 II = CurDecl->getIdentifier(); 2424 return true; 2425 } 2426 2427 return false; 2428 } 2429 2430 /// Determine whether the given class is a base class of the given 2431 /// class, including looking at dependent bases. 2432 static bool findCircularInheritance(const CXXRecordDecl *Class, 2433 const CXXRecordDecl *Current) { 2434 SmallVector<const CXXRecordDecl*, 8> Queue; 2435 2436 Class = Class->getCanonicalDecl(); 2437 while (true) { 2438 for (const auto &I : Current->bases()) { 2439 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2440 if (!Base) 2441 continue; 2442 2443 Base = Base->getDefinition(); 2444 if (!Base) 2445 continue; 2446 2447 if (Base->getCanonicalDecl() == Class) 2448 return true; 2449 2450 Queue.push_back(Base); 2451 } 2452 2453 if (Queue.empty()) 2454 return false; 2455 2456 Current = Queue.pop_back_val(); 2457 } 2458 2459 return false; 2460 } 2461 2462 /// Check the validity of a C++ base class specifier. 2463 /// 2464 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2465 /// and returns NULL otherwise. 2466 CXXBaseSpecifier * 2467 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2468 SourceRange SpecifierRange, 2469 bool Virtual, AccessSpecifier Access, 2470 TypeSourceInfo *TInfo, 2471 SourceLocation EllipsisLoc) { 2472 QualType BaseType = TInfo->getType(); 2473 if (BaseType->containsErrors()) { 2474 // Already emitted a diagnostic when parsing the error type. 2475 return nullptr; 2476 } 2477 // C++ [class.union]p1: 2478 // A union shall not have base classes. 2479 if (Class->isUnion()) { 2480 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2481 << SpecifierRange; 2482 return nullptr; 2483 } 2484 2485 if (EllipsisLoc.isValid() && 2486 !TInfo->getType()->containsUnexpandedParameterPack()) { 2487 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2488 << TInfo->getTypeLoc().getSourceRange(); 2489 EllipsisLoc = SourceLocation(); 2490 } 2491 2492 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2493 2494 if (BaseType->isDependentType()) { 2495 // Make sure that we don't have circular inheritance among our dependent 2496 // bases. For non-dependent bases, the check for completeness below handles 2497 // this. 2498 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2499 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2500 ((BaseDecl = BaseDecl->getDefinition()) && 2501 findCircularInheritance(Class, BaseDecl))) { 2502 Diag(BaseLoc, diag::err_circular_inheritance) 2503 << BaseType << Context.getTypeDeclType(Class); 2504 2505 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2506 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2507 << BaseType; 2508 2509 return nullptr; 2510 } 2511 } 2512 2513 // Make sure that we don't make an ill-formed AST where the type of the 2514 // Class is non-dependent and its attached base class specifier is an 2515 // dependent type, which violates invariants in many clang code paths (e.g. 2516 // constexpr evaluator). If this case happens (in errory-recovery mode), we 2517 // explicitly mark the Class decl invalid. The diagnostic was already 2518 // emitted. 2519 if (!Class->getTypeForDecl()->isDependentType()) 2520 Class->setInvalidDecl(); 2521 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2522 Class->getTagKind() == TTK_Class, 2523 Access, TInfo, EllipsisLoc); 2524 } 2525 2526 // Base specifiers must be record types. 2527 if (!BaseType->isRecordType()) { 2528 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2529 return nullptr; 2530 } 2531 2532 // C++ [class.union]p1: 2533 // A union shall not be used as a base class. 2534 if (BaseType->isUnionType()) { 2535 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2536 return nullptr; 2537 } 2538 2539 // For the MS ABI, propagate DLL attributes to base class templates. 2540 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2541 if (Attr *ClassAttr = getDLLAttr(Class)) { 2542 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2543 BaseType->getAsCXXRecordDecl())) { 2544 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2545 BaseLoc); 2546 } 2547 } 2548 } 2549 2550 // C++ [class.derived]p2: 2551 // The class-name in a base-specifier shall not be an incompletely 2552 // defined class. 2553 if (RequireCompleteType(BaseLoc, BaseType, 2554 diag::err_incomplete_base_class, SpecifierRange)) { 2555 Class->setInvalidDecl(); 2556 return nullptr; 2557 } 2558 2559 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2560 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2561 assert(BaseDecl && "Record type has no declaration"); 2562 BaseDecl = BaseDecl->getDefinition(); 2563 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2564 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2565 assert(CXXBaseDecl && "Base type is not a C++ type"); 2566 2567 // Microsoft docs say: 2568 // "If a base-class has a code_seg attribute, derived classes must have the 2569 // same attribute." 2570 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2571 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2572 if ((DerivedCSA || BaseCSA) && 2573 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2574 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2575 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2576 << CXXBaseDecl; 2577 return nullptr; 2578 } 2579 2580 // A class which contains a flexible array member is not suitable for use as a 2581 // base class: 2582 // - If the layout determines that a base comes before another base, 2583 // the flexible array member would index into the subsequent base. 2584 // - If the layout determines that base comes before the derived class, 2585 // the flexible array member would index into the derived class. 2586 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2587 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2588 << CXXBaseDecl->getDeclName(); 2589 return nullptr; 2590 } 2591 2592 // C++ [class]p3: 2593 // If a class is marked final and it appears as a base-type-specifier in 2594 // base-clause, the program is ill-formed. 2595 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2596 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2597 << CXXBaseDecl->getDeclName() 2598 << FA->isSpelledAsSealed(); 2599 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2600 << CXXBaseDecl->getDeclName() << FA->getRange(); 2601 return nullptr; 2602 } 2603 2604 if (BaseDecl->isInvalidDecl()) 2605 Class->setInvalidDecl(); 2606 2607 // Create the base specifier. 2608 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2609 Class->getTagKind() == TTK_Class, 2610 Access, TInfo, EllipsisLoc); 2611 } 2612 2613 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2614 /// one entry in the base class list of a class specifier, for 2615 /// example: 2616 /// class foo : public bar, virtual private baz { 2617 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2618 BaseResult 2619 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2620 ParsedAttributes &Attributes, 2621 bool Virtual, AccessSpecifier Access, 2622 ParsedType basetype, SourceLocation BaseLoc, 2623 SourceLocation EllipsisLoc) { 2624 if (!classdecl) 2625 return true; 2626 2627 AdjustDeclIfTemplate(classdecl); 2628 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2629 if (!Class) 2630 return true; 2631 2632 // We haven't yet attached the base specifiers. 2633 Class->setIsParsingBaseSpecifiers(); 2634 2635 // We do not support any C++11 attributes on base-specifiers yet. 2636 // Diagnose any attributes we see. 2637 for (const ParsedAttr &AL : Attributes) { 2638 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2639 continue; 2640 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2641 ? (unsigned)diag::warn_unknown_attribute_ignored 2642 : (unsigned)diag::err_base_specifier_attribute) 2643 << AL << AL.getRange(); 2644 } 2645 2646 TypeSourceInfo *TInfo = nullptr; 2647 GetTypeFromParser(basetype, &TInfo); 2648 2649 if (EllipsisLoc.isInvalid() && 2650 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2651 UPPC_BaseType)) 2652 return true; 2653 2654 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2655 Virtual, Access, TInfo, 2656 EllipsisLoc)) 2657 return BaseSpec; 2658 else 2659 Class->setInvalidDecl(); 2660 2661 return true; 2662 } 2663 2664 /// Use small set to collect indirect bases. As this is only used 2665 /// locally, there's no need to abstract the small size parameter. 2666 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2667 2668 /// Recursively add the bases of Type. Don't add Type itself. 2669 static void 2670 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2671 const QualType &Type) 2672 { 2673 // Even though the incoming type is a base, it might not be 2674 // a class -- it could be a template parm, for instance. 2675 if (auto Rec = Type->getAs<RecordType>()) { 2676 auto Decl = Rec->getAsCXXRecordDecl(); 2677 2678 // Iterate over its bases. 2679 for (const auto &BaseSpec : Decl->bases()) { 2680 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2681 .getUnqualifiedType(); 2682 if (Set.insert(Base).second) 2683 // If we've not already seen it, recurse. 2684 NoteIndirectBases(Context, Set, Base); 2685 } 2686 } 2687 } 2688 2689 /// Performs the actual work of attaching the given base class 2690 /// specifiers to a C++ class. 2691 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2692 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2693 if (Bases.empty()) 2694 return false; 2695 2696 // Used to keep track of which base types we have already seen, so 2697 // that we can properly diagnose redundant direct base types. Note 2698 // that the key is always the unqualified canonical type of the base 2699 // class. 2700 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2701 2702 // Used to track indirect bases so we can see if a direct base is 2703 // ambiguous. 2704 IndirectBaseSet IndirectBaseTypes; 2705 2706 // Copy non-redundant base specifiers into permanent storage. 2707 unsigned NumGoodBases = 0; 2708 bool Invalid = false; 2709 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2710 QualType NewBaseType 2711 = Context.getCanonicalType(Bases[idx]->getType()); 2712 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2713 2714 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2715 if (KnownBase) { 2716 // C++ [class.mi]p3: 2717 // A class shall not be specified as a direct base class of a 2718 // derived class more than once. 2719 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2720 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2721 2722 // Delete the duplicate base class specifier; we're going to 2723 // overwrite its pointer later. 2724 Context.Deallocate(Bases[idx]); 2725 2726 Invalid = true; 2727 } else { 2728 // Okay, add this new base class. 2729 KnownBase = Bases[idx]; 2730 Bases[NumGoodBases++] = Bases[idx]; 2731 2732 // Note this base's direct & indirect bases, if there could be ambiguity. 2733 if (Bases.size() > 1) 2734 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2735 2736 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2737 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2738 if (Class->isInterface() && 2739 (!RD->isInterfaceLike() || 2740 KnownBase->getAccessSpecifier() != AS_public)) { 2741 // The Microsoft extension __interface does not permit bases that 2742 // are not themselves public interfaces. 2743 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2744 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2745 << RD->getSourceRange(); 2746 Invalid = true; 2747 } 2748 if (RD->hasAttr<WeakAttr>()) 2749 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2750 } 2751 } 2752 } 2753 2754 // Attach the remaining base class specifiers to the derived class. 2755 Class->setBases(Bases.data(), NumGoodBases); 2756 2757 // Check that the only base classes that are duplicate are virtual. 2758 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2759 // Check whether this direct base is inaccessible due to ambiguity. 2760 QualType BaseType = Bases[idx]->getType(); 2761 2762 // Skip all dependent types in templates being used as base specifiers. 2763 // Checks below assume that the base specifier is a CXXRecord. 2764 if (BaseType->isDependentType()) 2765 continue; 2766 2767 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2768 .getUnqualifiedType(); 2769 2770 if (IndirectBaseTypes.count(CanonicalBase)) { 2771 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2772 /*DetectVirtual=*/true); 2773 bool found 2774 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2775 assert(found); 2776 (void)found; 2777 2778 if (Paths.isAmbiguous(CanonicalBase)) 2779 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2780 << BaseType << getAmbiguousPathsDisplayString(Paths) 2781 << Bases[idx]->getSourceRange(); 2782 else 2783 assert(Bases[idx]->isVirtual()); 2784 } 2785 2786 // Delete the base class specifier, since its data has been copied 2787 // into the CXXRecordDecl. 2788 Context.Deallocate(Bases[idx]); 2789 } 2790 2791 return Invalid; 2792 } 2793 2794 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2795 /// class, after checking whether there are any duplicate base 2796 /// classes. 2797 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2798 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2799 if (!ClassDecl || Bases.empty()) 2800 return; 2801 2802 AdjustDeclIfTemplate(ClassDecl); 2803 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2804 } 2805 2806 /// Determine whether the type \p Derived is a C++ class that is 2807 /// derived from the type \p Base. 2808 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2809 if (!getLangOpts().CPlusPlus) 2810 return false; 2811 2812 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2813 if (!DerivedRD) 2814 return false; 2815 2816 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2817 if (!BaseRD) 2818 return false; 2819 2820 // If either the base or the derived type is invalid, don't try to 2821 // check whether one is derived from the other. 2822 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2823 return false; 2824 2825 // FIXME: In a modules build, do we need the entire path to be visible for us 2826 // to be able to use the inheritance relationship? 2827 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2828 return false; 2829 2830 return DerivedRD->isDerivedFrom(BaseRD); 2831 } 2832 2833 /// Determine whether the type \p Derived is a C++ class that is 2834 /// derived from the type \p Base. 2835 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2836 CXXBasePaths &Paths) { 2837 if (!getLangOpts().CPlusPlus) 2838 return false; 2839 2840 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2841 if (!DerivedRD) 2842 return false; 2843 2844 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2845 if (!BaseRD) 2846 return false; 2847 2848 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2849 return false; 2850 2851 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2852 } 2853 2854 static void BuildBasePathArray(const CXXBasePath &Path, 2855 CXXCastPath &BasePathArray) { 2856 // We first go backward and check if we have a virtual base. 2857 // FIXME: It would be better if CXXBasePath had the base specifier for 2858 // the nearest virtual base. 2859 unsigned Start = 0; 2860 for (unsigned I = Path.size(); I != 0; --I) { 2861 if (Path[I - 1].Base->isVirtual()) { 2862 Start = I - 1; 2863 break; 2864 } 2865 } 2866 2867 // Now add all bases. 2868 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2869 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2870 } 2871 2872 2873 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2874 CXXCastPath &BasePathArray) { 2875 assert(BasePathArray.empty() && "Base path array must be empty!"); 2876 assert(Paths.isRecordingPaths() && "Must record paths!"); 2877 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2878 } 2879 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2880 /// conversion (where Derived and Base are class types) is 2881 /// well-formed, meaning that the conversion is unambiguous (and 2882 /// that all of the base classes are accessible). Returns true 2883 /// and emits a diagnostic if the code is ill-formed, returns false 2884 /// otherwise. Loc is the location where this routine should point to 2885 /// if there is an error, and Range is the source range to highlight 2886 /// if there is an error. 2887 /// 2888 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the 2889 /// diagnostic for the respective type of error will be suppressed, but the 2890 /// check for ill-formed code will still be performed. 2891 bool 2892 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2893 unsigned InaccessibleBaseID, 2894 unsigned AmbiguousBaseConvID, 2895 SourceLocation Loc, SourceRange Range, 2896 DeclarationName Name, 2897 CXXCastPath *BasePath, 2898 bool IgnoreAccess) { 2899 // First, determine whether the path from Derived to Base is 2900 // ambiguous. This is slightly more expensive than checking whether 2901 // the Derived to Base conversion exists, because here we need to 2902 // explore multiple paths to determine if there is an ambiguity. 2903 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2904 /*DetectVirtual=*/false); 2905 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2906 if (!DerivationOkay) 2907 return true; 2908 2909 const CXXBasePath *Path = nullptr; 2910 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2911 Path = &Paths.front(); 2912 2913 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2914 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2915 // user to access such bases. 2916 if (!Path && getLangOpts().MSVCCompat) { 2917 for (const CXXBasePath &PossiblePath : Paths) { 2918 if (PossiblePath.size() == 1) { 2919 Path = &PossiblePath; 2920 if (AmbiguousBaseConvID) 2921 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2922 << Base << Derived << Range; 2923 break; 2924 } 2925 } 2926 } 2927 2928 if (Path) { 2929 if (!IgnoreAccess) { 2930 // Check that the base class can be accessed. 2931 switch ( 2932 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2933 case AR_inaccessible: 2934 return true; 2935 case AR_accessible: 2936 case AR_dependent: 2937 case AR_delayed: 2938 break; 2939 } 2940 } 2941 2942 // Build a base path if necessary. 2943 if (BasePath) 2944 ::BuildBasePathArray(*Path, *BasePath); 2945 return false; 2946 } 2947 2948 if (AmbiguousBaseConvID) { 2949 // We know that the derived-to-base conversion is ambiguous, and 2950 // we're going to produce a diagnostic. Perform the derived-to-base 2951 // search just one more time to compute all of the possible paths so 2952 // that we can print them out. This is more expensive than any of 2953 // the previous derived-to-base checks we've done, but at this point 2954 // performance isn't as much of an issue. 2955 Paths.clear(); 2956 Paths.setRecordingPaths(true); 2957 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2958 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2959 (void)StillOkay; 2960 2961 // Build up a textual representation of the ambiguous paths, e.g., 2962 // D -> B -> A, that will be used to illustrate the ambiguous 2963 // conversions in the diagnostic. We only print one of the paths 2964 // to each base class subobject. 2965 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2966 2967 Diag(Loc, AmbiguousBaseConvID) 2968 << Derived << Base << PathDisplayStr << Range << Name; 2969 } 2970 return true; 2971 } 2972 2973 bool 2974 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2975 SourceLocation Loc, SourceRange Range, 2976 CXXCastPath *BasePath, 2977 bool IgnoreAccess) { 2978 return CheckDerivedToBaseConversion( 2979 Derived, Base, diag::err_upcast_to_inaccessible_base, 2980 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2981 BasePath, IgnoreAccess); 2982 } 2983 2984 2985 /// Builds a string representing ambiguous paths from a 2986 /// specific derived class to different subobjects of the same base 2987 /// class. 2988 /// 2989 /// This function builds a string that can be used in error messages 2990 /// to show the different paths that one can take through the 2991 /// inheritance hierarchy to go from the derived class to different 2992 /// subobjects of a base class. The result looks something like this: 2993 /// @code 2994 /// struct D -> struct B -> struct A 2995 /// struct D -> struct C -> struct A 2996 /// @endcode 2997 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2998 std::string PathDisplayStr; 2999 std::set<unsigned> DisplayedPaths; 3000 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3001 Path != Paths.end(); ++Path) { 3002 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 3003 // We haven't displayed a path to this particular base 3004 // class subobject yet. 3005 PathDisplayStr += "\n "; 3006 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 3007 for (CXXBasePath::const_iterator Element = Path->begin(); 3008 Element != Path->end(); ++Element) 3009 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 3010 } 3011 } 3012 3013 return PathDisplayStr; 3014 } 3015 3016 //===----------------------------------------------------------------------===// 3017 // C++ class member Handling 3018 //===----------------------------------------------------------------------===// 3019 3020 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 3021 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 3022 SourceLocation ColonLoc, 3023 const ParsedAttributesView &Attrs) { 3024 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 3025 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 3026 ASLoc, ColonLoc); 3027 CurContext->addHiddenDecl(ASDecl); 3028 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 3029 } 3030 3031 /// CheckOverrideControl - Check C++11 override control semantics. 3032 void Sema::CheckOverrideControl(NamedDecl *D) { 3033 if (D->isInvalidDecl()) 3034 return; 3035 3036 // We only care about "override" and "final" declarations. 3037 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 3038 return; 3039 3040 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3041 3042 // We can't check dependent instance methods. 3043 if (MD && MD->isInstance() && 3044 (MD->getParent()->hasAnyDependentBases() || 3045 MD->getType()->isDependentType())) 3046 return; 3047 3048 if (MD && !MD->isVirtual()) { 3049 // If we have a non-virtual method, check if if hides a virtual method. 3050 // (In that case, it's most likely the method has the wrong type.) 3051 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 3052 FindHiddenVirtualMethods(MD, OverloadedMethods); 3053 3054 if (!OverloadedMethods.empty()) { 3055 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3056 Diag(OA->getLocation(), 3057 diag::override_keyword_hides_virtual_member_function) 3058 << "override" << (OverloadedMethods.size() > 1); 3059 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3060 Diag(FA->getLocation(), 3061 diag::override_keyword_hides_virtual_member_function) 3062 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3063 << (OverloadedMethods.size() > 1); 3064 } 3065 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3066 MD->setInvalidDecl(); 3067 return; 3068 } 3069 // Fall through into the general case diagnostic. 3070 // FIXME: We might want to attempt typo correction here. 3071 } 3072 3073 if (!MD || !MD->isVirtual()) { 3074 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3075 Diag(OA->getLocation(), 3076 diag::override_keyword_only_allowed_on_virtual_member_functions) 3077 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3078 D->dropAttr<OverrideAttr>(); 3079 } 3080 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3081 Diag(FA->getLocation(), 3082 diag::override_keyword_only_allowed_on_virtual_member_functions) 3083 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3084 << FixItHint::CreateRemoval(FA->getLocation()); 3085 D->dropAttr<FinalAttr>(); 3086 } 3087 return; 3088 } 3089 3090 // C++11 [class.virtual]p5: 3091 // If a function is marked with the virt-specifier override and 3092 // does not override a member function of a base class, the program is 3093 // ill-formed. 3094 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3095 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3096 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3097 << MD->getDeclName(); 3098 } 3099 3100 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { 3101 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3102 return; 3103 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3104 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3105 return; 3106 3107 SourceLocation Loc = MD->getLocation(); 3108 SourceLocation SpellingLoc = Loc; 3109 if (getSourceManager().isMacroArgExpansion(Loc)) 3110 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3111 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3112 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3113 return; 3114 3115 if (MD->size_overridden_methods() > 0) { 3116 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { 3117 unsigned DiagID = 3118 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation()) 3119 ? DiagInconsistent 3120 : DiagSuggest; 3121 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3122 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3123 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3124 }; 3125 if (isa<CXXDestructorDecl>(MD)) 3126 EmitDiag( 3127 diag::warn_inconsistent_destructor_marked_not_override_overriding, 3128 diag::warn_suggest_destructor_marked_not_override_overriding); 3129 else 3130 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding, 3131 diag::warn_suggest_function_marked_not_override_overriding); 3132 } 3133 } 3134 3135 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3136 /// function overrides a virtual member function marked 'final', according to 3137 /// C++11 [class.virtual]p4. 3138 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3139 const CXXMethodDecl *Old) { 3140 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3141 if (!FA) 3142 return false; 3143 3144 Diag(New->getLocation(), diag::err_final_function_overridden) 3145 << New->getDeclName() 3146 << FA->isSpelledAsSealed(); 3147 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3148 return true; 3149 } 3150 3151 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3152 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3153 // FIXME: Destruction of ObjC lifetime types has side-effects. 3154 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3155 return !RD->isCompleteDefinition() || 3156 !RD->hasTrivialDefaultConstructor() || 3157 !RD->hasTrivialDestructor(); 3158 return false; 3159 } 3160 3161 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3162 ParsedAttributesView::const_iterator Itr = 3163 llvm::find_if(list, [](const ParsedAttr &AL) { 3164 return AL.isDeclspecPropertyAttribute(); 3165 }); 3166 if (Itr != list.end()) 3167 return &*Itr; 3168 return nullptr; 3169 } 3170 3171 // Check if there is a field shadowing. 3172 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3173 DeclarationName FieldName, 3174 const CXXRecordDecl *RD, 3175 bool DeclIsField) { 3176 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3177 return; 3178 3179 // To record a shadowed field in a base 3180 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3181 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3182 CXXBasePath &Path) { 3183 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3184 // Record an ambiguous path directly 3185 if (Bases.find(Base) != Bases.end()) 3186 return true; 3187 for (const auto Field : Base->lookup(FieldName)) { 3188 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3189 Field->getAccess() != AS_private) { 3190 assert(Field->getAccess() != AS_none); 3191 assert(Bases.find(Base) == Bases.end()); 3192 Bases[Base] = Field; 3193 return true; 3194 } 3195 } 3196 return false; 3197 }; 3198 3199 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3200 /*DetectVirtual=*/true); 3201 if (!RD->lookupInBases(FieldShadowed, Paths)) 3202 return; 3203 3204 for (const auto &P : Paths) { 3205 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3206 auto It = Bases.find(Base); 3207 // Skip duplicated bases 3208 if (It == Bases.end()) 3209 continue; 3210 auto BaseField = It->second; 3211 assert(BaseField->getAccess() != AS_private); 3212 if (AS_none != 3213 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3214 Diag(Loc, diag::warn_shadow_field) 3215 << FieldName << RD << Base << DeclIsField; 3216 Diag(BaseField->getLocation(), diag::note_shadow_field); 3217 Bases.erase(It); 3218 } 3219 } 3220 } 3221 3222 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3223 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3224 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3225 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3226 /// present (but parsing it has been deferred). 3227 NamedDecl * 3228 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3229 MultiTemplateParamsArg TemplateParameterLists, 3230 Expr *BW, const VirtSpecifiers &VS, 3231 InClassInitStyle InitStyle) { 3232 const DeclSpec &DS = D.getDeclSpec(); 3233 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3234 DeclarationName Name = NameInfo.getName(); 3235 SourceLocation Loc = NameInfo.getLoc(); 3236 3237 // For anonymous bitfields, the location should point to the type. 3238 if (Loc.isInvalid()) 3239 Loc = D.getBeginLoc(); 3240 3241 Expr *BitWidth = static_cast<Expr*>(BW); 3242 3243 assert(isa<CXXRecordDecl>(CurContext)); 3244 assert(!DS.isFriendSpecified()); 3245 3246 bool isFunc = D.isDeclarationOfFunction(); 3247 const ParsedAttr *MSPropertyAttr = 3248 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3249 3250 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3251 // The Microsoft extension __interface only permits public member functions 3252 // and prohibits constructors, destructors, operators, non-public member 3253 // functions, static methods and data members. 3254 unsigned InvalidDecl; 3255 bool ShowDeclName = true; 3256 if (!isFunc && 3257 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3258 InvalidDecl = 0; 3259 else if (!isFunc) 3260 InvalidDecl = 1; 3261 else if (AS != AS_public) 3262 InvalidDecl = 2; 3263 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3264 InvalidDecl = 3; 3265 else switch (Name.getNameKind()) { 3266 case DeclarationName::CXXConstructorName: 3267 InvalidDecl = 4; 3268 ShowDeclName = false; 3269 break; 3270 3271 case DeclarationName::CXXDestructorName: 3272 InvalidDecl = 5; 3273 ShowDeclName = false; 3274 break; 3275 3276 case DeclarationName::CXXOperatorName: 3277 case DeclarationName::CXXConversionFunctionName: 3278 InvalidDecl = 6; 3279 break; 3280 3281 default: 3282 InvalidDecl = 0; 3283 break; 3284 } 3285 3286 if (InvalidDecl) { 3287 if (ShowDeclName) 3288 Diag(Loc, diag::err_invalid_member_in_interface) 3289 << (InvalidDecl-1) << Name; 3290 else 3291 Diag(Loc, diag::err_invalid_member_in_interface) 3292 << (InvalidDecl-1) << ""; 3293 return nullptr; 3294 } 3295 } 3296 3297 // C++ 9.2p6: A member shall not be declared to have automatic storage 3298 // duration (auto, register) or with the extern storage-class-specifier. 3299 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3300 // data members and cannot be applied to names declared const or static, 3301 // and cannot be applied to reference members. 3302 switch (DS.getStorageClassSpec()) { 3303 case DeclSpec::SCS_unspecified: 3304 case DeclSpec::SCS_typedef: 3305 case DeclSpec::SCS_static: 3306 break; 3307 case DeclSpec::SCS_mutable: 3308 if (isFunc) { 3309 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3310 3311 // FIXME: It would be nicer if the keyword was ignored only for this 3312 // declarator. Otherwise we could get follow-up errors. 3313 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3314 } 3315 break; 3316 default: 3317 Diag(DS.getStorageClassSpecLoc(), 3318 diag::err_storageclass_invalid_for_member); 3319 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3320 break; 3321 } 3322 3323 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3324 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3325 !isFunc); 3326 3327 if (DS.hasConstexprSpecifier() && isInstField) { 3328 SemaDiagnosticBuilder B = 3329 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3330 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3331 if (InitStyle == ICIS_NoInit) { 3332 B << 0 << 0; 3333 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3334 B << FixItHint::CreateRemoval(ConstexprLoc); 3335 else { 3336 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3337 D.getMutableDeclSpec().ClearConstexprSpec(); 3338 const char *PrevSpec; 3339 unsigned DiagID; 3340 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3341 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3342 (void)Failed; 3343 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3344 } 3345 } else { 3346 B << 1; 3347 const char *PrevSpec; 3348 unsigned DiagID; 3349 if (D.getMutableDeclSpec().SetStorageClassSpec( 3350 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3351 Context.getPrintingPolicy())) { 3352 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3353 "This is the only DeclSpec that should fail to be applied"); 3354 B << 1; 3355 } else { 3356 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3357 isInstField = false; 3358 } 3359 } 3360 } 3361 3362 NamedDecl *Member; 3363 if (isInstField) { 3364 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3365 3366 // Data members must have identifiers for names. 3367 if (!Name.isIdentifier()) { 3368 Diag(Loc, diag::err_bad_variable_name) 3369 << Name; 3370 return nullptr; 3371 } 3372 3373 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3374 3375 // Member field could not be with "template" keyword. 3376 // So TemplateParameterLists should be empty in this case. 3377 if (TemplateParameterLists.size()) { 3378 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3379 if (TemplateParams->size()) { 3380 // There is no such thing as a member field template. 3381 Diag(D.getIdentifierLoc(), diag::err_template_member) 3382 << II 3383 << SourceRange(TemplateParams->getTemplateLoc(), 3384 TemplateParams->getRAngleLoc()); 3385 } else { 3386 // There is an extraneous 'template<>' for this member. 3387 Diag(TemplateParams->getTemplateLoc(), 3388 diag::err_template_member_noparams) 3389 << II 3390 << SourceRange(TemplateParams->getTemplateLoc(), 3391 TemplateParams->getRAngleLoc()); 3392 } 3393 return nullptr; 3394 } 3395 3396 if (SS.isSet() && !SS.isInvalid()) { 3397 // The user provided a superfluous scope specifier inside a class 3398 // definition: 3399 // 3400 // class X { 3401 // int X::member; 3402 // }; 3403 if (DeclContext *DC = computeDeclContext(SS, false)) 3404 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3405 D.getName().getKind() == 3406 UnqualifiedIdKind::IK_TemplateId); 3407 else 3408 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3409 << Name << SS.getRange(); 3410 3411 SS.clear(); 3412 } 3413 3414 if (MSPropertyAttr) { 3415 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3416 BitWidth, InitStyle, AS, *MSPropertyAttr); 3417 if (!Member) 3418 return nullptr; 3419 isInstField = false; 3420 } else { 3421 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3422 BitWidth, InitStyle, AS); 3423 if (!Member) 3424 return nullptr; 3425 } 3426 3427 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3428 } else { 3429 Member = HandleDeclarator(S, D, TemplateParameterLists); 3430 if (!Member) 3431 return nullptr; 3432 3433 // Non-instance-fields can't have a bitfield. 3434 if (BitWidth) { 3435 if (Member->isInvalidDecl()) { 3436 // don't emit another diagnostic. 3437 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3438 // C++ 9.6p3: A bit-field shall not be a static member. 3439 // "static member 'A' cannot be a bit-field" 3440 Diag(Loc, diag::err_static_not_bitfield) 3441 << Name << BitWidth->getSourceRange(); 3442 } else if (isa<TypedefDecl>(Member)) { 3443 // "typedef member 'x' cannot be a bit-field" 3444 Diag(Loc, diag::err_typedef_not_bitfield) 3445 << Name << BitWidth->getSourceRange(); 3446 } else { 3447 // A function typedef ("typedef int f(); f a;"). 3448 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3449 Diag(Loc, diag::err_not_integral_type_bitfield) 3450 << Name << cast<ValueDecl>(Member)->getType() 3451 << BitWidth->getSourceRange(); 3452 } 3453 3454 BitWidth = nullptr; 3455 Member->setInvalidDecl(); 3456 } 3457 3458 NamedDecl *NonTemplateMember = Member; 3459 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3460 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3461 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3462 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3463 3464 Member->setAccess(AS); 3465 3466 // If we have declared a member function template or static data member 3467 // template, set the access of the templated declaration as well. 3468 if (NonTemplateMember != Member) 3469 NonTemplateMember->setAccess(AS); 3470 3471 // C++ [temp.deduct.guide]p3: 3472 // A deduction guide [...] for a member class template [shall be 3473 // declared] with the same access [as the template]. 3474 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3475 auto *TD = DG->getDeducedTemplate(); 3476 // Access specifiers are only meaningful if both the template and the 3477 // deduction guide are from the same scope. 3478 if (AS != TD->getAccess() && 3479 TD->getDeclContext()->getRedeclContext()->Equals( 3480 DG->getDeclContext()->getRedeclContext())) { 3481 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3482 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3483 << TD->getAccess(); 3484 const AccessSpecDecl *LastAccessSpec = nullptr; 3485 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3486 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3487 LastAccessSpec = AccessSpec; 3488 } 3489 assert(LastAccessSpec && "differing access with no access specifier"); 3490 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3491 << AS; 3492 } 3493 } 3494 } 3495 3496 if (VS.isOverrideSpecified()) 3497 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3498 AttributeCommonInfo::AS_Keyword)); 3499 if (VS.isFinalSpecified()) 3500 Member->addAttr(FinalAttr::Create( 3501 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3502 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3503 3504 if (VS.getLastLocation().isValid()) { 3505 // Update the end location of a method that has a virt-specifiers. 3506 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3507 MD->setRangeEnd(VS.getLastLocation()); 3508 } 3509 3510 CheckOverrideControl(Member); 3511 3512 assert((Name || isInstField) && "No identifier for non-field ?"); 3513 3514 if (isInstField) { 3515 FieldDecl *FD = cast<FieldDecl>(Member); 3516 FieldCollector->Add(FD); 3517 3518 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3519 // Remember all explicit private FieldDecls that have a name, no side 3520 // effects and are not part of a dependent type declaration. 3521 if (!FD->isImplicit() && FD->getDeclName() && 3522 FD->getAccess() == AS_private && 3523 !FD->hasAttr<UnusedAttr>() && 3524 !FD->getParent()->isDependentContext() && 3525 !InitializationHasSideEffects(*FD)) 3526 UnusedPrivateFields.insert(FD); 3527 } 3528 } 3529 3530 return Member; 3531 } 3532 3533 namespace { 3534 class UninitializedFieldVisitor 3535 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3536 Sema &S; 3537 // List of Decls to generate a warning on. Also remove Decls that become 3538 // initialized. 3539 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3540 // List of base classes of the record. Classes are removed after their 3541 // initializers. 3542 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3543 // Vector of decls to be removed from the Decl set prior to visiting the 3544 // nodes. These Decls may have been initialized in the prior initializer. 3545 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3546 // If non-null, add a note to the warning pointing back to the constructor. 3547 const CXXConstructorDecl *Constructor; 3548 // Variables to hold state when processing an initializer list. When 3549 // InitList is true, special case initialization of FieldDecls matching 3550 // InitListFieldDecl. 3551 bool InitList; 3552 FieldDecl *InitListFieldDecl; 3553 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3554 3555 public: 3556 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3557 UninitializedFieldVisitor(Sema &S, 3558 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3559 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3560 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3561 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3562 3563 // Returns true if the use of ME is not an uninitialized use. 3564 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3565 bool CheckReferenceOnly) { 3566 llvm::SmallVector<FieldDecl*, 4> Fields; 3567 bool ReferenceField = false; 3568 while (ME) { 3569 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3570 if (!FD) 3571 return false; 3572 Fields.push_back(FD); 3573 if (FD->getType()->isReferenceType()) 3574 ReferenceField = true; 3575 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3576 } 3577 3578 // Binding a reference to an uninitialized field is not an 3579 // uninitialized use. 3580 if (CheckReferenceOnly && !ReferenceField) 3581 return true; 3582 3583 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3584 // Discard the first field since it is the field decl that is being 3585 // initialized. 3586 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3587 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3588 } 3589 3590 for (auto UsedIter = UsedFieldIndex.begin(), 3591 UsedEnd = UsedFieldIndex.end(), 3592 OrigIter = InitFieldIndex.begin(), 3593 OrigEnd = InitFieldIndex.end(); 3594 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3595 if (*UsedIter < *OrigIter) 3596 return true; 3597 if (*UsedIter > *OrigIter) 3598 break; 3599 } 3600 3601 return false; 3602 } 3603 3604 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3605 bool AddressOf) { 3606 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3607 return; 3608 3609 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3610 // or union. 3611 MemberExpr *FieldME = ME; 3612 3613 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3614 3615 Expr *Base = ME; 3616 while (MemberExpr *SubME = 3617 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3618 3619 if (isa<VarDecl>(SubME->getMemberDecl())) 3620 return; 3621 3622 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3623 if (!FD->isAnonymousStructOrUnion()) 3624 FieldME = SubME; 3625 3626 if (!FieldME->getType().isPODType(S.Context)) 3627 AllPODFields = false; 3628 3629 Base = SubME->getBase(); 3630 } 3631 3632 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) { 3633 Visit(Base); 3634 return; 3635 } 3636 3637 if (AddressOf && AllPODFields) 3638 return; 3639 3640 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3641 3642 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3643 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3644 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3645 } 3646 3647 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3648 QualType T = BaseCast->getType(); 3649 if (T->isPointerType() && 3650 BaseClasses.count(T->getPointeeType())) { 3651 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3652 << T->getPointeeType() << FoundVD; 3653 } 3654 } 3655 } 3656 3657 if (!Decls.count(FoundVD)) 3658 return; 3659 3660 const bool IsReference = FoundVD->getType()->isReferenceType(); 3661 3662 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3663 // Special checking for initializer lists. 3664 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3665 return; 3666 } 3667 } else { 3668 // Prevent double warnings on use of unbounded references. 3669 if (CheckReferenceOnly && !IsReference) 3670 return; 3671 } 3672 3673 unsigned diag = IsReference 3674 ? diag::warn_reference_field_is_uninit 3675 : diag::warn_field_is_uninit; 3676 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3677 if (Constructor) 3678 S.Diag(Constructor->getLocation(), 3679 diag::note_uninit_in_this_constructor) 3680 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3681 3682 } 3683 3684 void HandleValue(Expr *E, bool AddressOf) { 3685 E = E->IgnoreParens(); 3686 3687 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3688 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3689 AddressOf /*AddressOf*/); 3690 return; 3691 } 3692 3693 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3694 Visit(CO->getCond()); 3695 HandleValue(CO->getTrueExpr(), AddressOf); 3696 HandleValue(CO->getFalseExpr(), AddressOf); 3697 return; 3698 } 3699 3700 if (BinaryConditionalOperator *BCO = 3701 dyn_cast<BinaryConditionalOperator>(E)) { 3702 Visit(BCO->getCond()); 3703 HandleValue(BCO->getFalseExpr(), AddressOf); 3704 return; 3705 } 3706 3707 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3708 HandleValue(OVE->getSourceExpr(), AddressOf); 3709 return; 3710 } 3711 3712 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3713 switch (BO->getOpcode()) { 3714 default: 3715 break; 3716 case(BO_PtrMemD): 3717 case(BO_PtrMemI): 3718 HandleValue(BO->getLHS(), AddressOf); 3719 Visit(BO->getRHS()); 3720 return; 3721 case(BO_Comma): 3722 Visit(BO->getLHS()); 3723 HandleValue(BO->getRHS(), AddressOf); 3724 return; 3725 } 3726 } 3727 3728 Visit(E); 3729 } 3730 3731 void CheckInitListExpr(InitListExpr *ILE) { 3732 InitFieldIndex.push_back(0); 3733 for (auto Child : ILE->children()) { 3734 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3735 CheckInitListExpr(SubList); 3736 } else { 3737 Visit(Child); 3738 } 3739 ++InitFieldIndex.back(); 3740 } 3741 InitFieldIndex.pop_back(); 3742 } 3743 3744 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3745 FieldDecl *Field, const Type *BaseClass) { 3746 // Remove Decls that may have been initialized in the previous 3747 // initializer. 3748 for (ValueDecl* VD : DeclsToRemove) 3749 Decls.erase(VD); 3750 DeclsToRemove.clear(); 3751 3752 Constructor = FieldConstructor; 3753 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3754 3755 if (ILE && Field) { 3756 InitList = true; 3757 InitListFieldDecl = Field; 3758 InitFieldIndex.clear(); 3759 CheckInitListExpr(ILE); 3760 } else { 3761 InitList = false; 3762 Visit(E); 3763 } 3764 3765 if (Field) 3766 Decls.erase(Field); 3767 if (BaseClass) 3768 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3769 } 3770 3771 void VisitMemberExpr(MemberExpr *ME) { 3772 // All uses of unbounded reference fields will warn. 3773 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3774 } 3775 3776 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3777 if (E->getCastKind() == CK_LValueToRValue) { 3778 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3779 return; 3780 } 3781 3782 Inherited::VisitImplicitCastExpr(E); 3783 } 3784 3785 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3786 if (E->getConstructor()->isCopyConstructor()) { 3787 Expr *ArgExpr = E->getArg(0); 3788 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3789 if (ILE->getNumInits() == 1) 3790 ArgExpr = ILE->getInit(0); 3791 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3792 if (ICE->getCastKind() == CK_NoOp) 3793 ArgExpr = ICE->getSubExpr(); 3794 HandleValue(ArgExpr, false /*AddressOf*/); 3795 return; 3796 } 3797 Inherited::VisitCXXConstructExpr(E); 3798 } 3799 3800 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3801 Expr *Callee = E->getCallee(); 3802 if (isa<MemberExpr>(Callee)) { 3803 HandleValue(Callee, false /*AddressOf*/); 3804 for (auto Arg : E->arguments()) 3805 Visit(Arg); 3806 return; 3807 } 3808 3809 Inherited::VisitCXXMemberCallExpr(E); 3810 } 3811 3812 void VisitCallExpr(CallExpr *E) { 3813 // Treat std::move as a use. 3814 if (E->isCallToStdMove()) { 3815 HandleValue(E->getArg(0), /*AddressOf=*/false); 3816 return; 3817 } 3818 3819 Inherited::VisitCallExpr(E); 3820 } 3821 3822 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3823 Expr *Callee = E->getCallee(); 3824 3825 if (isa<UnresolvedLookupExpr>(Callee)) 3826 return Inherited::VisitCXXOperatorCallExpr(E); 3827 3828 Visit(Callee); 3829 for (auto Arg : E->arguments()) 3830 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3831 } 3832 3833 void VisitBinaryOperator(BinaryOperator *E) { 3834 // If a field assignment is detected, remove the field from the 3835 // uninitiailized field set. 3836 if (E->getOpcode() == BO_Assign) 3837 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3838 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3839 if (!FD->getType()->isReferenceType()) 3840 DeclsToRemove.push_back(FD); 3841 3842 if (E->isCompoundAssignmentOp()) { 3843 HandleValue(E->getLHS(), false /*AddressOf*/); 3844 Visit(E->getRHS()); 3845 return; 3846 } 3847 3848 Inherited::VisitBinaryOperator(E); 3849 } 3850 3851 void VisitUnaryOperator(UnaryOperator *E) { 3852 if (E->isIncrementDecrementOp()) { 3853 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3854 return; 3855 } 3856 if (E->getOpcode() == UO_AddrOf) { 3857 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3858 HandleValue(ME->getBase(), true /*AddressOf*/); 3859 return; 3860 } 3861 } 3862 3863 Inherited::VisitUnaryOperator(E); 3864 } 3865 }; 3866 3867 // Diagnose value-uses of fields to initialize themselves, e.g. 3868 // foo(foo) 3869 // where foo is not also a parameter to the constructor. 3870 // Also diagnose across field uninitialized use such as 3871 // x(y), y(x) 3872 // TODO: implement -Wuninitialized and fold this into that framework. 3873 static void DiagnoseUninitializedFields( 3874 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3875 3876 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3877 Constructor->getLocation())) { 3878 return; 3879 } 3880 3881 if (Constructor->isInvalidDecl()) 3882 return; 3883 3884 const CXXRecordDecl *RD = Constructor->getParent(); 3885 3886 if (RD->isDependentContext()) 3887 return; 3888 3889 // Holds fields that are uninitialized. 3890 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3891 3892 // At the beginning, all fields are uninitialized. 3893 for (auto *I : RD->decls()) { 3894 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3895 UninitializedFields.insert(FD); 3896 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3897 UninitializedFields.insert(IFD->getAnonField()); 3898 } 3899 } 3900 3901 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3902 for (auto I : RD->bases()) 3903 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3904 3905 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3906 return; 3907 3908 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3909 UninitializedFields, 3910 UninitializedBaseClasses); 3911 3912 for (const auto *FieldInit : Constructor->inits()) { 3913 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3914 break; 3915 3916 Expr *InitExpr = FieldInit->getInit(); 3917 if (!InitExpr) 3918 continue; 3919 3920 if (CXXDefaultInitExpr *Default = 3921 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3922 InitExpr = Default->getExpr(); 3923 if (!InitExpr) 3924 continue; 3925 // In class initializers will point to the constructor. 3926 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3927 FieldInit->getAnyMember(), 3928 FieldInit->getBaseClass()); 3929 } else { 3930 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3931 FieldInit->getAnyMember(), 3932 FieldInit->getBaseClass()); 3933 } 3934 } 3935 } 3936 } // namespace 3937 3938 /// Enter a new C++ default initializer scope. After calling this, the 3939 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3940 /// parsing or instantiating the initializer failed. 3941 void Sema::ActOnStartCXXInClassMemberInitializer() { 3942 // Create a synthetic function scope to represent the call to the constructor 3943 // that notionally surrounds a use of this initializer. 3944 PushFunctionScope(); 3945 } 3946 3947 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 3948 if (!D.isFunctionDeclarator()) 3949 return; 3950 auto &FTI = D.getFunctionTypeInfo(); 3951 if (!FTI.Params) 3952 return; 3953 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 3954 FTI.NumParams)) { 3955 auto *ParamDecl = cast<NamedDecl>(Param.Param); 3956 if (ParamDecl->getDeclName()) 3957 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 3958 } 3959 } 3960 3961 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 3962 return ActOnRequiresClause(ConstraintExpr); 3963 } 3964 3965 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) { 3966 if (ConstraintExpr.isInvalid()) 3967 return ExprError(); 3968 3969 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr); 3970 if (ConstraintExpr.isInvalid()) 3971 return ExprError(); 3972 3973 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(), 3974 UPPC_RequiresClause)) 3975 return ExprError(); 3976 3977 return ConstraintExpr; 3978 } 3979 3980 /// This is invoked after parsing an in-class initializer for a 3981 /// non-static C++ class member, and after instantiating an in-class initializer 3982 /// in a class template. Such actions are deferred until the class is complete. 3983 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3984 SourceLocation InitLoc, 3985 Expr *InitExpr) { 3986 // Pop the notional constructor scope we created earlier. 3987 PopFunctionScopeInfo(nullptr, D); 3988 3989 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3990 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3991 "must set init style when field is created"); 3992 3993 if (!InitExpr) { 3994 D->setInvalidDecl(); 3995 if (FD) 3996 FD->removeInClassInitializer(); 3997 return; 3998 } 3999 4000 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 4001 FD->setInvalidDecl(); 4002 FD->removeInClassInitializer(); 4003 return; 4004 } 4005 4006 ExprResult Init = InitExpr; 4007 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 4008 InitializedEntity Entity = 4009 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 4010 InitializationKind Kind = 4011 FD->getInClassInitStyle() == ICIS_ListInit 4012 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 4013 InitExpr->getBeginLoc(), 4014 InitExpr->getEndLoc()) 4015 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 4016 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 4017 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 4018 if (Init.isInvalid()) { 4019 FD->setInvalidDecl(); 4020 return; 4021 } 4022 } 4023 4024 // C++11 [class.base.init]p7: 4025 // The initialization of each base and member constitutes a 4026 // full-expression. 4027 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 4028 if (Init.isInvalid()) { 4029 FD->setInvalidDecl(); 4030 return; 4031 } 4032 4033 InitExpr = Init.get(); 4034 4035 FD->setInClassInitializer(InitExpr); 4036 } 4037 4038 /// Find the direct and/or virtual base specifiers that 4039 /// correspond to the given base type, for use in base initialization 4040 /// within a constructor. 4041 static bool FindBaseInitializer(Sema &SemaRef, 4042 CXXRecordDecl *ClassDecl, 4043 QualType BaseType, 4044 const CXXBaseSpecifier *&DirectBaseSpec, 4045 const CXXBaseSpecifier *&VirtualBaseSpec) { 4046 // First, check for a direct base class. 4047 DirectBaseSpec = nullptr; 4048 for (const auto &Base : ClassDecl->bases()) { 4049 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 4050 // We found a direct base of this type. That's what we're 4051 // initializing. 4052 DirectBaseSpec = &Base; 4053 break; 4054 } 4055 } 4056 4057 // Check for a virtual base class. 4058 // FIXME: We might be able to short-circuit this if we know in advance that 4059 // there are no virtual bases. 4060 VirtualBaseSpec = nullptr; 4061 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 4062 // We haven't found a base yet; search the class hierarchy for a 4063 // virtual base class. 4064 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 4065 /*DetectVirtual=*/false); 4066 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 4067 SemaRef.Context.getTypeDeclType(ClassDecl), 4068 BaseType, Paths)) { 4069 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 4070 Path != Paths.end(); ++Path) { 4071 if (Path->back().Base->isVirtual()) { 4072 VirtualBaseSpec = Path->back().Base; 4073 break; 4074 } 4075 } 4076 } 4077 } 4078 4079 return DirectBaseSpec || VirtualBaseSpec; 4080 } 4081 4082 /// Handle a C++ member initializer using braced-init-list syntax. 4083 MemInitResult 4084 Sema::ActOnMemInitializer(Decl *ConstructorD, 4085 Scope *S, 4086 CXXScopeSpec &SS, 4087 IdentifierInfo *MemberOrBase, 4088 ParsedType TemplateTypeTy, 4089 const DeclSpec &DS, 4090 SourceLocation IdLoc, 4091 Expr *InitList, 4092 SourceLocation EllipsisLoc) { 4093 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4094 DS, IdLoc, InitList, 4095 EllipsisLoc); 4096 } 4097 4098 /// Handle a C++ member initializer using parentheses syntax. 4099 MemInitResult 4100 Sema::ActOnMemInitializer(Decl *ConstructorD, 4101 Scope *S, 4102 CXXScopeSpec &SS, 4103 IdentifierInfo *MemberOrBase, 4104 ParsedType TemplateTypeTy, 4105 const DeclSpec &DS, 4106 SourceLocation IdLoc, 4107 SourceLocation LParenLoc, 4108 ArrayRef<Expr *> Args, 4109 SourceLocation RParenLoc, 4110 SourceLocation EllipsisLoc) { 4111 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4112 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4113 DS, IdLoc, List, EllipsisLoc); 4114 } 4115 4116 namespace { 4117 4118 // Callback to only accept typo corrections that can be a valid C++ member 4119 // initializer: either a non-static field member or a base class. 4120 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4121 public: 4122 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4123 : ClassDecl(ClassDecl) {} 4124 4125 bool ValidateCandidate(const TypoCorrection &candidate) override { 4126 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4127 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4128 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4129 return isa<TypeDecl>(ND); 4130 } 4131 return false; 4132 } 4133 4134 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4135 return std::make_unique<MemInitializerValidatorCCC>(*this); 4136 } 4137 4138 private: 4139 CXXRecordDecl *ClassDecl; 4140 }; 4141 4142 } 4143 4144 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4145 CXXScopeSpec &SS, 4146 ParsedType TemplateTypeTy, 4147 IdentifierInfo *MemberOrBase) { 4148 if (SS.getScopeRep() || TemplateTypeTy) 4149 return nullptr; 4150 for (auto *D : ClassDecl->lookup(MemberOrBase)) 4151 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) 4152 return cast<ValueDecl>(D); 4153 return nullptr; 4154 } 4155 4156 /// Handle a C++ member initializer. 4157 MemInitResult 4158 Sema::BuildMemInitializer(Decl *ConstructorD, 4159 Scope *S, 4160 CXXScopeSpec &SS, 4161 IdentifierInfo *MemberOrBase, 4162 ParsedType TemplateTypeTy, 4163 const DeclSpec &DS, 4164 SourceLocation IdLoc, 4165 Expr *Init, 4166 SourceLocation EllipsisLoc) { 4167 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr, 4168 /*RecoverUncorrectedTypos=*/true); 4169 if (!Res.isUsable()) 4170 return true; 4171 Init = Res.get(); 4172 4173 if (!ConstructorD) 4174 return true; 4175 4176 AdjustDeclIfTemplate(ConstructorD); 4177 4178 CXXConstructorDecl *Constructor 4179 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4180 if (!Constructor) { 4181 // The user wrote a constructor initializer on a function that is 4182 // not a C++ constructor. Ignore the error for now, because we may 4183 // have more member initializers coming; we'll diagnose it just 4184 // once in ActOnMemInitializers. 4185 return true; 4186 } 4187 4188 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4189 4190 // C++ [class.base.init]p2: 4191 // Names in a mem-initializer-id are looked up in the scope of the 4192 // constructor's class and, if not found in that scope, are looked 4193 // up in the scope containing the constructor's definition. 4194 // [Note: if the constructor's class contains a member with the 4195 // same name as a direct or virtual base class of the class, a 4196 // mem-initializer-id naming the member or base class and composed 4197 // of a single identifier refers to the class member. A 4198 // mem-initializer-id for the hidden base class may be specified 4199 // using a qualified name. ] 4200 4201 // Look for a member, first. 4202 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4203 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4204 if (EllipsisLoc.isValid()) 4205 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4206 << MemberOrBase 4207 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4208 4209 return BuildMemberInitializer(Member, Init, IdLoc); 4210 } 4211 // It didn't name a member, so see if it names a class. 4212 QualType BaseType; 4213 TypeSourceInfo *TInfo = nullptr; 4214 4215 if (TemplateTypeTy) { 4216 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4217 if (BaseType.isNull()) 4218 return true; 4219 } else if (DS.getTypeSpecType() == TST_decltype) { 4220 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4221 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4222 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4223 return true; 4224 } else { 4225 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4226 LookupParsedName(R, S, &SS); 4227 4228 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4229 if (!TyD) { 4230 if (R.isAmbiguous()) return true; 4231 4232 // We don't want access-control diagnostics here. 4233 R.suppressDiagnostics(); 4234 4235 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4236 bool NotUnknownSpecialization = false; 4237 DeclContext *DC = computeDeclContext(SS, false); 4238 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4239 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4240 4241 if (!NotUnknownSpecialization) { 4242 // When the scope specifier can refer to a member of an unknown 4243 // specialization, we take it as a type name. 4244 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4245 SS.getWithLocInContext(Context), 4246 *MemberOrBase, IdLoc); 4247 if (BaseType.isNull()) 4248 return true; 4249 4250 TInfo = Context.CreateTypeSourceInfo(BaseType); 4251 DependentNameTypeLoc TL = 4252 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4253 if (!TL.isNull()) { 4254 TL.setNameLoc(IdLoc); 4255 TL.setElaboratedKeywordLoc(SourceLocation()); 4256 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4257 } 4258 4259 R.clear(); 4260 R.setLookupName(MemberOrBase); 4261 } 4262 } 4263 4264 // If no results were found, try to correct typos. 4265 TypoCorrection Corr; 4266 MemInitializerValidatorCCC CCC(ClassDecl); 4267 if (R.empty() && BaseType.isNull() && 4268 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4269 CCC, CTK_ErrorRecovery, ClassDecl))) { 4270 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4271 // We have found a non-static data member with a similar 4272 // name to what was typed; complain and initialize that 4273 // member. 4274 diagnoseTypo(Corr, 4275 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4276 << MemberOrBase << true); 4277 return BuildMemberInitializer(Member, Init, IdLoc); 4278 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4279 const CXXBaseSpecifier *DirectBaseSpec; 4280 const CXXBaseSpecifier *VirtualBaseSpec; 4281 if (FindBaseInitializer(*this, ClassDecl, 4282 Context.getTypeDeclType(Type), 4283 DirectBaseSpec, VirtualBaseSpec)) { 4284 // We have found a direct or virtual base class with a 4285 // similar name to what was typed; complain and initialize 4286 // that base class. 4287 diagnoseTypo(Corr, 4288 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4289 << MemberOrBase << false, 4290 PDiag() /*Suppress note, we provide our own.*/); 4291 4292 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4293 : VirtualBaseSpec; 4294 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4295 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4296 4297 TyD = Type; 4298 } 4299 } 4300 } 4301 4302 if (!TyD && BaseType.isNull()) { 4303 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4304 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4305 return true; 4306 } 4307 } 4308 4309 if (BaseType.isNull()) { 4310 BaseType = Context.getTypeDeclType(TyD); 4311 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4312 if (SS.isSet()) { 4313 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4314 BaseType); 4315 TInfo = Context.CreateTypeSourceInfo(BaseType); 4316 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4317 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4318 TL.setElaboratedKeywordLoc(SourceLocation()); 4319 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4320 } 4321 } 4322 } 4323 4324 if (!TInfo) 4325 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4326 4327 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4328 } 4329 4330 MemInitResult 4331 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4332 SourceLocation IdLoc) { 4333 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4334 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4335 assert((DirectMember || IndirectMember) && 4336 "Member must be a FieldDecl or IndirectFieldDecl"); 4337 4338 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4339 return true; 4340 4341 if (Member->isInvalidDecl()) 4342 return true; 4343 4344 MultiExprArg Args; 4345 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4346 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4347 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4348 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4349 } else { 4350 // Template instantiation doesn't reconstruct ParenListExprs for us. 4351 Args = Init; 4352 } 4353 4354 SourceRange InitRange = Init->getSourceRange(); 4355 4356 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4357 // Can't check initialization for a member of dependent type or when 4358 // any of the arguments are type-dependent expressions. 4359 DiscardCleanupsInEvaluationContext(); 4360 } else { 4361 bool InitList = false; 4362 if (isa<InitListExpr>(Init)) { 4363 InitList = true; 4364 Args = Init; 4365 } 4366 4367 // Initialize the member. 4368 InitializedEntity MemberEntity = 4369 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4370 : InitializedEntity::InitializeMember(IndirectMember, 4371 nullptr); 4372 InitializationKind Kind = 4373 InitList ? InitializationKind::CreateDirectList( 4374 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4375 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4376 InitRange.getEnd()); 4377 4378 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4379 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4380 nullptr); 4381 if (!MemberInit.isInvalid()) { 4382 // C++11 [class.base.init]p7: 4383 // The initialization of each base and member constitutes a 4384 // full-expression. 4385 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4386 /*DiscardedValue*/ false); 4387 } 4388 4389 if (MemberInit.isInvalid()) { 4390 // Args were sensible expressions but we couldn't initialize the member 4391 // from them. Preserve them in a RecoveryExpr instead. 4392 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, 4393 Member->getType()) 4394 .get(); 4395 if (!Init) 4396 return true; 4397 } else { 4398 Init = MemberInit.get(); 4399 } 4400 } 4401 4402 if (DirectMember) { 4403 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4404 InitRange.getBegin(), Init, 4405 InitRange.getEnd()); 4406 } else { 4407 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4408 InitRange.getBegin(), Init, 4409 InitRange.getEnd()); 4410 } 4411 } 4412 4413 MemInitResult 4414 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4415 CXXRecordDecl *ClassDecl) { 4416 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4417 if (!LangOpts.CPlusPlus11) 4418 return Diag(NameLoc, diag::err_delegating_ctor) 4419 << TInfo->getTypeLoc().getLocalSourceRange(); 4420 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4421 4422 bool InitList = true; 4423 MultiExprArg Args = Init; 4424 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4425 InitList = false; 4426 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4427 } 4428 4429 SourceRange InitRange = Init->getSourceRange(); 4430 // Initialize the object. 4431 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4432 QualType(ClassDecl->getTypeForDecl(), 0)); 4433 InitializationKind Kind = 4434 InitList ? InitializationKind::CreateDirectList( 4435 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4436 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4437 InitRange.getEnd()); 4438 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4439 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4440 Args, nullptr); 4441 if (!DelegationInit.isInvalid()) { 4442 assert((DelegationInit.get()->containsErrors() || 4443 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) && 4444 "Delegating constructor with no target?"); 4445 4446 // C++11 [class.base.init]p7: 4447 // The initialization of each base and member constitutes a 4448 // full-expression. 4449 DelegationInit = ActOnFinishFullExpr( 4450 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4451 } 4452 4453 if (DelegationInit.isInvalid()) { 4454 DelegationInit = 4455 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, 4456 QualType(ClassDecl->getTypeForDecl(), 0)); 4457 if (DelegationInit.isInvalid()) 4458 return true; 4459 } else { 4460 // If we are in a dependent context, template instantiation will 4461 // perform this type-checking again. Just save the arguments that we 4462 // received in a ParenListExpr. 4463 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4464 // of the information that we have about the base 4465 // initializer. However, deconstructing the ASTs is a dicey process, 4466 // and this approach is far more likely to get the corner cases right. 4467 if (CurContext->isDependentContext()) 4468 DelegationInit = Init; 4469 } 4470 4471 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4472 DelegationInit.getAs<Expr>(), 4473 InitRange.getEnd()); 4474 } 4475 4476 MemInitResult 4477 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4478 Expr *Init, CXXRecordDecl *ClassDecl, 4479 SourceLocation EllipsisLoc) { 4480 SourceLocation BaseLoc 4481 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4482 4483 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4484 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4485 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4486 4487 // C++ [class.base.init]p2: 4488 // [...] Unless the mem-initializer-id names a nonstatic data 4489 // member of the constructor's class or a direct or virtual base 4490 // of that class, the mem-initializer is ill-formed. A 4491 // mem-initializer-list can initialize a base class using any 4492 // name that denotes that base class type. 4493 4494 // We can store the initializers in "as-written" form and delay analysis until 4495 // instantiation if the constructor is dependent. But not for dependent 4496 // (broken) code in a non-template! SetCtorInitializers does not expect this. 4497 bool Dependent = CurContext->isDependentContext() && 4498 (BaseType->isDependentType() || Init->isTypeDependent()); 4499 4500 SourceRange InitRange = Init->getSourceRange(); 4501 if (EllipsisLoc.isValid()) { 4502 // This is a pack expansion. 4503 if (!BaseType->containsUnexpandedParameterPack()) { 4504 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4505 << SourceRange(BaseLoc, InitRange.getEnd()); 4506 4507 EllipsisLoc = SourceLocation(); 4508 } 4509 } else { 4510 // Check for any unexpanded parameter packs. 4511 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4512 return true; 4513 4514 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4515 return true; 4516 } 4517 4518 // Check for direct and virtual base classes. 4519 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4520 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4521 if (!Dependent) { 4522 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4523 BaseType)) 4524 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4525 4526 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4527 VirtualBaseSpec); 4528 4529 // C++ [base.class.init]p2: 4530 // Unless the mem-initializer-id names a nonstatic data member of the 4531 // constructor's class or a direct or virtual base of that class, the 4532 // mem-initializer is ill-formed. 4533 if (!DirectBaseSpec && !VirtualBaseSpec) { 4534 // If the class has any dependent bases, then it's possible that 4535 // one of those types will resolve to the same type as 4536 // BaseType. Therefore, just treat this as a dependent base 4537 // class initialization. FIXME: Should we try to check the 4538 // initialization anyway? It seems odd. 4539 if (ClassDecl->hasAnyDependentBases()) 4540 Dependent = true; 4541 else 4542 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4543 << BaseType << Context.getTypeDeclType(ClassDecl) 4544 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4545 } 4546 } 4547 4548 if (Dependent) { 4549 DiscardCleanupsInEvaluationContext(); 4550 4551 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4552 /*IsVirtual=*/false, 4553 InitRange.getBegin(), Init, 4554 InitRange.getEnd(), EllipsisLoc); 4555 } 4556 4557 // C++ [base.class.init]p2: 4558 // If a mem-initializer-id is ambiguous because it designates both 4559 // a direct non-virtual base class and an inherited virtual base 4560 // class, the mem-initializer is ill-formed. 4561 if (DirectBaseSpec && VirtualBaseSpec) 4562 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4563 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4564 4565 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4566 if (!BaseSpec) 4567 BaseSpec = VirtualBaseSpec; 4568 4569 // Initialize the base. 4570 bool InitList = true; 4571 MultiExprArg Args = Init; 4572 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4573 InitList = false; 4574 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4575 } 4576 4577 InitializedEntity BaseEntity = 4578 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4579 InitializationKind Kind = 4580 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4581 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4582 InitRange.getEnd()); 4583 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4584 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4585 if (!BaseInit.isInvalid()) { 4586 // C++11 [class.base.init]p7: 4587 // The initialization of each base and member constitutes a 4588 // full-expression. 4589 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4590 /*DiscardedValue*/ false); 4591 } 4592 4593 if (BaseInit.isInvalid()) { 4594 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), 4595 Args, BaseType); 4596 if (BaseInit.isInvalid()) 4597 return true; 4598 } else { 4599 // If we are in a dependent context, template instantiation will 4600 // perform this type-checking again. Just save the arguments that we 4601 // received in a ParenListExpr. 4602 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4603 // of the information that we have about the base 4604 // initializer. However, deconstructing the ASTs is a dicey process, 4605 // and this approach is far more likely to get the corner cases right. 4606 if (CurContext->isDependentContext()) 4607 BaseInit = Init; 4608 } 4609 4610 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4611 BaseSpec->isVirtual(), 4612 InitRange.getBegin(), 4613 BaseInit.getAs<Expr>(), 4614 InitRange.getEnd(), EllipsisLoc); 4615 } 4616 4617 // Create a static_cast\<T&&>(expr). 4618 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4619 if (T.isNull()) T = E->getType(); 4620 QualType TargetType = SemaRef.BuildReferenceType( 4621 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4622 SourceLocation ExprLoc = E->getBeginLoc(); 4623 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4624 TargetType, ExprLoc); 4625 4626 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4627 SourceRange(ExprLoc, ExprLoc), 4628 E->getSourceRange()).get(); 4629 } 4630 4631 /// ImplicitInitializerKind - How an implicit base or member initializer should 4632 /// initialize its base or member. 4633 enum ImplicitInitializerKind { 4634 IIK_Default, 4635 IIK_Copy, 4636 IIK_Move, 4637 IIK_Inherit 4638 }; 4639 4640 static bool 4641 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4642 ImplicitInitializerKind ImplicitInitKind, 4643 CXXBaseSpecifier *BaseSpec, 4644 bool IsInheritedVirtualBase, 4645 CXXCtorInitializer *&CXXBaseInit) { 4646 InitializedEntity InitEntity 4647 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4648 IsInheritedVirtualBase); 4649 4650 ExprResult BaseInit; 4651 4652 switch (ImplicitInitKind) { 4653 case IIK_Inherit: 4654 case IIK_Default: { 4655 InitializationKind InitKind 4656 = InitializationKind::CreateDefault(Constructor->getLocation()); 4657 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4658 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4659 break; 4660 } 4661 4662 case IIK_Move: 4663 case IIK_Copy: { 4664 bool Moving = ImplicitInitKind == IIK_Move; 4665 ParmVarDecl *Param = Constructor->getParamDecl(0); 4666 QualType ParamType = Param->getType().getNonReferenceType(); 4667 4668 Expr *CopyCtorArg = 4669 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4670 SourceLocation(), Param, false, 4671 Constructor->getLocation(), ParamType, 4672 VK_LValue, nullptr); 4673 4674 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4675 4676 // Cast to the base class to avoid ambiguities. 4677 QualType ArgTy = 4678 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4679 ParamType.getQualifiers()); 4680 4681 if (Moving) { 4682 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4683 } 4684 4685 CXXCastPath BasePath; 4686 BasePath.push_back(BaseSpec); 4687 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4688 CK_UncheckedDerivedToBase, 4689 Moving ? VK_XValue : VK_LValue, 4690 &BasePath).get(); 4691 4692 InitializationKind InitKind 4693 = InitializationKind::CreateDirect(Constructor->getLocation(), 4694 SourceLocation(), SourceLocation()); 4695 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4696 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4697 break; 4698 } 4699 } 4700 4701 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4702 if (BaseInit.isInvalid()) 4703 return true; 4704 4705 CXXBaseInit = 4706 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4707 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4708 SourceLocation()), 4709 BaseSpec->isVirtual(), 4710 SourceLocation(), 4711 BaseInit.getAs<Expr>(), 4712 SourceLocation(), 4713 SourceLocation()); 4714 4715 return false; 4716 } 4717 4718 static bool RefersToRValueRef(Expr *MemRef) { 4719 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4720 return Referenced->getType()->isRValueReferenceType(); 4721 } 4722 4723 static bool 4724 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4725 ImplicitInitializerKind ImplicitInitKind, 4726 FieldDecl *Field, IndirectFieldDecl *Indirect, 4727 CXXCtorInitializer *&CXXMemberInit) { 4728 if (Field->isInvalidDecl()) 4729 return true; 4730 4731 SourceLocation Loc = Constructor->getLocation(); 4732 4733 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4734 bool Moving = ImplicitInitKind == IIK_Move; 4735 ParmVarDecl *Param = Constructor->getParamDecl(0); 4736 QualType ParamType = Param->getType().getNonReferenceType(); 4737 4738 // Suppress copying zero-width bitfields. 4739 if (Field->isZeroLengthBitField(SemaRef.Context)) 4740 return false; 4741 4742 Expr *MemberExprBase = 4743 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4744 SourceLocation(), Param, false, 4745 Loc, ParamType, VK_LValue, nullptr); 4746 4747 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4748 4749 if (Moving) { 4750 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4751 } 4752 4753 // Build a reference to this field within the parameter. 4754 CXXScopeSpec SS; 4755 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4756 Sema::LookupMemberName); 4757 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4758 : cast<ValueDecl>(Field), AS_public); 4759 MemberLookup.resolveKind(); 4760 ExprResult CtorArg 4761 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4762 ParamType, Loc, 4763 /*IsArrow=*/false, 4764 SS, 4765 /*TemplateKWLoc=*/SourceLocation(), 4766 /*FirstQualifierInScope=*/nullptr, 4767 MemberLookup, 4768 /*TemplateArgs=*/nullptr, 4769 /*S*/nullptr); 4770 if (CtorArg.isInvalid()) 4771 return true; 4772 4773 // C++11 [class.copy]p15: 4774 // - if a member m has rvalue reference type T&&, it is direct-initialized 4775 // with static_cast<T&&>(x.m); 4776 if (RefersToRValueRef(CtorArg.get())) { 4777 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4778 } 4779 4780 InitializedEntity Entity = 4781 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4782 /*Implicit*/ true) 4783 : InitializedEntity::InitializeMember(Field, nullptr, 4784 /*Implicit*/ true); 4785 4786 // Direct-initialize to use the copy constructor. 4787 InitializationKind InitKind = 4788 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4789 4790 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4791 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4792 ExprResult MemberInit = 4793 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4794 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4795 if (MemberInit.isInvalid()) 4796 return true; 4797 4798 if (Indirect) 4799 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4800 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4801 else 4802 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4803 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4804 return false; 4805 } 4806 4807 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4808 "Unhandled implicit init kind!"); 4809 4810 QualType FieldBaseElementType = 4811 SemaRef.Context.getBaseElementType(Field->getType()); 4812 4813 if (FieldBaseElementType->isRecordType()) { 4814 InitializedEntity InitEntity = 4815 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4816 /*Implicit*/ true) 4817 : InitializedEntity::InitializeMember(Field, nullptr, 4818 /*Implicit*/ true); 4819 InitializationKind InitKind = 4820 InitializationKind::CreateDefault(Loc); 4821 4822 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4823 ExprResult MemberInit = 4824 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4825 4826 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4827 if (MemberInit.isInvalid()) 4828 return true; 4829 4830 if (Indirect) 4831 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4832 Indirect, Loc, 4833 Loc, 4834 MemberInit.get(), 4835 Loc); 4836 else 4837 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4838 Field, Loc, Loc, 4839 MemberInit.get(), 4840 Loc); 4841 return false; 4842 } 4843 4844 if (!Field->getParent()->isUnion()) { 4845 if (FieldBaseElementType->isReferenceType()) { 4846 SemaRef.Diag(Constructor->getLocation(), 4847 diag::err_uninitialized_member_in_ctor) 4848 << (int)Constructor->isImplicit() 4849 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4850 << 0 << Field->getDeclName(); 4851 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4852 return true; 4853 } 4854 4855 if (FieldBaseElementType.isConstQualified()) { 4856 SemaRef.Diag(Constructor->getLocation(), 4857 diag::err_uninitialized_member_in_ctor) 4858 << (int)Constructor->isImplicit() 4859 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4860 << 1 << Field->getDeclName(); 4861 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4862 return true; 4863 } 4864 } 4865 4866 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4867 // ARC and Weak: 4868 // Default-initialize Objective-C pointers to NULL. 4869 CXXMemberInit 4870 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4871 Loc, Loc, 4872 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4873 Loc); 4874 return false; 4875 } 4876 4877 // Nothing to initialize. 4878 CXXMemberInit = nullptr; 4879 return false; 4880 } 4881 4882 namespace { 4883 struct BaseAndFieldInfo { 4884 Sema &S; 4885 CXXConstructorDecl *Ctor; 4886 bool AnyErrorsInInits; 4887 ImplicitInitializerKind IIK; 4888 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4889 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4890 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4891 4892 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4893 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4894 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4895 if (Ctor->getInheritedConstructor()) 4896 IIK = IIK_Inherit; 4897 else if (Generated && Ctor->isCopyConstructor()) 4898 IIK = IIK_Copy; 4899 else if (Generated && Ctor->isMoveConstructor()) 4900 IIK = IIK_Move; 4901 else 4902 IIK = IIK_Default; 4903 } 4904 4905 bool isImplicitCopyOrMove() const { 4906 switch (IIK) { 4907 case IIK_Copy: 4908 case IIK_Move: 4909 return true; 4910 4911 case IIK_Default: 4912 case IIK_Inherit: 4913 return false; 4914 } 4915 4916 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4917 } 4918 4919 bool addFieldInitializer(CXXCtorInitializer *Init) { 4920 AllToInit.push_back(Init); 4921 4922 // Check whether this initializer makes the field "used". 4923 if (Init->getInit()->HasSideEffects(S.Context)) 4924 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4925 4926 return false; 4927 } 4928 4929 bool isInactiveUnionMember(FieldDecl *Field) { 4930 RecordDecl *Record = Field->getParent(); 4931 if (!Record->isUnion()) 4932 return false; 4933 4934 if (FieldDecl *Active = 4935 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4936 return Active != Field->getCanonicalDecl(); 4937 4938 // In an implicit copy or move constructor, ignore any in-class initializer. 4939 if (isImplicitCopyOrMove()) 4940 return true; 4941 4942 // If there's no explicit initialization, the field is active only if it 4943 // has an in-class initializer... 4944 if (Field->hasInClassInitializer()) 4945 return false; 4946 // ... or it's an anonymous struct or union whose class has an in-class 4947 // initializer. 4948 if (!Field->isAnonymousStructOrUnion()) 4949 return true; 4950 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4951 return !FieldRD->hasInClassInitializer(); 4952 } 4953 4954 /// Determine whether the given field is, or is within, a union member 4955 /// that is inactive (because there was an initializer given for a different 4956 /// member of the union, or because the union was not initialized at all). 4957 bool isWithinInactiveUnionMember(FieldDecl *Field, 4958 IndirectFieldDecl *Indirect) { 4959 if (!Indirect) 4960 return isInactiveUnionMember(Field); 4961 4962 for (auto *C : Indirect->chain()) { 4963 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4964 if (Field && isInactiveUnionMember(Field)) 4965 return true; 4966 } 4967 return false; 4968 } 4969 }; 4970 } 4971 4972 /// Determine whether the given type is an incomplete or zero-lenfgth 4973 /// array type. 4974 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4975 if (T->isIncompleteArrayType()) 4976 return true; 4977 4978 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4979 if (!ArrayT->getSize()) 4980 return true; 4981 4982 T = ArrayT->getElementType(); 4983 } 4984 4985 return false; 4986 } 4987 4988 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4989 FieldDecl *Field, 4990 IndirectFieldDecl *Indirect = nullptr) { 4991 if (Field->isInvalidDecl()) 4992 return false; 4993 4994 // Overwhelmingly common case: we have a direct initializer for this field. 4995 if (CXXCtorInitializer *Init = 4996 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4997 return Info.addFieldInitializer(Init); 4998 4999 // C++11 [class.base.init]p8: 5000 // if the entity is a non-static data member that has a 5001 // brace-or-equal-initializer and either 5002 // -- the constructor's class is a union and no other variant member of that 5003 // union is designated by a mem-initializer-id or 5004 // -- the constructor's class is not a union, and, if the entity is a member 5005 // of an anonymous union, no other member of that union is designated by 5006 // a mem-initializer-id, 5007 // the entity is initialized as specified in [dcl.init]. 5008 // 5009 // We also apply the same rules to handle anonymous structs within anonymous 5010 // unions. 5011 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 5012 return false; 5013 5014 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 5015 ExprResult DIE = 5016 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 5017 if (DIE.isInvalid()) 5018 return true; 5019 5020 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 5021 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 5022 5023 CXXCtorInitializer *Init; 5024 if (Indirect) 5025 Init = new (SemaRef.Context) 5026 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 5027 SourceLocation(), DIE.get(), SourceLocation()); 5028 else 5029 Init = new (SemaRef.Context) 5030 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 5031 SourceLocation(), DIE.get(), SourceLocation()); 5032 return Info.addFieldInitializer(Init); 5033 } 5034 5035 // Don't initialize incomplete or zero-length arrays. 5036 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 5037 return false; 5038 5039 // Don't try to build an implicit initializer if there were semantic 5040 // errors in any of the initializers (and therefore we might be 5041 // missing some that the user actually wrote). 5042 if (Info.AnyErrorsInInits) 5043 return false; 5044 5045 CXXCtorInitializer *Init = nullptr; 5046 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 5047 Indirect, Init)) 5048 return true; 5049 5050 if (!Init) 5051 return false; 5052 5053 return Info.addFieldInitializer(Init); 5054 } 5055 5056 bool 5057 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 5058 CXXCtorInitializer *Initializer) { 5059 assert(Initializer->isDelegatingInitializer()); 5060 Constructor->setNumCtorInitializers(1); 5061 CXXCtorInitializer **initializer = 5062 new (Context) CXXCtorInitializer*[1]; 5063 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 5064 Constructor->setCtorInitializers(initializer); 5065 5066 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 5067 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 5068 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 5069 } 5070 5071 DelegatingCtorDecls.push_back(Constructor); 5072 5073 DiagnoseUninitializedFields(*this, Constructor); 5074 5075 return false; 5076 } 5077 5078 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 5079 ArrayRef<CXXCtorInitializer *> Initializers) { 5080 if (Constructor->isDependentContext()) { 5081 // Just store the initializers as written, they will be checked during 5082 // instantiation. 5083 if (!Initializers.empty()) { 5084 Constructor->setNumCtorInitializers(Initializers.size()); 5085 CXXCtorInitializer **baseOrMemberInitializers = 5086 new (Context) CXXCtorInitializer*[Initializers.size()]; 5087 memcpy(baseOrMemberInitializers, Initializers.data(), 5088 Initializers.size() * sizeof(CXXCtorInitializer*)); 5089 Constructor->setCtorInitializers(baseOrMemberInitializers); 5090 } 5091 5092 // Let template instantiation know whether we had errors. 5093 if (AnyErrors) 5094 Constructor->setInvalidDecl(); 5095 5096 return false; 5097 } 5098 5099 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 5100 5101 // We need to build the initializer AST according to order of construction 5102 // and not what user specified in the Initializers list. 5103 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 5104 if (!ClassDecl) 5105 return true; 5106 5107 bool HadError = false; 5108 5109 for (unsigned i = 0; i < Initializers.size(); i++) { 5110 CXXCtorInitializer *Member = Initializers[i]; 5111 5112 if (Member->isBaseInitializer()) 5113 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5114 else { 5115 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5116 5117 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5118 for (auto *C : F->chain()) { 5119 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5120 if (FD && FD->getParent()->isUnion()) 5121 Info.ActiveUnionMember.insert(std::make_pair( 5122 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5123 } 5124 } else if (FieldDecl *FD = Member->getMember()) { 5125 if (FD->getParent()->isUnion()) 5126 Info.ActiveUnionMember.insert(std::make_pair( 5127 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5128 } 5129 } 5130 } 5131 5132 // Keep track of the direct virtual bases. 5133 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5134 for (auto &I : ClassDecl->bases()) { 5135 if (I.isVirtual()) 5136 DirectVBases.insert(&I); 5137 } 5138 5139 // Push virtual bases before others. 5140 for (auto &VBase : ClassDecl->vbases()) { 5141 if (CXXCtorInitializer *Value 5142 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5143 // [class.base.init]p7, per DR257: 5144 // A mem-initializer where the mem-initializer-id names a virtual base 5145 // class is ignored during execution of a constructor of any class that 5146 // is not the most derived class. 5147 if (ClassDecl->isAbstract()) { 5148 // FIXME: Provide a fixit to remove the base specifier. This requires 5149 // tracking the location of the associated comma for a base specifier. 5150 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5151 << VBase.getType() << ClassDecl; 5152 DiagnoseAbstractType(ClassDecl); 5153 } 5154 5155 Info.AllToInit.push_back(Value); 5156 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5157 // [class.base.init]p8, per DR257: 5158 // If a given [...] base class is not named by a mem-initializer-id 5159 // [...] and the entity is not a virtual base class of an abstract 5160 // class, then [...] the entity is default-initialized. 5161 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5162 CXXCtorInitializer *CXXBaseInit; 5163 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5164 &VBase, IsInheritedVirtualBase, 5165 CXXBaseInit)) { 5166 HadError = true; 5167 continue; 5168 } 5169 5170 Info.AllToInit.push_back(CXXBaseInit); 5171 } 5172 } 5173 5174 // Non-virtual bases. 5175 for (auto &Base : ClassDecl->bases()) { 5176 // Virtuals are in the virtual base list and already constructed. 5177 if (Base.isVirtual()) 5178 continue; 5179 5180 if (CXXCtorInitializer *Value 5181 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5182 Info.AllToInit.push_back(Value); 5183 } else if (!AnyErrors) { 5184 CXXCtorInitializer *CXXBaseInit; 5185 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5186 &Base, /*IsInheritedVirtualBase=*/false, 5187 CXXBaseInit)) { 5188 HadError = true; 5189 continue; 5190 } 5191 5192 Info.AllToInit.push_back(CXXBaseInit); 5193 } 5194 } 5195 5196 // Fields. 5197 for (auto *Mem : ClassDecl->decls()) { 5198 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5199 // C++ [class.bit]p2: 5200 // A declaration for a bit-field that omits the identifier declares an 5201 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5202 // initialized. 5203 if (F->isUnnamedBitfield()) 5204 continue; 5205 5206 // If we're not generating the implicit copy/move constructor, then we'll 5207 // handle anonymous struct/union fields based on their individual 5208 // indirect fields. 5209 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5210 continue; 5211 5212 if (CollectFieldInitializer(*this, Info, F)) 5213 HadError = true; 5214 continue; 5215 } 5216 5217 // Beyond this point, we only consider default initialization. 5218 if (Info.isImplicitCopyOrMove()) 5219 continue; 5220 5221 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5222 if (F->getType()->isIncompleteArrayType()) { 5223 assert(ClassDecl->hasFlexibleArrayMember() && 5224 "Incomplete array type is not valid"); 5225 continue; 5226 } 5227 5228 // Initialize each field of an anonymous struct individually. 5229 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5230 HadError = true; 5231 5232 continue; 5233 } 5234 } 5235 5236 unsigned NumInitializers = Info.AllToInit.size(); 5237 if (NumInitializers > 0) { 5238 Constructor->setNumCtorInitializers(NumInitializers); 5239 CXXCtorInitializer **baseOrMemberInitializers = 5240 new (Context) CXXCtorInitializer*[NumInitializers]; 5241 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5242 NumInitializers * sizeof(CXXCtorInitializer*)); 5243 Constructor->setCtorInitializers(baseOrMemberInitializers); 5244 5245 // Constructors implicitly reference the base and member 5246 // destructors. 5247 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5248 Constructor->getParent()); 5249 } 5250 5251 return HadError; 5252 } 5253 5254 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5255 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5256 const RecordDecl *RD = RT->getDecl(); 5257 if (RD->isAnonymousStructOrUnion()) { 5258 for (auto *Field : RD->fields()) 5259 PopulateKeysForFields(Field, IdealInits); 5260 return; 5261 } 5262 } 5263 IdealInits.push_back(Field->getCanonicalDecl()); 5264 } 5265 5266 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5267 return Context.getCanonicalType(BaseType).getTypePtr(); 5268 } 5269 5270 static const void *GetKeyForMember(ASTContext &Context, 5271 CXXCtorInitializer *Member) { 5272 if (!Member->isAnyMemberInitializer()) 5273 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5274 5275 return Member->getAnyMember()->getCanonicalDecl(); 5276 } 5277 5278 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, 5279 const CXXCtorInitializer *Previous, 5280 const CXXCtorInitializer *Current) { 5281 if (Previous->isAnyMemberInitializer()) 5282 Diag << 0 << Previous->getAnyMember(); 5283 else 5284 Diag << 1 << Previous->getTypeSourceInfo()->getType(); 5285 5286 if (Current->isAnyMemberInitializer()) 5287 Diag << 0 << Current->getAnyMember(); 5288 else 5289 Diag << 1 << Current->getTypeSourceInfo()->getType(); 5290 } 5291 5292 static void DiagnoseBaseOrMemInitializerOrder( 5293 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5294 ArrayRef<CXXCtorInitializer *> Inits) { 5295 if (Constructor->getDeclContext()->isDependentContext()) 5296 return; 5297 5298 // Don't check initializers order unless the warning is enabled at the 5299 // location of at least one initializer. 5300 bool ShouldCheckOrder = false; 5301 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5302 CXXCtorInitializer *Init = Inits[InitIndex]; 5303 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5304 Init->getSourceLocation())) { 5305 ShouldCheckOrder = true; 5306 break; 5307 } 5308 } 5309 if (!ShouldCheckOrder) 5310 return; 5311 5312 // Build the list of bases and members in the order that they'll 5313 // actually be initialized. The explicit initializers should be in 5314 // this same order but may be missing things. 5315 SmallVector<const void*, 32> IdealInitKeys; 5316 5317 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5318 5319 // 1. Virtual bases. 5320 for (const auto &VBase : ClassDecl->vbases()) 5321 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5322 5323 // 2. Non-virtual bases. 5324 for (const auto &Base : ClassDecl->bases()) { 5325 if (Base.isVirtual()) 5326 continue; 5327 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5328 } 5329 5330 // 3. Direct fields. 5331 for (auto *Field : ClassDecl->fields()) { 5332 if (Field->isUnnamedBitfield()) 5333 continue; 5334 5335 PopulateKeysForFields(Field, IdealInitKeys); 5336 } 5337 5338 unsigned NumIdealInits = IdealInitKeys.size(); 5339 unsigned IdealIndex = 0; 5340 5341 // Track initializers that are in an incorrect order for either a warning or 5342 // note if multiple ones occur. 5343 SmallVector<unsigned> WarnIndexes; 5344 // Correlates the index of an initializer in the init-list to the index of 5345 // the field/base in the class. 5346 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder; 5347 5348 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5349 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]); 5350 5351 // Scan forward to try to find this initializer in the idealized 5352 // initializers list. 5353 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5354 if (InitKey == IdealInitKeys[IdealIndex]) 5355 break; 5356 5357 // If we didn't find this initializer, it must be because we 5358 // scanned past it on a previous iteration. That can only 5359 // happen if we're out of order; emit a warning. 5360 if (IdealIndex == NumIdealInits && InitIndex) { 5361 WarnIndexes.push_back(InitIndex); 5362 5363 // Move back to the initializer's location in the ideal list. 5364 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5365 if (InitKey == IdealInitKeys[IdealIndex]) 5366 break; 5367 5368 assert(IdealIndex < NumIdealInits && 5369 "initializer not found in initializer list"); 5370 } 5371 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex); 5372 } 5373 5374 if (WarnIndexes.empty()) 5375 return; 5376 5377 // Sort based on the ideal order, first in the pair. 5378 llvm::sort(CorrelatedInitOrder, 5379 [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; }); 5380 5381 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to 5382 // emit the diagnostic before we can try adding notes. 5383 { 5384 Sema::SemaDiagnosticBuilder D = SemaRef.Diag( 5385 Inits[WarnIndexes.front() - 1]->getSourceLocation(), 5386 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order 5387 : diag::warn_some_initializers_out_of_order); 5388 5389 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) { 5390 if (CorrelatedInitOrder[I].second == I) 5391 continue; 5392 // Ideally we would be using InsertFromRange here, but clang doesn't 5393 // appear to handle InsertFromRange correctly when the source range is 5394 // modified by another fix-it. 5395 D << FixItHint::CreateReplacement( 5396 Inits[I]->getSourceRange(), 5397 Lexer::getSourceText( 5398 CharSourceRange::getTokenRange( 5399 Inits[CorrelatedInitOrder[I].second]->getSourceRange()), 5400 SemaRef.getSourceManager(), SemaRef.getLangOpts())); 5401 } 5402 5403 // If there is only 1 item out of order, the warning expects the name and 5404 // type of each being added to it. 5405 if (WarnIndexes.size() == 1) { 5406 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1], 5407 Inits[WarnIndexes.front()]); 5408 return; 5409 } 5410 } 5411 // More than 1 item to warn, create notes letting the user know which ones 5412 // are bad. 5413 for (unsigned WarnIndex : WarnIndexes) { 5414 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1]; 5415 auto D = SemaRef.Diag(PrevInit->getSourceLocation(), 5416 diag::note_initializer_out_of_order); 5417 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]); 5418 D << PrevInit->getSourceRange(); 5419 } 5420 } 5421 5422 namespace { 5423 bool CheckRedundantInit(Sema &S, 5424 CXXCtorInitializer *Init, 5425 CXXCtorInitializer *&PrevInit) { 5426 if (!PrevInit) { 5427 PrevInit = Init; 5428 return false; 5429 } 5430 5431 if (FieldDecl *Field = Init->getAnyMember()) 5432 S.Diag(Init->getSourceLocation(), 5433 diag::err_multiple_mem_initialization) 5434 << Field->getDeclName() 5435 << Init->getSourceRange(); 5436 else { 5437 const Type *BaseClass = Init->getBaseClass(); 5438 assert(BaseClass && "neither field nor base"); 5439 S.Diag(Init->getSourceLocation(), 5440 diag::err_multiple_base_initialization) 5441 << QualType(BaseClass, 0) 5442 << Init->getSourceRange(); 5443 } 5444 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5445 << 0 << PrevInit->getSourceRange(); 5446 5447 return true; 5448 } 5449 5450 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5451 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5452 5453 bool CheckRedundantUnionInit(Sema &S, 5454 CXXCtorInitializer *Init, 5455 RedundantUnionMap &Unions) { 5456 FieldDecl *Field = Init->getAnyMember(); 5457 RecordDecl *Parent = Field->getParent(); 5458 NamedDecl *Child = Field; 5459 5460 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5461 if (Parent->isUnion()) { 5462 UnionEntry &En = Unions[Parent]; 5463 if (En.first && En.first != Child) { 5464 S.Diag(Init->getSourceLocation(), 5465 diag::err_multiple_mem_union_initialization) 5466 << Field->getDeclName() 5467 << Init->getSourceRange(); 5468 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5469 << 0 << En.second->getSourceRange(); 5470 return true; 5471 } 5472 if (!En.first) { 5473 En.first = Child; 5474 En.second = Init; 5475 } 5476 if (!Parent->isAnonymousStructOrUnion()) 5477 return false; 5478 } 5479 5480 Child = Parent; 5481 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5482 } 5483 5484 return false; 5485 } 5486 } // namespace 5487 5488 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5489 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5490 SourceLocation ColonLoc, 5491 ArrayRef<CXXCtorInitializer*> MemInits, 5492 bool AnyErrors) { 5493 if (!ConstructorDecl) 5494 return; 5495 5496 AdjustDeclIfTemplate(ConstructorDecl); 5497 5498 CXXConstructorDecl *Constructor 5499 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5500 5501 if (!Constructor) { 5502 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5503 return; 5504 } 5505 5506 // Mapping for the duplicate initializers check. 5507 // For member initializers, this is keyed with a FieldDecl*. 5508 // For base initializers, this is keyed with a Type*. 5509 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5510 5511 // Mapping for the inconsistent anonymous-union initializers check. 5512 RedundantUnionMap MemberUnions; 5513 5514 bool HadError = false; 5515 for (unsigned i = 0; i < MemInits.size(); i++) { 5516 CXXCtorInitializer *Init = MemInits[i]; 5517 5518 // Set the source order index. 5519 Init->setSourceOrder(i); 5520 5521 if (Init->isAnyMemberInitializer()) { 5522 const void *Key = GetKeyForMember(Context, Init); 5523 if (CheckRedundantInit(*this, Init, Members[Key]) || 5524 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5525 HadError = true; 5526 } else if (Init->isBaseInitializer()) { 5527 const void *Key = GetKeyForMember(Context, Init); 5528 if (CheckRedundantInit(*this, Init, Members[Key])) 5529 HadError = true; 5530 } else { 5531 assert(Init->isDelegatingInitializer()); 5532 // This must be the only initializer 5533 if (MemInits.size() != 1) { 5534 Diag(Init->getSourceLocation(), 5535 diag::err_delegating_initializer_alone) 5536 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5537 // We will treat this as being the only initializer. 5538 } 5539 SetDelegatingInitializer(Constructor, MemInits[i]); 5540 // Return immediately as the initializer is set. 5541 return; 5542 } 5543 } 5544 5545 if (HadError) 5546 return; 5547 5548 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5549 5550 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5551 5552 DiagnoseUninitializedFields(*this, Constructor); 5553 } 5554 5555 void 5556 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5557 CXXRecordDecl *ClassDecl) { 5558 // Ignore dependent contexts. Also ignore unions, since their members never 5559 // have destructors implicitly called. 5560 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5561 return; 5562 5563 // FIXME: all the access-control diagnostics are positioned on the 5564 // field/base declaration. That's probably good; that said, the 5565 // user might reasonably want to know why the destructor is being 5566 // emitted, and we currently don't say. 5567 5568 // Non-static data members. 5569 for (auto *Field : ClassDecl->fields()) { 5570 if (Field->isInvalidDecl()) 5571 continue; 5572 5573 // Don't destroy incomplete or zero-length arrays. 5574 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5575 continue; 5576 5577 QualType FieldType = Context.getBaseElementType(Field->getType()); 5578 5579 const RecordType* RT = FieldType->getAs<RecordType>(); 5580 if (!RT) 5581 continue; 5582 5583 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5584 if (FieldClassDecl->isInvalidDecl()) 5585 continue; 5586 if (FieldClassDecl->hasIrrelevantDestructor()) 5587 continue; 5588 // The destructor for an implicit anonymous union member is never invoked. 5589 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5590 continue; 5591 5592 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5593 assert(Dtor && "No dtor found for FieldClassDecl!"); 5594 CheckDestructorAccess(Field->getLocation(), Dtor, 5595 PDiag(diag::err_access_dtor_field) 5596 << Field->getDeclName() 5597 << FieldType); 5598 5599 MarkFunctionReferenced(Location, Dtor); 5600 DiagnoseUseOfDecl(Dtor, Location); 5601 } 5602 5603 // We only potentially invoke the destructors of potentially constructed 5604 // subobjects. 5605 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5606 5607 // If the destructor exists and has already been marked used in the MS ABI, 5608 // then virtual base destructors have already been checked and marked used. 5609 // Skip checking them again to avoid duplicate diagnostics. 5610 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5611 CXXDestructorDecl *Dtor = ClassDecl->getDestructor(); 5612 if (Dtor && Dtor->isUsed()) 5613 VisitVirtualBases = false; 5614 } 5615 5616 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5617 5618 // Bases. 5619 for (const auto &Base : ClassDecl->bases()) { 5620 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5621 if (!RT) 5622 continue; 5623 5624 // Remember direct virtual bases. 5625 if (Base.isVirtual()) { 5626 if (!VisitVirtualBases) 5627 continue; 5628 DirectVirtualBases.insert(RT); 5629 } 5630 5631 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5632 // If our base class is invalid, we probably can't get its dtor anyway. 5633 if (BaseClassDecl->isInvalidDecl()) 5634 continue; 5635 if (BaseClassDecl->hasIrrelevantDestructor()) 5636 continue; 5637 5638 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5639 assert(Dtor && "No dtor found for BaseClassDecl!"); 5640 5641 // FIXME: caret should be on the start of the class name 5642 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5643 PDiag(diag::err_access_dtor_base) 5644 << Base.getType() << Base.getSourceRange(), 5645 Context.getTypeDeclType(ClassDecl)); 5646 5647 MarkFunctionReferenced(Location, Dtor); 5648 DiagnoseUseOfDecl(Dtor, Location); 5649 } 5650 5651 if (VisitVirtualBases) 5652 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl, 5653 &DirectVirtualBases); 5654 } 5655 5656 void Sema::MarkVirtualBaseDestructorsReferenced( 5657 SourceLocation Location, CXXRecordDecl *ClassDecl, 5658 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) { 5659 // Virtual bases. 5660 for (const auto &VBase : ClassDecl->vbases()) { 5661 // Bases are always records in a well-formed non-dependent class. 5662 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5663 5664 // Ignore already visited direct virtual bases. 5665 if (DirectVirtualBases && DirectVirtualBases->count(RT)) 5666 continue; 5667 5668 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5669 // If our base class is invalid, we probably can't get its dtor anyway. 5670 if (BaseClassDecl->isInvalidDecl()) 5671 continue; 5672 if (BaseClassDecl->hasIrrelevantDestructor()) 5673 continue; 5674 5675 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5676 assert(Dtor && "No dtor found for BaseClassDecl!"); 5677 if (CheckDestructorAccess( 5678 ClassDecl->getLocation(), Dtor, 5679 PDiag(diag::err_access_dtor_vbase) 5680 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5681 Context.getTypeDeclType(ClassDecl)) == 5682 AR_accessible) { 5683 CheckDerivedToBaseConversion( 5684 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5685 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5686 SourceRange(), DeclarationName(), nullptr); 5687 } 5688 5689 MarkFunctionReferenced(Location, Dtor); 5690 DiagnoseUseOfDecl(Dtor, Location); 5691 } 5692 } 5693 5694 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5695 if (!CDtorDecl) 5696 return; 5697 5698 if (CXXConstructorDecl *Constructor 5699 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5700 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5701 DiagnoseUninitializedFields(*this, Constructor); 5702 } 5703 } 5704 5705 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5706 if (!getLangOpts().CPlusPlus) 5707 return false; 5708 5709 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5710 if (!RD) 5711 return false; 5712 5713 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5714 // class template specialization here, but doing so breaks a lot of code. 5715 5716 // We can't answer whether something is abstract until it has a 5717 // definition. If it's currently being defined, we'll walk back 5718 // over all the declarations when we have a full definition. 5719 const CXXRecordDecl *Def = RD->getDefinition(); 5720 if (!Def || Def->isBeingDefined()) 5721 return false; 5722 5723 return RD->isAbstract(); 5724 } 5725 5726 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5727 TypeDiagnoser &Diagnoser) { 5728 if (!isAbstractType(Loc, T)) 5729 return false; 5730 5731 T = Context.getBaseElementType(T); 5732 Diagnoser.diagnose(*this, Loc, T); 5733 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5734 return true; 5735 } 5736 5737 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5738 // Check if we've already emitted the list of pure virtual functions 5739 // for this class. 5740 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5741 return; 5742 5743 // If the diagnostic is suppressed, don't emit the notes. We're only 5744 // going to emit them once, so try to attach them to a diagnostic we're 5745 // actually going to show. 5746 if (Diags.isLastDiagnosticIgnored()) 5747 return; 5748 5749 CXXFinalOverriderMap FinalOverriders; 5750 RD->getFinalOverriders(FinalOverriders); 5751 5752 // Keep a set of seen pure methods so we won't diagnose the same method 5753 // more than once. 5754 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5755 5756 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5757 MEnd = FinalOverriders.end(); 5758 M != MEnd; 5759 ++M) { 5760 for (OverridingMethods::iterator SO = M->second.begin(), 5761 SOEnd = M->second.end(); 5762 SO != SOEnd; ++SO) { 5763 // C++ [class.abstract]p4: 5764 // A class is abstract if it contains or inherits at least one 5765 // pure virtual function for which the final overrider is pure 5766 // virtual. 5767 5768 // 5769 if (SO->second.size() != 1) 5770 continue; 5771 5772 if (!SO->second.front().Method->isPure()) 5773 continue; 5774 5775 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5776 continue; 5777 5778 Diag(SO->second.front().Method->getLocation(), 5779 diag::note_pure_virtual_function) 5780 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5781 } 5782 } 5783 5784 if (!PureVirtualClassDiagSet) 5785 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5786 PureVirtualClassDiagSet->insert(RD); 5787 } 5788 5789 namespace { 5790 struct AbstractUsageInfo { 5791 Sema &S; 5792 CXXRecordDecl *Record; 5793 CanQualType AbstractType; 5794 bool Invalid; 5795 5796 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5797 : S(S), Record(Record), 5798 AbstractType(S.Context.getCanonicalType( 5799 S.Context.getTypeDeclType(Record))), 5800 Invalid(false) {} 5801 5802 void DiagnoseAbstractType() { 5803 if (Invalid) return; 5804 S.DiagnoseAbstractType(Record); 5805 Invalid = true; 5806 } 5807 5808 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5809 }; 5810 5811 struct CheckAbstractUsage { 5812 AbstractUsageInfo &Info; 5813 const NamedDecl *Ctx; 5814 5815 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5816 : Info(Info), Ctx(Ctx) {} 5817 5818 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5819 switch (TL.getTypeLocClass()) { 5820 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5821 #define TYPELOC(CLASS, PARENT) \ 5822 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5823 #include "clang/AST/TypeLocNodes.def" 5824 } 5825 } 5826 5827 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5828 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5829 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5830 if (!TL.getParam(I)) 5831 continue; 5832 5833 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5834 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5835 } 5836 } 5837 5838 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5839 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5840 } 5841 5842 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5843 // Visit the type parameters from a permissive context. 5844 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5845 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5846 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5847 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5848 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5849 // TODO: other template argument types? 5850 } 5851 } 5852 5853 // Visit pointee types from a permissive context. 5854 #define CheckPolymorphic(Type) \ 5855 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5856 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5857 } 5858 CheckPolymorphic(PointerTypeLoc) 5859 CheckPolymorphic(ReferenceTypeLoc) 5860 CheckPolymorphic(MemberPointerTypeLoc) 5861 CheckPolymorphic(BlockPointerTypeLoc) 5862 CheckPolymorphic(AtomicTypeLoc) 5863 5864 /// Handle all the types we haven't given a more specific 5865 /// implementation for above. 5866 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5867 // Every other kind of type that we haven't called out already 5868 // that has an inner type is either (1) sugar or (2) contains that 5869 // inner type in some way as a subobject. 5870 if (TypeLoc Next = TL.getNextTypeLoc()) 5871 return Visit(Next, Sel); 5872 5873 // If there's no inner type and we're in a permissive context, 5874 // don't diagnose. 5875 if (Sel == Sema::AbstractNone) return; 5876 5877 // Check whether the type matches the abstract type. 5878 QualType T = TL.getType(); 5879 if (T->isArrayType()) { 5880 Sel = Sema::AbstractArrayType; 5881 T = Info.S.Context.getBaseElementType(T); 5882 } 5883 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5884 if (CT != Info.AbstractType) return; 5885 5886 // It matched; do some magic. 5887 if (Sel == Sema::AbstractArrayType) { 5888 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5889 << T << TL.getSourceRange(); 5890 } else { 5891 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5892 << Sel << T << TL.getSourceRange(); 5893 } 5894 Info.DiagnoseAbstractType(); 5895 } 5896 }; 5897 5898 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5899 Sema::AbstractDiagSelID Sel) { 5900 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5901 } 5902 5903 } 5904 5905 /// Check for invalid uses of an abstract type in a method declaration. 5906 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5907 CXXMethodDecl *MD) { 5908 // No need to do the check on definitions, which require that 5909 // the return/param types be complete. 5910 if (MD->doesThisDeclarationHaveABody()) 5911 return; 5912 5913 // For safety's sake, just ignore it if we don't have type source 5914 // information. This should never happen for non-implicit methods, 5915 // but... 5916 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5917 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5918 } 5919 5920 /// Check for invalid uses of an abstract type within a class definition. 5921 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5922 CXXRecordDecl *RD) { 5923 for (auto *D : RD->decls()) { 5924 if (D->isImplicit()) continue; 5925 5926 // Methods and method templates. 5927 if (isa<CXXMethodDecl>(D)) { 5928 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5929 } else if (isa<FunctionTemplateDecl>(D)) { 5930 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5931 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5932 5933 // Fields and static variables. 5934 } else if (isa<FieldDecl>(D)) { 5935 FieldDecl *FD = cast<FieldDecl>(D); 5936 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5937 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5938 } else if (isa<VarDecl>(D)) { 5939 VarDecl *VD = cast<VarDecl>(D); 5940 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5941 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5942 5943 // Nested classes and class templates. 5944 } else if (isa<CXXRecordDecl>(D)) { 5945 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5946 } else if (isa<ClassTemplateDecl>(D)) { 5947 CheckAbstractClassUsage(Info, 5948 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5949 } 5950 } 5951 } 5952 5953 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5954 Attr *ClassAttr = getDLLAttr(Class); 5955 if (!ClassAttr) 5956 return; 5957 5958 assert(ClassAttr->getKind() == attr::DLLExport); 5959 5960 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5961 5962 if (TSK == TSK_ExplicitInstantiationDeclaration) 5963 // Don't go any further if this is just an explicit instantiation 5964 // declaration. 5965 return; 5966 5967 // Add a context note to explain how we got to any diagnostics produced below. 5968 struct MarkingClassDllexported { 5969 Sema &S; 5970 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class, 5971 SourceLocation AttrLoc) 5972 : S(S) { 5973 Sema::CodeSynthesisContext Ctx; 5974 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported; 5975 Ctx.PointOfInstantiation = AttrLoc; 5976 Ctx.Entity = Class; 5977 S.pushCodeSynthesisContext(Ctx); 5978 } 5979 ~MarkingClassDllexported() { 5980 S.popCodeSynthesisContext(); 5981 } 5982 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); 5983 5984 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5985 S.MarkVTableUsed(Class->getLocation(), Class, true); 5986 5987 for (Decl *Member : Class->decls()) { 5988 // Skip members that were not marked exported. 5989 if (!Member->hasAttr<DLLExportAttr>()) 5990 continue; 5991 5992 // Defined static variables that are members of an exported base 5993 // class must be marked export too. 5994 auto *VD = dyn_cast<VarDecl>(Member); 5995 if (VD && VD->getStorageClass() == SC_Static && 5996 TSK == TSK_ImplicitInstantiation) 5997 S.MarkVariableReferenced(VD->getLocation(), VD); 5998 5999 auto *MD = dyn_cast<CXXMethodDecl>(Member); 6000 if (!MD) 6001 continue; 6002 6003 if (MD->isUserProvided()) { 6004 // Instantiate non-default class member functions ... 6005 6006 // .. except for certain kinds of template specializations. 6007 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 6008 continue; 6009 6010 // If this is an MS ABI dllexport default constructor, instantiate any 6011 // default arguments. 6012 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 6013 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6014 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) { 6015 S.InstantiateDefaultCtorDefaultArgs(CD); 6016 } 6017 } 6018 6019 S.MarkFunctionReferenced(Class->getLocation(), MD); 6020 6021 // The function will be passed to the consumer when its definition is 6022 // encountered. 6023 } else if (MD->isExplicitlyDefaulted()) { 6024 // Synthesize and instantiate explicitly defaulted methods. 6025 S.MarkFunctionReferenced(Class->getLocation(), MD); 6026 6027 if (TSK != TSK_ExplicitInstantiationDefinition) { 6028 // Except for explicit instantiation defs, we will not see the 6029 // definition again later, so pass it to the consumer now. 6030 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 6031 } 6032 } else if (!MD->isTrivial() || 6033 MD->isCopyAssignmentOperator() || 6034 MD->isMoveAssignmentOperator()) { 6035 // Synthesize and instantiate non-trivial implicit methods, and the copy 6036 // and move assignment operators. The latter are exported even if they 6037 // are trivial, because the address of an operator can be taken and 6038 // should compare equal across libraries. 6039 S.MarkFunctionReferenced(Class->getLocation(), MD); 6040 6041 // There is no later point when we will see the definition of this 6042 // function, so pass it to the consumer now. 6043 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 6044 } 6045 } 6046 } 6047 6048 static void checkForMultipleExportedDefaultConstructors(Sema &S, 6049 CXXRecordDecl *Class) { 6050 // Only the MS ABI has default constructor closures, so we don't need to do 6051 // this semantic checking anywhere else. 6052 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 6053 return; 6054 6055 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 6056 for (Decl *Member : Class->decls()) { 6057 // Look for exported default constructors. 6058 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 6059 if (!CD || !CD->isDefaultConstructor()) 6060 continue; 6061 auto *Attr = CD->getAttr<DLLExportAttr>(); 6062 if (!Attr) 6063 continue; 6064 6065 // If the class is non-dependent, mark the default arguments as ODR-used so 6066 // that we can properly codegen the constructor closure. 6067 if (!Class->isDependentContext()) { 6068 for (ParmVarDecl *PD : CD->parameters()) { 6069 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 6070 S.DiscardCleanupsInEvaluationContext(); 6071 } 6072 } 6073 6074 if (LastExportedDefaultCtor) { 6075 S.Diag(LastExportedDefaultCtor->getLocation(), 6076 diag::err_attribute_dll_ambiguous_default_ctor) 6077 << Class; 6078 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 6079 << CD->getDeclName(); 6080 return; 6081 } 6082 LastExportedDefaultCtor = CD; 6083 } 6084 } 6085 6086 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, 6087 CXXRecordDecl *Class) { 6088 bool ErrorReported = false; 6089 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6090 ClassTemplateDecl *TD) { 6091 if (ErrorReported) 6092 return; 6093 S.Diag(TD->getLocation(), 6094 diag::err_cuda_device_builtin_surftex_cls_template) 6095 << /*surface*/ 0 << TD; 6096 ErrorReported = true; 6097 }; 6098 6099 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6100 if (!TD) { 6101 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6102 if (!SD) { 6103 S.Diag(Class->getLocation(), 6104 diag::err_cuda_device_builtin_surftex_ref_decl) 6105 << /*surface*/ 0 << Class; 6106 S.Diag(Class->getLocation(), 6107 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6108 << Class; 6109 return; 6110 } 6111 TD = SD->getSpecializedTemplate(); 6112 } 6113 6114 TemplateParameterList *Params = TD->getTemplateParameters(); 6115 unsigned N = Params->size(); 6116 6117 if (N != 2) { 6118 reportIllegalClassTemplate(S, TD); 6119 S.Diag(TD->getLocation(), 6120 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6121 << TD << 2; 6122 } 6123 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6124 reportIllegalClassTemplate(S, TD); 6125 S.Diag(TD->getLocation(), 6126 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6127 << TD << /*1st*/ 0 << /*type*/ 0; 6128 } 6129 if (N > 1) { 6130 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6131 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6132 reportIllegalClassTemplate(S, TD); 6133 S.Diag(TD->getLocation(), 6134 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6135 << TD << /*2nd*/ 1 << /*integer*/ 1; 6136 } 6137 } 6138 } 6139 6140 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, 6141 CXXRecordDecl *Class) { 6142 bool ErrorReported = false; 6143 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6144 ClassTemplateDecl *TD) { 6145 if (ErrorReported) 6146 return; 6147 S.Diag(TD->getLocation(), 6148 diag::err_cuda_device_builtin_surftex_cls_template) 6149 << /*texture*/ 1 << TD; 6150 ErrorReported = true; 6151 }; 6152 6153 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6154 if (!TD) { 6155 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6156 if (!SD) { 6157 S.Diag(Class->getLocation(), 6158 diag::err_cuda_device_builtin_surftex_ref_decl) 6159 << /*texture*/ 1 << Class; 6160 S.Diag(Class->getLocation(), 6161 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6162 << Class; 6163 return; 6164 } 6165 TD = SD->getSpecializedTemplate(); 6166 } 6167 6168 TemplateParameterList *Params = TD->getTemplateParameters(); 6169 unsigned N = Params->size(); 6170 6171 if (N != 3) { 6172 reportIllegalClassTemplate(S, TD); 6173 S.Diag(TD->getLocation(), 6174 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6175 << TD << 3; 6176 } 6177 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6178 reportIllegalClassTemplate(S, TD); 6179 S.Diag(TD->getLocation(), 6180 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6181 << TD << /*1st*/ 0 << /*type*/ 0; 6182 } 6183 if (N > 1) { 6184 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6185 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6186 reportIllegalClassTemplate(S, TD); 6187 S.Diag(TD->getLocation(), 6188 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6189 << TD << /*2nd*/ 1 << /*integer*/ 1; 6190 } 6191 } 6192 if (N > 2) { 6193 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2)); 6194 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6195 reportIllegalClassTemplate(S, TD); 6196 S.Diag(TD->getLocation(), 6197 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6198 << TD << /*3rd*/ 2 << /*integer*/ 1; 6199 } 6200 } 6201 } 6202 6203 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 6204 // Mark any compiler-generated routines with the implicit code_seg attribute. 6205 for (auto *Method : Class->methods()) { 6206 if (Method->isUserProvided()) 6207 continue; 6208 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 6209 Method->addAttr(A); 6210 } 6211 } 6212 6213 /// Check class-level dllimport/dllexport attribute. 6214 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 6215 Attr *ClassAttr = getDLLAttr(Class); 6216 6217 // MSVC inherits DLL attributes to partial class template specializations. 6218 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) { 6219 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 6220 if (Attr *TemplateAttr = 6221 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 6222 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 6223 A->setInherited(true); 6224 ClassAttr = A; 6225 } 6226 } 6227 } 6228 6229 if (!ClassAttr) 6230 return; 6231 6232 if (!Class->isExternallyVisible()) { 6233 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 6234 << Class << ClassAttr; 6235 return; 6236 } 6237 6238 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6239 !ClassAttr->isInherited()) { 6240 // Diagnose dll attributes on members of class with dll attribute. 6241 for (Decl *Member : Class->decls()) { 6242 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 6243 continue; 6244 InheritableAttr *MemberAttr = getDLLAttr(Member); 6245 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 6246 continue; 6247 6248 Diag(MemberAttr->getLocation(), 6249 diag::err_attribute_dll_member_of_dll_class) 6250 << MemberAttr << ClassAttr; 6251 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 6252 Member->setInvalidDecl(); 6253 } 6254 } 6255 6256 if (Class->getDescribedClassTemplate()) 6257 // Don't inherit dll attribute until the template is instantiated. 6258 return; 6259 6260 // The class is either imported or exported. 6261 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 6262 6263 // Check if this was a dllimport attribute propagated from a derived class to 6264 // a base class template specialization. We don't apply these attributes to 6265 // static data members. 6266 const bool PropagatedImport = 6267 !ClassExported && 6268 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 6269 6270 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6271 6272 // Ignore explicit dllexport on explicit class template instantiation 6273 // declarations, except in MinGW mode. 6274 if (ClassExported && !ClassAttr->isInherited() && 6275 TSK == TSK_ExplicitInstantiationDeclaration && 6276 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 6277 Class->dropAttr<DLLExportAttr>(); 6278 return; 6279 } 6280 6281 // Force declaration of implicit members so they can inherit the attribute. 6282 ForceDeclarationOfImplicitMembers(Class); 6283 6284 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 6285 // seem to be true in practice? 6286 6287 for (Decl *Member : Class->decls()) { 6288 VarDecl *VD = dyn_cast<VarDecl>(Member); 6289 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 6290 6291 // Only methods and static fields inherit the attributes. 6292 if (!VD && !MD) 6293 continue; 6294 6295 if (MD) { 6296 // Don't process deleted methods. 6297 if (MD->isDeleted()) 6298 continue; 6299 6300 if (MD->isInlined()) { 6301 // MinGW does not import or export inline methods. But do it for 6302 // template instantiations. 6303 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6304 TSK != TSK_ExplicitInstantiationDeclaration && 6305 TSK != TSK_ExplicitInstantiationDefinition) 6306 continue; 6307 6308 // MSVC versions before 2015 don't export the move assignment operators 6309 // and move constructor, so don't attempt to import/export them if 6310 // we have a definition. 6311 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 6312 if ((MD->isMoveAssignmentOperator() || 6313 (Ctor && Ctor->isMoveConstructor())) && 6314 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 6315 continue; 6316 6317 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 6318 // operator is exported anyway. 6319 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6320 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 6321 continue; 6322 } 6323 } 6324 6325 // Don't apply dllimport attributes to static data members of class template 6326 // instantiations when the attribute is propagated from a derived class. 6327 if (VD && PropagatedImport) 6328 continue; 6329 6330 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6331 continue; 6332 6333 if (!getDLLAttr(Member)) { 6334 InheritableAttr *NewAttr = nullptr; 6335 6336 // Do not export/import inline function when -fno-dllexport-inlines is 6337 // passed. But add attribute for later local static var check. 6338 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6339 TSK != TSK_ExplicitInstantiationDeclaration && 6340 TSK != TSK_ExplicitInstantiationDefinition) { 6341 if (ClassExported) { 6342 NewAttr = ::new (getASTContext()) 6343 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6344 } else { 6345 NewAttr = ::new (getASTContext()) 6346 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6347 } 6348 } else { 6349 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6350 } 6351 6352 NewAttr->setInherited(true); 6353 Member->addAttr(NewAttr); 6354 6355 if (MD) { 6356 // Propagate DLLAttr to friend re-declarations of MD that have already 6357 // been constructed. 6358 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6359 FD = FD->getPreviousDecl()) { 6360 if (FD->getFriendObjectKind() == Decl::FOK_None) 6361 continue; 6362 assert(!getDLLAttr(FD) && 6363 "friend re-decl should not already have a DLLAttr"); 6364 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6365 NewAttr->setInherited(true); 6366 FD->addAttr(NewAttr); 6367 } 6368 } 6369 } 6370 } 6371 6372 if (ClassExported) 6373 DelayedDllExportClasses.push_back(Class); 6374 } 6375 6376 /// Perform propagation of DLL attributes from a derived class to a 6377 /// templated base class for MS compatibility. 6378 void Sema::propagateDLLAttrToBaseClassTemplate( 6379 CXXRecordDecl *Class, Attr *ClassAttr, 6380 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6381 if (getDLLAttr( 6382 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6383 // If the base class template has a DLL attribute, don't try to change it. 6384 return; 6385 } 6386 6387 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6388 if (!getDLLAttr(BaseTemplateSpec) && 6389 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6390 TSK == TSK_ImplicitInstantiation)) { 6391 // The template hasn't been instantiated yet (or it has, but only as an 6392 // explicit instantiation declaration or implicit instantiation, which means 6393 // we haven't codegenned any members yet), so propagate the attribute. 6394 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6395 NewAttr->setInherited(true); 6396 BaseTemplateSpec->addAttr(NewAttr); 6397 6398 // If this was an import, mark that we propagated it from a derived class to 6399 // a base class template specialization. 6400 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6401 ImportAttr->setPropagatedToBaseTemplate(); 6402 6403 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6404 // needs to be run again to work see the new attribute. Otherwise this will 6405 // get run whenever the template is instantiated. 6406 if (TSK != TSK_Undeclared) 6407 checkClassLevelDLLAttribute(BaseTemplateSpec); 6408 6409 return; 6410 } 6411 6412 if (getDLLAttr(BaseTemplateSpec)) { 6413 // The template has already been specialized or instantiated with an 6414 // attribute, explicitly or through propagation. We should not try to change 6415 // it. 6416 return; 6417 } 6418 6419 // The template was previously instantiated or explicitly specialized without 6420 // a dll attribute, It's too late for us to add an attribute, so warn that 6421 // this is unsupported. 6422 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6423 << BaseTemplateSpec->isExplicitSpecialization(); 6424 Diag(ClassAttr->getLocation(), diag::note_attribute); 6425 if (BaseTemplateSpec->isExplicitSpecialization()) { 6426 Diag(BaseTemplateSpec->getLocation(), 6427 diag::note_template_class_explicit_specialization_was_here) 6428 << BaseTemplateSpec; 6429 } else { 6430 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6431 diag::note_template_class_instantiation_was_here) 6432 << BaseTemplateSpec; 6433 } 6434 } 6435 6436 /// Determine the kind of defaulting that would be done for a given function. 6437 /// 6438 /// If the function is both a default constructor and a copy / move constructor 6439 /// (due to having a default argument for the first parameter), this picks 6440 /// CXXDefaultConstructor. 6441 /// 6442 /// FIXME: Check that case is properly handled by all callers. 6443 Sema::DefaultedFunctionKind 6444 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6445 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6446 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6447 if (Ctor->isDefaultConstructor()) 6448 return Sema::CXXDefaultConstructor; 6449 6450 if (Ctor->isCopyConstructor()) 6451 return Sema::CXXCopyConstructor; 6452 6453 if (Ctor->isMoveConstructor()) 6454 return Sema::CXXMoveConstructor; 6455 } 6456 6457 if (MD->isCopyAssignmentOperator()) 6458 return Sema::CXXCopyAssignment; 6459 6460 if (MD->isMoveAssignmentOperator()) 6461 return Sema::CXXMoveAssignment; 6462 6463 if (isa<CXXDestructorDecl>(FD)) 6464 return Sema::CXXDestructor; 6465 } 6466 6467 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6468 case OO_EqualEqual: 6469 return DefaultedComparisonKind::Equal; 6470 6471 case OO_ExclaimEqual: 6472 return DefaultedComparisonKind::NotEqual; 6473 6474 case OO_Spaceship: 6475 // No point allowing this if <=> doesn't exist in the current language mode. 6476 if (!getLangOpts().CPlusPlus20) 6477 break; 6478 return DefaultedComparisonKind::ThreeWay; 6479 6480 case OO_Less: 6481 case OO_LessEqual: 6482 case OO_Greater: 6483 case OO_GreaterEqual: 6484 // No point allowing this if <=> doesn't exist in the current language mode. 6485 if (!getLangOpts().CPlusPlus20) 6486 break; 6487 return DefaultedComparisonKind::Relational; 6488 6489 default: 6490 break; 6491 } 6492 6493 // Not defaultable. 6494 return DefaultedFunctionKind(); 6495 } 6496 6497 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, 6498 SourceLocation DefaultLoc) { 6499 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD); 6500 if (DFK.isComparison()) 6501 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison()); 6502 6503 switch (DFK.asSpecialMember()) { 6504 case Sema::CXXDefaultConstructor: 6505 S.DefineImplicitDefaultConstructor(DefaultLoc, 6506 cast<CXXConstructorDecl>(FD)); 6507 break; 6508 case Sema::CXXCopyConstructor: 6509 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6510 break; 6511 case Sema::CXXCopyAssignment: 6512 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6513 break; 6514 case Sema::CXXDestructor: 6515 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD)); 6516 break; 6517 case Sema::CXXMoveConstructor: 6518 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6519 break; 6520 case Sema::CXXMoveAssignment: 6521 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6522 break; 6523 case Sema::CXXInvalid: 6524 llvm_unreachable("Invalid special member."); 6525 } 6526 } 6527 6528 /// Determine whether a type is permitted to be passed or returned in 6529 /// registers, per C++ [class.temporary]p3. 6530 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6531 TargetInfo::CallingConvKind CCK) { 6532 if (D->isDependentType() || D->isInvalidDecl()) 6533 return false; 6534 6535 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6536 // The PS4 platform ABI follows the behavior of Clang 3.2. 6537 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6538 return !D->hasNonTrivialDestructorForCall() && 6539 !D->hasNonTrivialCopyConstructorForCall(); 6540 6541 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6542 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6543 bool DtorIsTrivialForCall = false; 6544 6545 // If a class has at least one non-deleted, trivial copy constructor, it 6546 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6547 // 6548 // Note: This permits classes with non-trivial copy or move ctors to be 6549 // passed in registers, so long as they *also* have a trivial copy ctor, 6550 // which is non-conforming. 6551 if (D->needsImplicitCopyConstructor()) { 6552 if (!D->defaultedCopyConstructorIsDeleted()) { 6553 if (D->hasTrivialCopyConstructor()) 6554 CopyCtorIsTrivial = true; 6555 if (D->hasTrivialCopyConstructorForCall()) 6556 CopyCtorIsTrivialForCall = true; 6557 } 6558 } else { 6559 for (const CXXConstructorDecl *CD : D->ctors()) { 6560 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6561 if (CD->isTrivial()) 6562 CopyCtorIsTrivial = true; 6563 if (CD->isTrivialForCall()) 6564 CopyCtorIsTrivialForCall = true; 6565 } 6566 } 6567 } 6568 6569 if (D->needsImplicitDestructor()) { 6570 if (!D->defaultedDestructorIsDeleted() && 6571 D->hasTrivialDestructorForCall()) 6572 DtorIsTrivialForCall = true; 6573 } else if (const auto *DD = D->getDestructor()) { 6574 if (!DD->isDeleted() && DD->isTrivialForCall()) 6575 DtorIsTrivialForCall = true; 6576 } 6577 6578 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6579 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6580 return true; 6581 6582 // If a class has a destructor, we'd really like to pass it indirectly 6583 // because it allows us to elide copies. Unfortunately, MSVC makes that 6584 // impossible for small types, which it will pass in a single register or 6585 // stack slot. Most objects with dtors are large-ish, so handle that early. 6586 // We can't call out all large objects as being indirect because there are 6587 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6588 // how we pass large POD types. 6589 6590 // Note: This permits small classes with nontrivial destructors to be 6591 // passed in registers, which is non-conforming. 6592 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6593 uint64_t TypeSize = isAArch64 ? 128 : 64; 6594 6595 if (CopyCtorIsTrivial && 6596 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6597 return true; 6598 return false; 6599 } 6600 6601 // Per C++ [class.temporary]p3, the relevant condition is: 6602 // each copy constructor, move constructor, and destructor of X is 6603 // either trivial or deleted, and X has at least one non-deleted copy 6604 // or move constructor 6605 bool HasNonDeletedCopyOrMove = false; 6606 6607 if (D->needsImplicitCopyConstructor() && 6608 !D->defaultedCopyConstructorIsDeleted()) { 6609 if (!D->hasTrivialCopyConstructorForCall()) 6610 return false; 6611 HasNonDeletedCopyOrMove = true; 6612 } 6613 6614 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6615 !D->defaultedMoveConstructorIsDeleted()) { 6616 if (!D->hasTrivialMoveConstructorForCall()) 6617 return false; 6618 HasNonDeletedCopyOrMove = true; 6619 } 6620 6621 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6622 !D->hasTrivialDestructorForCall()) 6623 return false; 6624 6625 for (const CXXMethodDecl *MD : D->methods()) { 6626 if (MD->isDeleted()) 6627 continue; 6628 6629 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6630 if (CD && CD->isCopyOrMoveConstructor()) 6631 HasNonDeletedCopyOrMove = true; 6632 else if (!isa<CXXDestructorDecl>(MD)) 6633 continue; 6634 6635 if (!MD->isTrivialForCall()) 6636 return false; 6637 } 6638 6639 return HasNonDeletedCopyOrMove; 6640 } 6641 6642 /// Report an error regarding overriding, along with any relevant 6643 /// overridden methods. 6644 /// 6645 /// \param DiagID the primary error to report. 6646 /// \param MD the overriding method. 6647 static bool 6648 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, 6649 llvm::function_ref<bool(const CXXMethodDecl *)> Report) { 6650 bool IssuedDiagnostic = false; 6651 for (const CXXMethodDecl *O : MD->overridden_methods()) { 6652 if (Report(O)) { 6653 if (!IssuedDiagnostic) { 6654 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6655 IssuedDiagnostic = true; 6656 } 6657 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 6658 } 6659 } 6660 return IssuedDiagnostic; 6661 } 6662 6663 /// Perform semantic checks on a class definition that has been 6664 /// completing, introducing implicitly-declared members, checking for 6665 /// abstract types, etc. 6666 /// 6667 /// \param S The scope in which the class was parsed. Null if we didn't just 6668 /// parse a class definition. 6669 /// \param Record The completed class. 6670 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6671 if (!Record) 6672 return; 6673 6674 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6675 AbstractUsageInfo Info(*this, Record); 6676 CheckAbstractClassUsage(Info, Record); 6677 } 6678 6679 // If this is not an aggregate type and has no user-declared constructor, 6680 // complain about any non-static data members of reference or const scalar 6681 // type, since they will never get initializers. 6682 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6683 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6684 !Record->isLambda()) { 6685 bool Complained = false; 6686 for (const auto *F : Record->fields()) { 6687 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6688 continue; 6689 6690 if (F->getType()->isReferenceType() || 6691 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6692 if (!Complained) { 6693 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6694 << Record->getTagKind() << Record; 6695 Complained = true; 6696 } 6697 6698 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6699 << F->getType()->isReferenceType() 6700 << F->getDeclName(); 6701 } 6702 } 6703 } 6704 6705 if (Record->getIdentifier()) { 6706 // C++ [class.mem]p13: 6707 // If T is the name of a class, then each of the following shall have a 6708 // name different from T: 6709 // - every member of every anonymous union that is a member of class T. 6710 // 6711 // C++ [class.mem]p14: 6712 // In addition, if class T has a user-declared constructor (12.1), every 6713 // non-static data member of class T shall have a name different from T. 6714 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6715 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6716 ++I) { 6717 NamedDecl *D = (*I)->getUnderlyingDecl(); 6718 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6719 Record->hasUserDeclaredConstructor()) || 6720 isa<IndirectFieldDecl>(D)) { 6721 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6722 << D->getDeclName(); 6723 break; 6724 } 6725 } 6726 } 6727 6728 // Warn if the class has virtual methods but non-virtual public destructor. 6729 if (Record->isPolymorphic() && !Record->isDependentType()) { 6730 CXXDestructorDecl *dtor = Record->getDestructor(); 6731 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6732 !Record->hasAttr<FinalAttr>()) 6733 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6734 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6735 } 6736 6737 if (Record->isAbstract()) { 6738 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6739 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6740 << FA->isSpelledAsSealed(); 6741 DiagnoseAbstractType(Record); 6742 } 6743 } 6744 6745 // Warn if the class has a final destructor but is not itself marked final. 6746 if (!Record->hasAttr<FinalAttr>()) { 6747 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6748 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6749 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6750 << FA->isSpelledAsSealed() 6751 << FixItHint::CreateInsertion( 6752 getLocForEndOfToken(Record->getLocation()), 6753 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6754 Diag(Record->getLocation(), 6755 diag::note_final_dtor_non_final_class_silence) 6756 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6757 } 6758 } 6759 } 6760 6761 // See if trivial_abi has to be dropped. 6762 if (Record->hasAttr<TrivialABIAttr>()) 6763 checkIllFormedTrivialABIStruct(*Record); 6764 6765 // Set HasTrivialSpecialMemberForCall if the record has attribute 6766 // "trivial_abi". 6767 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6768 6769 if (HasTrivialABI) 6770 Record->setHasTrivialSpecialMemberForCall(); 6771 6772 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6773 // We check these last because they can depend on the properties of the 6774 // primary comparison functions (==, <=>). 6775 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6776 6777 // Perform checks that can't be done until we know all the properties of a 6778 // member function (whether it's defaulted, deleted, virtual, overriding, 6779 // ...). 6780 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) { 6781 // A static function cannot override anything. 6782 if (MD->getStorageClass() == SC_Static) { 6783 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD, 6784 [](const CXXMethodDecl *) { return true; })) 6785 return; 6786 } 6787 6788 // A deleted function cannot override a non-deleted function and vice 6789 // versa. 6790 if (ReportOverrides(*this, 6791 MD->isDeleted() ? diag::err_deleted_override 6792 : diag::err_non_deleted_override, 6793 MD, [&](const CXXMethodDecl *V) { 6794 return MD->isDeleted() != V->isDeleted(); 6795 })) { 6796 if (MD->isDefaulted() && MD->isDeleted()) 6797 // Explain why this defaulted function was deleted. 6798 DiagnoseDeletedDefaultedFunction(MD); 6799 return; 6800 } 6801 6802 // A consteval function cannot override a non-consteval function and vice 6803 // versa. 6804 if (ReportOverrides(*this, 6805 MD->isConsteval() ? diag::err_consteval_override 6806 : diag::err_non_consteval_override, 6807 MD, [&](const CXXMethodDecl *V) { 6808 return MD->isConsteval() != V->isConsteval(); 6809 })) { 6810 if (MD->isDefaulted() && MD->isDeleted()) 6811 // Explain why this defaulted function was deleted. 6812 DiagnoseDeletedDefaultedFunction(MD); 6813 return; 6814 } 6815 }; 6816 6817 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool { 6818 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6819 return false; 6820 6821 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6822 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6823 DFK.asComparison() == DefaultedComparisonKind::Relational) { 6824 DefaultedSecondaryComparisons.push_back(FD); 6825 return true; 6826 } 6827 6828 CheckExplicitlyDefaultedFunction(S, FD); 6829 return false; 6830 }; 6831 6832 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6833 // Check whether the explicitly-defaulted members are valid. 6834 bool Incomplete = CheckForDefaultedFunction(M); 6835 6836 // Skip the rest of the checks for a member of a dependent class. 6837 if (Record->isDependentType()) 6838 return; 6839 6840 // For an explicitly defaulted or deleted special member, we defer 6841 // determining triviality until the class is complete. That time is now! 6842 CXXSpecialMember CSM = getSpecialMember(M); 6843 if (!M->isImplicit() && !M->isUserProvided()) { 6844 if (CSM != CXXInvalid) { 6845 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6846 // Inform the class that we've finished declaring this member. 6847 Record->finishedDefaultedOrDeletedMember(M); 6848 M->setTrivialForCall( 6849 HasTrivialABI || 6850 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6851 Record->setTrivialForCallFlags(M); 6852 } 6853 } 6854 6855 // Set triviality for the purpose of calls if this is a user-provided 6856 // copy/move constructor or destructor. 6857 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6858 CSM == CXXDestructor) && M->isUserProvided()) { 6859 M->setTrivialForCall(HasTrivialABI); 6860 Record->setTrivialForCallFlags(M); 6861 } 6862 6863 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6864 M->hasAttr<DLLExportAttr>()) { 6865 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6866 M->isTrivial() && 6867 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6868 CSM == CXXDestructor)) 6869 M->dropAttr<DLLExportAttr>(); 6870 6871 if (M->hasAttr<DLLExportAttr>()) { 6872 // Define after any fields with in-class initializers have been parsed. 6873 DelayedDllExportMemberFunctions.push_back(M); 6874 } 6875 } 6876 6877 // Define defaulted constexpr virtual functions that override a base class 6878 // function right away. 6879 // FIXME: We can defer doing this until the vtable is marked as used. 6880 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6881 DefineDefaultedFunction(*this, M, M->getLocation()); 6882 6883 if (!Incomplete) 6884 CheckCompletedMemberFunction(M); 6885 }; 6886 6887 // Check the destructor before any other member function. We need to 6888 // determine whether it's trivial in order to determine whether the claas 6889 // type is a literal type, which is a prerequisite for determining whether 6890 // other special member functions are valid and whether they're implicitly 6891 // 'constexpr'. 6892 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6893 CompleteMemberFunction(Dtor); 6894 6895 bool HasMethodWithOverrideControl = false, 6896 HasOverridingMethodWithoutOverrideControl = false; 6897 for (auto *D : Record->decls()) { 6898 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 6899 // FIXME: We could do this check for dependent types with non-dependent 6900 // bases. 6901 if (!Record->isDependentType()) { 6902 // See if a method overloads virtual methods in a base 6903 // class without overriding any. 6904 if (!M->isStatic()) 6905 DiagnoseHiddenVirtualMethods(M); 6906 if (M->hasAttr<OverrideAttr>()) 6907 HasMethodWithOverrideControl = true; 6908 else if (M->size_overridden_methods() > 0) 6909 HasOverridingMethodWithoutOverrideControl = true; 6910 } 6911 6912 if (!isa<CXXDestructorDecl>(M)) 6913 CompleteMemberFunction(M); 6914 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 6915 CheckForDefaultedFunction( 6916 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 6917 } 6918 } 6919 6920 if (HasOverridingMethodWithoutOverrideControl) { 6921 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl; 6922 for (auto *M : Record->methods()) 6923 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl); 6924 } 6925 6926 // Check the defaulted secondary comparisons after any other member functions. 6927 for (FunctionDecl *FD : DefaultedSecondaryComparisons) { 6928 CheckExplicitlyDefaultedFunction(S, FD); 6929 6930 // If this is a member function, we deferred checking it until now. 6931 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) 6932 CheckCompletedMemberFunction(MD); 6933 } 6934 6935 // ms_struct is a request to use the same ABI rules as MSVC. Check 6936 // whether this class uses any C++ features that are implemented 6937 // completely differently in MSVC, and if so, emit a diagnostic. 6938 // That diagnostic defaults to an error, but we allow projects to 6939 // map it down to a warning (or ignore it). It's a fairly common 6940 // practice among users of the ms_struct pragma to mass-annotate 6941 // headers, sweeping up a bunch of types that the project doesn't 6942 // really rely on MSVC-compatible layout for. We must therefore 6943 // support "ms_struct except for C++ stuff" as a secondary ABI. 6944 // Don't emit this diagnostic if the feature was enabled as a 6945 // language option (as opposed to via a pragma or attribute), as 6946 // the option -mms-bitfields otherwise essentially makes it impossible 6947 // to build C++ code, unless this diagnostic is turned off. 6948 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields && 6949 (Record->isPolymorphic() || Record->getNumBases())) { 6950 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6951 } 6952 6953 checkClassLevelDLLAttribute(Record); 6954 checkClassLevelCodeSegAttribute(Record); 6955 6956 bool ClangABICompat4 = 6957 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6958 TargetInfo::CallingConvKind CCK = 6959 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6960 bool CanPass = canPassInRegisters(*this, Record, CCK); 6961 6962 // Do not change ArgPassingRestrictions if it has already been set to 6963 // APK_CanNeverPassInRegs. 6964 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6965 Record->setArgPassingRestrictions(CanPass 6966 ? RecordDecl::APK_CanPassInRegs 6967 : RecordDecl::APK_CannotPassInRegs); 6968 6969 // If canPassInRegisters returns true despite the record having a non-trivial 6970 // destructor, the record is destructed in the callee. This happens only when 6971 // the record or one of its subobjects has a field annotated with trivial_abi 6972 // or a field qualified with ObjC __strong/__weak. 6973 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6974 Record->setParamDestroyedInCallee(true); 6975 else if (Record->hasNonTrivialDestructor()) 6976 Record->setParamDestroyedInCallee(CanPass); 6977 6978 if (getLangOpts().ForceEmitVTables) { 6979 // If we want to emit all the vtables, we need to mark it as used. This 6980 // is especially required for cases like vtable assumption loads. 6981 MarkVTableUsed(Record->getInnerLocStart(), Record); 6982 } 6983 6984 if (getLangOpts().CUDA) { 6985 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) 6986 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record); 6987 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>()) 6988 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record); 6989 } 6990 } 6991 6992 /// Look up the special member function that would be called by a special 6993 /// member function for a subobject of class type. 6994 /// 6995 /// \param Class The class type of the subobject. 6996 /// \param CSM The kind of special member function. 6997 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6998 /// \param ConstRHS True if this is a copy operation with a const object 6999 /// on its RHS, that is, if the argument to the outer special member 7000 /// function is 'const' and this is not a field marked 'mutable'. 7001 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 7002 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 7003 unsigned FieldQuals, bool ConstRHS) { 7004 unsigned LHSQuals = 0; 7005 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 7006 LHSQuals = FieldQuals; 7007 7008 unsigned RHSQuals = FieldQuals; 7009 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 7010 RHSQuals = 0; 7011 else if (ConstRHS) 7012 RHSQuals |= Qualifiers::Const; 7013 7014 return S.LookupSpecialMember(Class, CSM, 7015 RHSQuals & Qualifiers::Const, 7016 RHSQuals & Qualifiers::Volatile, 7017 false, 7018 LHSQuals & Qualifiers::Const, 7019 LHSQuals & Qualifiers::Volatile); 7020 } 7021 7022 class Sema::InheritedConstructorInfo { 7023 Sema &S; 7024 SourceLocation UseLoc; 7025 7026 /// A mapping from the base classes through which the constructor was 7027 /// inherited to the using shadow declaration in that base class (or a null 7028 /// pointer if the constructor was declared in that base class). 7029 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 7030 InheritedFromBases; 7031 7032 public: 7033 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 7034 ConstructorUsingShadowDecl *Shadow) 7035 : S(S), UseLoc(UseLoc) { 7036 bool DiagnosedMultipleConstructedBases = false; 7037 CXXRecordDecl *ConstructedBase = nullptr; 7038 BaseUsingDecl *ConstructedBaseIntroducer = nullptr; 7039 7040 // Find the set of such base class subobjects and check that there's a 7041 // unique constructed subobject. 7042 for (auto *D : Shadow->redecls()) { 7043 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 7044 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 7045 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 7046 7047 InheritedFromBases.insert( 7048 std::make_pair(DNominatedBase->getCanonicalDecl(), 7049 DShadow->getNominatedBaseClassShadowDecl())); 7050 if (DShadow->constructsVirtualBase()) 7051 InheritedFromBases.insert( 7052 std::make_pair(DConstructedBase->getCanonicalDecl(), 7053 DShadow->getConstructedBaseClassShadowDecl())); 7054 else 7055 assert(DNominatedBase == DConstructedBase); 7056 7057 // [class.inhctor.init]p2: 7058 // If the constructor was inherited from multiple base class subobjects 7059 // of type B, the program is ill-formed. 7060 if (!ConstructedBase) { 7061 ConstructedBase = DConstructedBase; 7062 ConstructedBaseIntroducer = D->getIntroducer(); 7063 } else if (ConstructedBase != DConstructedBase && 7064 !Shadow->isInvalidDecl()) { 7065 if (!DiagnosedMultipleConstructedBases) { 7066 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 7067 << Shadow->getTargetDecl(); 7068 S.Diag(ConstructedBaseIntroducer->getLocation(), 7069 diag::note_ambiguous_inherited_constructor_using) 7070 << ConstructedBase; 7071 DiagnosedMultipleConstructedBases = true; 7072 } 7073 S.Diag(D->getIntroducer()->getLocation(), 7074 diag::note_ambiguous_inherited_constructor_using) 7075 << DConstructedBase; 7076 } 7077 } 7078 7079 if (DiagnosedMultipleConstructedBases) 7080 Shadow->setInvalidDecl(); 7081 } 7082 7083 /// Find the constructor to use for inherited construction of a base class, 7084 /// and whether that base class constructor inherits the constructor from a 7085 /// virtual base class (in which case it won't actually invoke it). 7086 std::pair<CXXConstructorDecl *, bool> 7087 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 7088 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 7089 if (It == InheritedFromBases.end()) 7090 return std::make_pair(nullptr, false); 7091 7092 // This is an intermediary class. 7093 if (It->second) 7094 return std::make_pair( 7095 S.findInheritingConstructor(UseLoc, Ctor, It->second), 7096 It->second->constructsVirtualBase()); 7097 7098 // This is the base class from which the constructor was inherited. 7099 return std::make_pair(Ctor, false); 7100 } 7101 }; 7102 7103 /// Is the special member function which would be selected to perform the 7104 /// specified operation on the specified class type a constexpr constructor? 7105 static bool 7106 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 7107 Sema::CXXSpecialMember CSM, unsigned Quals, 7108 bool ConstRHS, 7109 CXXConstructorDecl *InheritedCtor = nullptr, 7110 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7111 // If we're inheriting a constructor, see if we need to call it for this base 7112 // class. 7113 if (InheritedCtor) { 7114 assert(CSM == Sema::CXXDefaultConstructor); 7115 auto BaseCtor = 7116 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 7117 if (BaseCtor) 7118 return BaseCtor->isConstexpr(); 7119 } 7120 7121 if (CSM == Sema::CXXDefaultConstructor) 7122 return ClassDecl->hasConstexprDefaultConstructor(); 7123 if (CSM == Sema::CXXDestructor) 7124 return ClassDecl->hasConstexprDestructor(); 7125 7126 Sema::SpecialMemberOverloadResult SMOR = 7127 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 7128 if (!SMOR.getMethod()) 7129 // A constructor we wouldn't select can't be "involved in initializing" 7130 // anything. 7131 return true; 7132 return SMOR.getMethod()->isConstexpr(); 7133 } 7134 7135 /// Determine whether the specified special member function would be constexpr 7136 /// if it were implicitly defined. 7137 static bool defaultedSpecialMemberIsConstexpr( 7138 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 7139 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 7140 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7141 if (!S.getLangOpts().CPlusPlus11) 7142 return false; 7143 7144 // C++11 [dcl.constexpr]p4: 7145 // In the definition of a constexpr constructor [...] 7146 bool Ctor = true; 7147 switch (CSM) { 7148 case Sema::CXXDefaultConstructor: 7149 if (Inherited) 7150 break; 7151 // Since default constructor lookup is essentially trivial (and cannot 7152 // involve, for instance, template instantiation), we compute whether a 7153 // defaulted default constructor is constexpr directly within CXXRecordDecl. 7154 // 7155 // This is important for performance; we need to know whether the default 7156 // constructor is constexpr to determine whether the type is a literal type. 7157 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 7158 7159 case Sema::CXXCopyConstructor: 7160 case Sema::CXXMoveConstructor: 7161 // For copy or move constructors, we need to perform overload resolution. 7162 break; 7163 7164 case Sema::CXXCopyAssignment: 7165 case Sema::CXXMoveAssignment: 7166 if (!S.getLangOpts().CPlusPlus14) 7167 return false; 7168 // In C++1y, we need to perform overload resolution. 7169 Ctor = false; 7170 break; 7171 7172 case Sema::CXXDestructor: 7173 return ClassDecl->defaultedDestructorIsConstexpr(); 7174 7175 case Sema::CXXInvalid: 7176 return false; 7177 } 7178 7179 // -- if the class is a non-empty union, or for each non-empty anonymous 7180 // union member of a non-union class, exactly one non-static data member 7181 // shall be initialized; [DR1359] 7182 // 7183 // If we squint, this is guaranteed, since exactly one non-static data member 7184 // will be initialized (if the constructor isn't deleted), we just don't know 7185 // which one. 7186 if (Ctor && ClassDecl->isUnion()) 7187 return CSM == Sema::CXXDefaultConstructor 7188 ? ClassDecl->hasInClassInitializer() || 7189 !ClassDecl->hasVariantMembers() 7190 : true; 7191 7192 // -- the class shall not have any virtual base classes; 7193 if (Ctor && ClassDecl->getNumVBases()) 7194 return false; 7195 7196 // C++1y [class.copy]p26: 7197 // -- [the class] is a literal type, and 7198 if (!Ctor && !ClassDecl->isLiteral()) 7199 return false; 7200 7201 // -- every constructor involved in initializing [...] base class 7202 // sub-objects shall be a constexpr constructor; 7203 // -- the assignment operator selected to copy/move each direct base 7204 // class is a constexpr function, and 7205 for (const auto &B : ClassDecl->bases()) { 7206 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 7207 if (!BaseType) continue; 7208 7209 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7210 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 7211 InheritedCtor, Inherited)) 7212 return false; 7213 } 7214 7215 // -- every constructor involved in initializing non-static data members 7216 // [...] shall be a constexpr constructor; 7217 // -- every non-static data member and base class sub-object shall be 7218 // initialized 7219 // -- for each non-static data member of X that is of class type (or array 7220 // thereof), the assignment operator selected to copy/move that member is 7221 // a constexpr function 7222 for (const auto *F : ClassDecl->fields()) { 7223 if (F->isInvalidDecl()) 7224 continue; 7225 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 7226 continue; 7227 QualType BaseType = S.Context.getBaseElementType(F->getType()); 7228 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 7229 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7230 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 7231 BaseType.getCVRQualifiers(), 7232 ConstArg && !F->isMutable())) 7233 return false; 7234 } else if (CSM == Sema::CXXDefaultConstructor) { 7235 return false; 7236 } 7237 } 7238 7239 // All OK, it's constexpr! 7240 return true; 7241 } 7242 7243 namespace { 7244 /// RAII object to register a defaulted function as having its exception 7245 /// specification computed. 7246 struct ComputingExceptionSpec { 7247 Sema &S; 7248 7249 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 7250 : S(S) { 7251 Sema::CodeSynthesisContext Ctx; 7252 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 7253 Ctx.PointOfInstantiation = Loc; 7254 Ctx.Entity = FD; 7255 S.pushCodeSynthesisContext(Ctx); 7256 } 7257 ~ComputingExceptionSpec() { 7258 S.popCodeSynthesisContext(); 7259 } 7260 }; 7261 } 7262 7263 static Sema::ImplicitExceptionSpecification 7264 ComputeDefaultedSpecialMemberExceptionSpec( 7265 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 7266 Sema::InheritedConstructorInfo *ICI); 7267 7268 static Sema::ImplicitExceptionSpecification 7269 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 7270 FunctionDecl *FD, 7271 Sema::DefaultedComparisonKind DCK); 7272 7273 static Sema::ImplicitExceptionSpecification 7274 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 7275 auto DFK = S.getDefaultedFunctionKind(FD); 7276 if (DFK.isSpecialMember()) 7277 return ComputeDefaultedSpecialMemberExceptionSpec( 7278 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 7279 if (DFK.isComparison()) 7280 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 7281 DFK.asComparison()); 7282 7283 auto *CD = cast<CXXConstructorDecl>(FD); 7284 assert(CD->getInheritedConstructor() && 7285 "only defaulted functions and inherited constructors have implicit " 7286 "exception specs"); 7287 Sema::InheritedConstructorInfo ICI( 7288 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 7289 return ComputeDefaultedSpecialMemberExceptionSpec( 7290 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 7291 } 7292 7293 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 7294 CXXMethodDecl *MD) { 7295 FunctionProtoType::ExtProtoInfo EPI; 7296 7297 // Build an exception specification pointing back at this member. 7298 EPI.ExceptionSpec.Type = EST_Unevaluated; 7299 EPI.ExceptionSpec.SourceDecl = MD; 7300 7301 // Set the calling convention to the default for C++ instance methods. 7302 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 7303 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 7304 /*IsCXXMethod=*/true)); 7305 return EPI; 7306 } 7307 7308 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 7309 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 7310 if (FPT->getExceptionSpecType() != EST_Unevaluated) 7311 return; 7312 7313 // Evaluate the exception specification. 7314 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 7315 auto ESI = IES.getExceptionSpec(); 7316 7317 // Update the type of the special member to use it. 7318 UpdateExceptionSpec(FD, ESI); 7319 } 7320 7321 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 7322 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted"); 7323 7324 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 7325 if (!DefKind) { 7326 assert(FD->getDeclContext()->isDependentContext()); 7327 return; 7328 } 7329 7330 if (DefKind.isComparison()) 7331 UnusedPrivateFields.clear(); 7332 7333 if (DefKind.isSpecialMember() 7334 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 7335 DefKind.asSpecialMember()) 7336 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 7337 FD->setInvalidDecl(); 7338 } 7339 7340 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7341 CXXSpecialMember CSM) { 7342 CXXRecordDecl *RD = MD->getParent(); 7343 7344 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 7345 "not an explicitly-defaulted special member"); 7346 7347 // Defer all checking for special members of a dependent type. 7348 if (RD->isDependentType()) 7349 return false; 7350 7351 // Whether this was the first-declared instance of the constructor. 7352 // This affects whether we implicitly add an exception spec and constexpr. 7353 bool First = MD == MD->getCanonicalDecl(); 7354 7355 bool HadError = false; 7356 7357 // C++11 [dcl.fct.def.default]p1: 7358 // A function that is explicitly defaulted shall 7359 // -- be a special member function [...] (checked elsewhere), 7360 // -- have the same type (except for ref-qualifiers, and except that a 7361 // copy operation can take a non-const reference) as an implicit 7362 // declaration, and 7363 // -- not have default arguments. 7364 // C++2a changes the second bullet to instead delete the function if it's 7365 // defaulted on its first declaration, unless it's "an assignment operator, 7366 // and its return type differs or its parameter type is not a reference". 7367 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First; 7368 bool ShouldDeleteForTypeMismatch = false; 7369 unsigned ExpectedParams = 1; 7370 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 7371 ExpectedParams = 0; 7372 if (MD->getNumParams() != ExpectedParams) { 7373 // This checks for default arguments: a copy or move constructor with a 7374 // default argument is classified as a default constructor, and assignment 7375 // operations and destructors can't have default arguments. 7376 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 7377 << CSM << MD->getSourceRange(); 7378 HadError = true; 7379 } else if (MD->isVariadic()) { 7380 if (DeleteOnTypeMismatch) 7381 ShouldDeleteForTypeMismatch = true; 7382 else { 7383 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 7384 << CSM << MD->getSourceRange(); 7385 HadError = true; 7386 } 7387 } 7388 7389 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 7390 7391 bool CanHaveConstParam = false; 7392 if (CSM == CXXCopyConstructor) 7393 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 7394 else if (CSM == CXXCopyAssignment) 7395 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 7396 7397 QualType ReturnType = Context.VoidTy; 7398 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 7399 // Check for return type matching. 7400 ReturnType = Type->getReturnType(); 7401 7402 QualType DeclType = Context.getTypeDeclType(RD); 7403 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 7404 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 7405 7406 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 7407 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 7408 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 7409 HadError = true; 7410 } 7411 7412 // A defaulted special member cannot have cv-qualifiers. 7413 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 7414 if (DeleteOnTypeMismatch) 7415 ShouldDeleteForTypeMismatch = true; 7416 else { 7417 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 7418 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 7419 HadError = true; 7420 } 7421 } 7422 } 7423 7424 // Check for parameter type matching. 7425 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 7426 bool HasConstParam = false; 7427 if (ExpectedParams && ArgType->isReferenceType()) { 7428 // Argument must be reference to possibly-const T. 7429 QualType ReferentType = ArgType->getPointeeType(); 7430 HasConstParam = ReferentType.isConstQualified(); 7431 7432 if (ReferentType.isVolatileQualified()) { 7433 if (DeleteOnTypeMismatch) 7434 ShouldDeleteForTypeMismatch = true; 7435 else { 7436 Diag(MD->getLocation(), 7437 diag::err_defaulted_special_member_volatile_param) << CSM; 7438 HadError = true; 7439 } 7440 } 7441 7442 if (HasConstParam && !CanHaveConstParam) { 7443 if (DeleteOnTypeMismatch) 7444 ShouldDeleteForTypeMismatch = true; 7445 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7446 Diag(MD->getLocation(), 7447 diag::err_defaulted_special_member_copy_const_param) 7448 << (CSM == CXXCopyAssignment); 7449 // FIXME: Explain why this special member can't be const. 7450 HadError = true; 7451 } else { 7452 Diag(MD->getLocation(), 7453 diag::err_defaulted_special_member_move_const_param) 7454 << (CSM == CXXMoveAssignment); 7455 HadError = true; 7456 } 7457 } 7458 } else if (ExpectedParams) { 7459 // A copy assignment operator can take its argument by value, but a 7460 // defaulted one cannot. 7461 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 7462 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7463 HadError = true; 7464 } 7465 7466 // C++11 [dcl.fct.def.default]p2: 7467 // An explicitly-defaulted function may be declared constexpr only if it 7468 // would have been implicitly declared as constexpr, 7469 // Do not apply this rule to members of class templates, since core issue 1358 7470 // makes such functions always instantiate to constexpr functions. For 7471 // functions which cannot be constexpr (for non-constructors in C++11 and for 7472 // destructors in C++14 and C++17), this is checked elsewhere. 7473 // 7474 // FIXME: This should not apply if the member is deleted. 7475 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7476 HasConstParam); 7477 if ((getLangOpts().CPlusPlus20 || 7478 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7479 : isa<CXXConstructorDecl>(MD))) && 7480 MD->isConstexpr() && !Constexpr && 7481 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7482 Diag(MD->getBeginLoc(), MD->isConsteval() 7483 ? diag::err_incorrect_defaulted_consteval 7484 : diag::err_incorrect_defaulted_constexpr) 7485 << CSM; 7486 // FIXME: Explain why the special member can't be constexpr. 7487 HadError = true; 7488 } 7489 7490 if (First) { 7491 // C++2a [dcl.fct.def.default]p3: 7492 // If a function is explicitly defaulted on its first declaration, it is 7493 // implicitly considered to be constexpr if the implicit declaration 7494 // would be. 7495 MD->setConstexprKind(Constexpr ? (MD->isConsteval() 7496 ? ConstexprSpecKind::Consteval 7497 : ConstexprSpecKind::Constexpr) 7498 : ConstexprSpecKind::Unspecified); 7499 7500 if (!Type->hasExceptionSpec()) { 7501 // C++2a [except.spec]p3: 7502 // If a declaration of a function does not have a noexcept-specifier 7503 // [and] is defaulted on its first declaration, [...] the exception 7504 // specification is as specified below 7505 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7506 EPI.ExceptionSpec.Type = EST_Unevaluated; 7507 EPI.ExceptionSpec.SourceDecl = MD; 7508 MD->setType(Context.getFunctionType(ReturnType, 7509 llvm::makeArrayRef(&ArgType, 7510 ExpectedParams), 7511 EPI)); 7512 } 7513 } 7514 7515 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7516 if (First) { 7517 SetDeclDeleted(MD, MD->getLocation()); 7518 if (!inTemplateInstantiation() && !HadError) { 7519 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7520 if (ShouldDeleteForTypeMismatch) { 7521 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7522 } else { 7523 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7524 } 7525 } 7526 if (ShouldDeleteForTypeMismatch && !HadError) { 7527 Diag(MD->getLocation(), 7528 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7529 } 7530 } else { 7531 // C++11 [dcl.fct.def.default]p4: 7532 // [For a] user-provided explicitly-defaulted function [...] if such a 7533 // function is implicitly defined as deleted, the program is ill-formed. 7534 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7535 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 7536 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7537 HadError = true; 7538 } 7539 } 7540 7541 return HadError; 7542 } 7543 7544 namespace { 7545 /// Helper class for building and checking a defaulted comparison. 7546 /// 7547 /// Defaulted functions are built in two phases: 7548 /// 7549 /// * First, the set of operations that the function will perform are 7550 /// identified, and some of them are checked. If any of the checked 7551 /// operations is invalid in certain ways, the comparison function is 7552 /// defined as deleted and no body is built. 7553 /// * Then, if the function is not defined as deleted, the body is built. 7554 /// 7555 /// This is accomplished by performing two visitation steps over the eventual 7556 /// body of the function. 7557 template<typename Derived, typename ResultList, typename Result, 7558 typename Subobject> 7559 class DefaultedComparisonVisitor { 7560 public: 7561 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7562 7563 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7564 DefaultedComparisonKind DCK) 7565 : S(S), RD(RD), FD(FD), DCK(DCK) { 7566 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7567 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7568 // UnresolvedSet to avoid this copy. 7569 Fns.assign(Info->getUnqualifiedLookups().begin(), 7570 Info->getUnqualifiedLookups().end()); 7571 } 7572 } 7573 7574 ResultList visit() { 7575 // The type of an lvalue naming a parameter of this function. 7576 QualType ParamLvalType = 7577 FD->getParamDecl(0)->getType().getNonReferenceType(); 7578 7579 ResultList Results; 7580 7581 switch (DCK) { 7582 case DefaultedComparisonKind::None: 7583 llvm_unreachable("not a defaulted comparison"); 7584 7585 case DefaultedComparisonKind::Equal: 7586 case DefaultedComparisonKind::ThreeWay: 7587 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7588 return Results; 7589 7590 case DefaultedComparisonKind::NotEqual: 7591 case DefaultedComparisonKind::Relational: 7592 Results.add(getDerived().visitExpandedSubobject( 7593 ParamLvalType, getDerived().getCompleteObject())); 7594 return Results; 7595 } 7596 llvm_unreachable(""); 7597 } 7598 7599 protected: 7600 Derived &getDerived() { return static_cast<Derived&>(*this); } 7601 7602 /// Visit the expanded list of subobjects of the given type, as specified in 7603 /// C++2a [class.compare.default]. 7604 /// 7605 /// \return \c true if the ResultList object said we're done, \c false if not. 7606 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7607 Qualifiers Quals) { 7608 // C++2a [class.compare.default]p4: 7609 // The direct base class subobjects of C 7610 for (CXXBaseSpecifier &Base : Record->bases()) 7611 if (Results.add(getDerived().visitSubobject( 7612 S.Context.getQualifiedType(Base.getType(), Quals), 7613 getDerived().getBase(&Base)))) 7614 return true; 7615 7616 // followed by the non-static data members of C 7617 for (FieldDecl *Field : Record->fields()) { 7618 // Recursively expand anonymous structs. 7619 if (Field->isAnonymousStructOrUnion()) { 7620 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7621 Quals)) 7622 return true; 7623 continue; 7624 } 7625 7626 // Figure out the type of an lvalue denoting this field. 7627 Qualifiers FieldQuals = Quals; 7628 if (Field->isMutable()) 7629 FieldQuals.removeConst(); 7630 QualType FieldType = 7631 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7632 7633 if (Results.add(getDerived().visitSubobject( 7634 FieldType, getDerived().getField(Field)))) 7635 return true; 7636 } 7637 7638 // form a list of subobjects. 7639 return false; 7640 } 7641 7642 Result visitSubobject(QualType Type, Subobject Subobj) { 7643 // In that list, any subobject of array type is recursively expanded 7644 const ArrayType *AT = S.Context.getAsArrayType(Type); 7645 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7646 return getDerived().visitSubobjectArray(CAT->getElementType(), 7647 CAT->getSize(), Subobj); 7648 return getDerived().visitExpandedSubobject(Type, Subobj); 7649 } 7650 7651 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7652 Subobject Subobj) { 7653 return getDerived().visitSubobject(Type, Subobj); 7654 } 7655 7656 protected: 7657 Sema &S; 7658 CXXRecordDecl *RD; 7659 FunctionDecl *FD; 7660 DefaultedComparisonKind DCK; 7661 UnresolvedSet<16> Fns; 7662 }; 7663 7664 /// Information about a defaulted comparison, as determined by 7665 /// DefaultedComparisonAnalyzer. 7666 struct DefaultedComparisonInfo { 7667 bool Deleted = false; 7668 bool Constexpr = true; 7669 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7670 7671 static DefaultedComparisonInfo deleted() { 7672 DefaultedComparisonInfo Deleted; 7673 Deleted.Deleted = true; 7674 return Deleted; 7675 } 7676 7677 bool add(const DefaultedComparisonInfo &R) { 7678 Deleted |= R.Deleted; 7679 Constexpr &= R.Constexpr; 7680 Category = commonComparisonType(Category, R.Category); 7681 return Deleted; 7682 } 7683 }; 7684 7685 /// An element in the expanded list of subobjects of a defaulted comparison, as 7686 /// specified in C++2a [class.compare.default]p4. 7687 struct DefaultedComparisonSubobject { 7688 enum { CompleteObject, Member, Base } Kind; 7689 NamedDecl *Decl; 7690 SourceLocation Loc; 7691 }; 7692 7693 /// A visitor over the notional body of a defaulted comparison that determines 7694 /// whether that body would be deleted or constexpr. 7695 class DefaultedComparisonAnalyzer 7696 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7697 DefaultedComparisonInfo, 7698 DefaultedComparisonInfo, 7699 DefaultedComparisonSubobject> { 7700 public: 7701 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7702 7703 private: 7704 DiagnosticKind Diagnose; 7705 7706 public: 7707 using Base = DefaultedComparisonVisitor; 7708 using Result = DefaultedComparisonInfo; 7709 using Subobject = DefaultedComparisonSubobject; 7710 7711 friend Base; 7712 7713 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7714 DefaultedComparisonKind DCK, 7715 DiagnosticKind Diagnose = NoDiagnostics) 7716 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7717 7718 Result visit() { 7719 if ((DCK == DefaultedComparisonKind::Equal || 7720 DCK == DefaultedComparisonKind::ThreeWay) && 7721 RD->hasVariantMembers()) { 7722 // C++2a [class.compare.default]p2 [P2002R0]: 7723 // A defaulted comparison operator function for class C is defined as 7724 // deleted if [...] C has variant members. 7725 if (Diagnose == ExplainDeleted) { 7726 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7727 << FD << RD->isUnion() << RD; 7728 } 7729 return Result::deleted(); 7730 } 7731 7732 return Base::visit(); 7733 } 7734 7735 private: 7736 Subobject getCompleteObject() { 7737 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()}; 7738 } 7739 7740 Subobject getBase(CXXBaseSpecifier *Base) { 7741 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7742 Base->getBaseTypeLoc()}; 7743 } 7744 7745 Subobject getField(FieldDecl *Field) { 7746 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7747 } 7748 7749 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7750 // C++2a [class.compare.default]p2 [P2002R0]: 7751 // A defaulted <=> or == operator function for class C is defined as 7752 // deleted if any non-static data member of C is of reference type 7753 if (Type->isReferenceType()) { 7754 if (Diagnose == ExplainDeleted) { 7755 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7756 << FD << RD; 7757 } 7758 return Result::deleted(); 7759 } 7760 7761 // [...] Let xi be an lvalue denoting the ith element [...] 7762 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7763 Expr *Args[] = {&Xi, &Xi}; 7764 7765 // All operators start by trying to apply that same operator recursively. 7766 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7767 assert(OO != OO_None && "not an overloaded operator!"); 7768 return visitBinaryOperator(OO, Args, Subobj); 7769 } 7770 7771 Result 7772 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7773 Subobject Subobj, 7774 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7775 // Note that there is no need to consider rewritten candidates here if 7776 // we've already found there is no viable 'operator<=>' candidate (and are 7777 // considering synthesizing a '<=>' from '==' and '<'). 7778 OverloadCandidateSet CandidateSet( 7779 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7780 OverloadCandidateSet::OperatorRewriteInfo( 7781 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7782 7783 /// C++2a [class.compare.default]p1 [P2002R0]: 7784 /// [...] the defaulted function itself is never a candidate for overload 7785 /// resolution [...] 7786 CandidateSet.exclude(FD); 7787 7788 if (Args[0]->getType()->isOverloadableType()) 7789 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7790 else 7791 // FIXME: We determine whether this is a valid expression by checking to 7792 // see if there's a viable builtin operator candidate for it. That isn't 7793 // really what the rules ask us to do, but should give the right results. 7794 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet); 7795 7796 Result R; 7797 7798 OverloadCandidateSet::iterator Best; 7799 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7800 case OR_Success: { 7801 // C++2a [class.compare.secondary]p2 [P2002R0]: 7802 // The operator function [...] is defined as deleted if [...] the 7803 // candidate selected by overload resolution is not a rewritten 7804 // candidate. 7805 if ((DCK == DefaultedComparisonKind::NotEqual || 7806 DCK == DefaultedComparisonKind::Relational) && 7807 !Best->RewriteKind) { 7808 if (Diagnose == ExplainDeleted) { 7809 if (Best->Function) { 7810 S.Diag(Best->Function->getLocation(), 7811 diag::note_defaulted_comparison_not_rewritten_callee) 7812 << FD; 7813 } else { 7814 assert(Best->Conversions.size() == 2 && 7815 Best->Conversions[0].isUserDefined() && 7816 "non-user-defined conversion from class to built-in " 7817 "comparison"); 7818 S.Diag(Best->Conversions[0] 7819 .UserDefined.FoundConversionFunction.getDecl() 7820 ->getLocation(), 7821 diag::note_defaulted_comparison_not_rewritten_conversion) 7822 << FD; 7823 } 7824 } 7825 return Result::deleted(); 7826 } 7827 7828 // Throughout C++2a [class.compare]: if overload resolution does not 7829 // result in a usable function, the candidate function is defined as 7830 // deleted. This requires that we selected an accessible function. 7831 // 7832 // Note that this only considers the access of the function when named 7833 // within the type of the subobject, and not the access path for any 7834 // derived-to-base conversion. 7835 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7836 if (ArgClass && Best->FoundDecl.getDecl() && 7837 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7838 QualType ObjectType = Subobj.Kind == Subobject::Member 7839 ? Args[0]->getType() 7840 : S.Context.getRecordType(RD); 7841 if (!S.isMemberAccessibleForDeletion( 7842 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7843 Diagnose == ExplainDeleted 7844 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7845 << FD << Subobj.Kind << Subobj.Decl 7846 : S.PDiag())) 7847 return Result::deleted(); 7848 } 7849 7850 bool NeedsDeducing = 7851 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType(); 7852 7853 if (FunctionDecl *BestFD = Best->Function) { 7854 // C++2a [class.compare.default]p3 [P2002R0]: 7855 // A defaulted comparison function is constexpr-compatible if 7856 // [...] no overlod resolution performed [...] results in a 7857 // non-constexpr function. 7858 assert(!BestFD->isDeleted() && "wrong overload resolution result"); 7859 // If it's not constexpr, explain why not. 7860 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 7861 if (Subobj.Kind != Subobject::CompleteObject) 7862 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7863 << Subobj.Kind << Subobj.Decl; 7864 S.Diag(BestFD->getLocation(), 7865 diag::note_defaulted_comparison_not_constexpr_here); 7866 // Bail out after explaining; we don't want any more notes. 7867 return Result::deleted(); 7868 } 7869 R.Constexpr &= BestFD->isConstexpr(); 7870 7871 if (NeedsDeducing) { 7872 // If any callee has an undeduced return type, deduce it now. 7873 // FIXME: It's not clear how a failure here should be handled. For 7874 // now, we produce an eager diagnostic, because that is forward 7875 // compatible with most (all?) other reasonable options. 7876 if (BestFD->getReturnType()->isUndeducedType() && 7877 S.DeduceReturnType(BestFD, FD->getLocation(), 7878 /*Diagnose=*/false)) { 7879 // Don't produce a duplicate error when asked to explain why the 7880 // comparison is deleted: we diagnosed that when initially checking 7881 // the defaulted operator. 7882 if (Diagnose == NoDiagnostics) { 7883 S.Diag( 7884 FD->getLocation(), 7885 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) 7886 << Subobj.Kind << Subobj.Decl; 7887 S.Diag( 7888 Subobj.Loc, 7889 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) 7890 << Subobj.Kind << Subobj.Decl; 7891 S.Diag(BestFD->getLocation(), 7892 diag::note_defaulted_comparison_cannot_deduce_callee) 7893 << Subobj.Kind << Subobj.Decl; 7894 } 7895 return Result::deleted(); 7896 } 7897 auto *Info = S.Context.CompCategories.lookupInfoForType( 7898 BestFD->getCallResultType()); 7899 if (!Info) { 7900 if (Diagnose == ExplainDeleted) { 7901 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 7902 << Subobj.Kind << Subobj.Decl 7903 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 7904 S.Diag(BestFD->getLocation(), 7905 diag::note_defaulted_comparison_cannot_deduce_callee) 7906 << Subobj.Kind << Subobj.Decl; 7907 } 7908 return Result::deleted(); 7909 } 7910 R.Category = Info->Kind; 7911 } 7912 } else { 7913 QualType T = Best->BuiltinParamTypes[0]; 7914 assert(T == Best->BuiltinParamTypes[1] && 7915 "builtin comparison for different types?"); 7916 assert(Best->BuiltinParamTypes[2].isNull() && 7917 "invalid builtin comparison"); 7918 7919 if (NeedsDeducing) { 7920 Optional<ComparisonCategoryType> Cat = 7921 getComparisonCategoryForBuiltinCmp(T); 7922 assert(Cat && "no category for builtin comparison?"); 7923 R.Category = *Cat; 7924 } 7925 } 7926 7927 // Note that we might be rewriting to a different operator. That call is 7928 // not considered until we come to actually build the comparison function. 7929 break; 7930 } 7931 7932 case OR_Ambiguous: 7933 if (Diagnose == ExplainDeleted) { 7934 unsigned Kind = 0; 7935 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 7936 Kind = OO == OO_EqualEqual ? 1 : 2; 7937 CandidateSet.NoteCandidates( 7938 PartialDiagnosticAt( 7939 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 7940 << FD << Kind << Subobj.Kind << Subobj.Decl), 7941 S, OCD_AmbiguousCandidates, Args); 7942 } 7943 R = Result::deleted(); 7944 break; 7945 7946 case OR_Deleted: 7947 if (Diagnose == ExplainDeleted) { 7948 if ((DCK == DefaultedComparisonKind::NotEqual || 7949 DCK == DefaultedComparisonKind::Relational) && 7950 !Best->RewriteKind) { 7951 S.Diag(Best->Function->getLocation(), 7952 diag::note_defaulted_comparison_not_rewritten_callee) 7953 << FD; 7954 } else { 7955 S.Diag(Subobj.Loc, 7956 diag::note_defaulted_comparison_calls_deleted) 7957 << FD << Subobj.Kind << Subobj.Decl; 7958 S.NoteDeletedFunction(Best->Function); 7959 } 7960 } 7961 R = Result::deleted(); 7962 break; 7963 7964 case OR_No_Viable_Function: 7965 // If there's no usable candidate, we're done unless we can rewrite a 7966 // '<=>' in terms of '==' and '<'. 7967 if (OO == OO_Spaceship && 7968 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 7969 // For any kind of comparison category return type, we need a usable 7970 // '==' and a usable '<'. 7971 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 7972 &CandidateSet))) 7973 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 7974 break; 7975 } 7976 7977 if (Diagnose == ExplainDeleted) { 7978 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 7979 << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl; 7980 7981 // For a three-way comparison, list both the candidates for the 7982 // original operator and the candidates for the synthesized operator. 7983 if (SpaceshipCandidates) { 7984 SpaceshipCandidates->NoteCandidates( 7985 S, Args, 7986 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 7987 Args, FD->getLocation())); 7988 S.Diag(Subobj.Loc, 7989 diag::note_defaulted_comparison_no_viable_function_synthesized) 7990 << (OO == OO_EqualEqual ? 0 : 1); 7991 } 7992 7993 CandidateSet.NoteCandidates( 7994 S, Args, 7995 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 7996 FD->getLocation())); 7997 } 7998 R = Result::deleted(); 7999 break; 8000 } 8001 8002 return R; 8003 } 8004 }; 8005 8006 /// A list of statements. 8007 struct StmtListResult { 8008 bool IsInvalid = false; 8009 llvm::SmallVector<Stmt*, 16> Stmts; 8010 8011 bool add(const StmtResult &S) { 8012 IsInvalid |= S.isInvalid(); 8013 if (IsInvalid) 8014 return true; 8015 Stmts.push_back(S.get()); 8016 return false; 8017 } 8018 }; 8019 8020 /// A visitor over the notional body of a defaulted comparison that synthesizes 8021 /// the actual body. 8022 class DefaultedComparisonSynthesizer 8023 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 8024 StmtListResult, StmtResult, 8025 std::pair<ExprResult, ExprResult>> { 8026 SourceLocation Loc; 8027 unsigned ArrayDepth = 0; 8028 8029 public: 8030 using Base = DefaultedComparisonVisitor; 8031 using ExprPair = std::pair<ExprResult, ExprResult>; 8032 8033 friend Base; 8034 8035 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 8036 DefaultedComparisonKind DCK, 8037 SourceLocation BodyLoc) 8038 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 8039 8040 /// Build a suitable function body for this defaulted comparison operator. 8041 StmtResult build() { 8042 Sema::CompoundScopeRAII CompoundScope(S); 8043 8044 StmtListResult Stmts = visit(); 8045 if (Stmts.IsInvalid) 8046 return StmtError(); 8047 8048 ExprResult RetVal; 8049 switch (DCK) { 8050 case DefaultedComparisonKind::None: 8051 llvm_unreachable("not a defaulted comparison"); 8052 8053 case DefaultedComparisonKind::Equal: { 8054 // C++2a [class.eq]p3: 8055 // [...] compar[e] the corresponding elements [...] until the first 8056 // index i where xi == yi yields [...] false. If no such index exists, 8057 // V is true. Otherwise, V is false. 8058 // 8059 // Join the comparisons with '&&'s and return the result. Use a right 8060 // fold (traversing the conditions right-to-left), because that 8061 // short-circuits more naturally. 8062 auto OldStmts = std::move(Stmts.Stmts); 8063 Stmts.Stmts.clear(); 8064 ExprResult CmpSoFar; 8065 // Finish a particular comparison chain. 8066 auto FinishCmp = [&] { 8067 if (Expr *Prior = CmpSoFar.get()) { 8068 // Convert the last expression to 'return ...;' 8069 if (RetVal.isUnset() && Stmts.Stmts.empty()) 8070 RetVal = CmpSoFar; 8071 // Convert any prior comparison to 'if (!(...)) return false;' 8072 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 8073 return true; 8074 CmpSoFar = ExprResult(); 8075 } 8076 return false; 8077 }; 8078 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 8079 Expr *E = dyn_cast<Expr>(EAsStmt); 8080 if (!E) { 8081 // Found an array comparison. 8082 if (FinishCmp() || Stmts.add(EAsStmt)) 8083 return StmtError(); 8084 continue; 8085 } 8086 8087 if (CmpSoFar.isUnset()) { 8088 CmpSoFar = E; 8089 continue; 8090 } 8091 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 8092 if (CmpSoFar.isInvalid()) 8093 return StmtError(); 8094 } 8095 if (FinishCmp()) 8096 return StmtError(); 8097 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 8098 // If no such index exists, V is true. 8099 if (RetVal.isUnset()) 8100 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 8101 break; 8102 } 8103 8104 case DefaultedComparisonKind::ThreeWay: { 8105 // Per C++2a [class.spaceship]p3, as a fallback add: 8106 // return static_cast<R>(std::strong_ordering::equal); 8107 QualType StrongOrdering = S.CheckComparisonCategoryType( 8108 ComparisonCategoryType::StrongOrdering, Loc, 8109 Sema::ComparisonCategoryUsage::DefaultedOperator); 8110 if (StrongOrdering.isNull()) 8111 return StmtError(); 8112 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 8113 .getValueInfo(ComparisonCategoryResult::Equal) 8114 ->VD; 8115 RetVal = getDecl(EqualVD); 8116 if (RetVal.isInvalid()) 8117 return StmtError(); 8118 RetVal = buildStaticCastToR(RetVal.get()); 8119 break; 8120 } 8121 8122 case DefaultedComparisonKind::NotEqual: 8123 case DefaultedComparisonKind::Relational: 8124 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 8125 break; 8126 } 8127 8128 // Build the final return statement. 8129 if (RetVal.isInvalid()) 8130 return StmtError(); 8131 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 8132 if (ReturnStmt.isInvalid()) 8133 return StmtError(); 8134 Stmts.Stmts.push_back(ReturnStmt.get()); 8135 8136 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 8137 } 8138 8139 private: 8140 ExprResult getDecl(ValueDecl *VD) { 8141 return S.BuildDeclarationNameExpr( 8142 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 8143 } 8144 8145 ExprResult getParam(unsigned I) { 8146 ParmVarDecl *PD = FD->getParamDecl(I); 8147 return getDecl(PD); 8148 } 8149 8150 ExprPair getCompleteObject() { 8151 unsigned Param = 0; 8152 ExprResult LHS; 8153 if (isa<CXXMethodDecl>(FD)) { 8154 // LHS is '*this'. 8155 LHS = S.ActOnCXXThis(Loc); 8156 if (!LHS.isInvalid()) 8157 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 8158 } else { 8159 LHS = getParam(Param++); 8160 } 8161 ExprResult RHS = getParam(Param++); 8162 assert(Param == FD->getNumParams()); 8163 return {LHS, RHS}; 8164 } 8165 8166 ExprPair getBase(CXXBaseSpecifier *Base) { 8167 ExprPair Obj = getCompleteObject(); 8168 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8169 return {ExprError(), ExprError()}; 8170 CXXCastPath Path = {Base}; 8171 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 8172 CK_DerivedToBase, VK_LValue, &Path), 8173 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 8174 CK_DerivedToBase, VK_LValue, &Path)}; 8175 } 8176 8177 ExprPair getField(FieldDecl *Field) { 8178 ExprPair Obj = getCompleteObject(); 8179 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8180 return {ExprError(), ExprError()}; 8181 8182 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 8183 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 8184 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 8185 CXXScopeSpec(), Field, Found, NameInfo), 8186 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 8187 CXXScopeSpec(), Field, Found, NameInfo)}; 8188 } 8189 8190 // FIXME: When expanding a subobject, register a note in the code synthesis 8191 // stack to say which subobject we're comparing. 8192 8193 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 8194 if (Cond.isInvalid()) 8195 return StmtError(); 8196 8197 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 8198 if (NotCond.isInvalid()) 8199 return StmtError(); 8200 8201 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 8202 assert(!False.isInvalid() && "should never fail"); 8203 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 8204 if (ReturnFalse.isInvalid()) 8205 return StmtError(); 8206 8207 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr, 8208 S.ActOnCondition(nullptr, Loc, NotCond.get(), 8209 Sema::ConditionKind::Boolean), 8210 Loc, ReturnFalse.get(), SourceLocation(), nullptr); 8211 } 8212 8213 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 8214 ExprPair Subobj) { 8215 QualType SizeType = S.Context.getSizeType(); 8216 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 8217 8218 // Build 'size_t i$n = 0'. 8219 IdentifierInfo *IterationVarName = nullptr; 8220 { 8221 SmallString<8> Str; 8222 llvm::raw_svector_ostream OS(Str); 8223 OS << "i" << ArrayDepth; 8224 IterationVarName = &S.Context.Idents.get(OS.str()); 8225 } 8226 VarDecl *IterationVar = VarDecl::Create( 8227 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 8228 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 8229 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8230 IterationVar->setInit( 8231 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8232 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 8233 8234 auto IterRef = [&] { 8235 ExprResult Ref = S.BuildDeclarationNameExpr( 8236 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 8237 IterationVar); 8238 assert(!Ref.isInvalid() && "can't reference our own variable?"); 8239 return Ref.get(); 8240 }; 8241 8242 // Build 'i$n != Size'. 8243 ExprResult Cond = S.CreateBuiltinBinOp( 8244 Loc, BO_NE, IterRef(), 8245 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 8246 assert(!Cond.isInvalid() && "should never fail"); 8247 8248 // Build '++i$n'. 8249 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 8250 assert(!Inc.isInvalid() && "should never fail"); 8251 8252 // Build 'a[i$n]' and 'b[i$n]'. 8253 auto Index = [&](ExprResult E) { 8254 if (E.isInvalid()) 8255 return ExprError(); 8256 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 8257 }; 8258 Subobj.first = Index(Subobj.first); 8259 Subobj.second = Index(Subobj.second); 8260 8261 // Compare the array elements. 8262 ++ArrayDepth; 8263 StmtResult Substmt = visitSubobject(Type, Subobj); 8264 --ArrayDepth; 8265 8266 if (Substmt.isInvalid()) 8267 return StmtError(); 8268 8269 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 8270 // For outer levels or for an 'operator<=>' we already have a suitable 8271 // statement that returns as necessary. 8272 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 8273 assert(DCK == DefaultedComparisonKind::Equal && 8274 "should have non-expression statement"); 8275 Substmt = buildIfNotCondReturnFalse(ElemCmp); 8276 if (Substmt.isInvalid()) 8277 return StmtError(); 8278 } 8279 8280 // Build 'for (...) ...' 8281 return S.ActOnForStmt(Loc, Loc, Init, 8282 S.ActOnCondition(nullptr, Loc, Cond.get(), 8283 Sema::ConditionKind::Boolean), 8284 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 8285 Substmt.get()); 8286 } 8287 8288 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 8289 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8290 return StmtError(); 8291 8292 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 8293 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); 8294 ExprResult Op; 8295 if (Type->isOverloadableType()) 8296 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(), 8297 Obj.second.get(), /*PerformADL=*/true, 8298 /*AllowRewrittenCandidates=*/true, FD); 8299 else 8300 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get()); 8301 if (Op.isInvalid()) 8302 return StmtError(); 8303 8304 switch (DCK) { 8305 case DefaultedComparisonKind::None: 8306 llvm_unreachable("not a defaulted comparison"); 8307 8308 case DefaultedComparisonKind::Equal: 8309 // Per C++2a [class.eq]p2, each comparison is individually contextually 8310 // converted to bool. 8311 Op = S.PerformContextuallyConvertToBool(Op.get()); 8312 if (Op.isInvalid()) 8313 return StmtError(); 8314 return Op.get(); 8315 8316 case DefaultedComparisonKind::ThreeWay: { 8317 // Per C++2a [class.spaceship]p3, form: 8318 // if (R cmp = static_cast<R>(op); cmp != 0) 8319 // return cmp; 8320 QualType R = FD->getReturnType(); 8321 Op = buildStaticCastToR(Op.get()); 8322 if (Op.isInvalid()) 8323 return StmtError(); 8324 8325 // R cmp = ...; 8326 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 8327 VarDecl *VD = 8328 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 8329 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 8330 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 8331 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 8332 8333 // cmp != 0 8334 ExprResult VDRef = getDecl(VD); 8335 if (VDRef.isInvalid()) 8336 return StmtError(); 8337 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 8338 Expr *Zero = 8339 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 8340 ExprResult Comp; 8341 if (VDRef.get()->getType()->isOverloadableType()) 8342 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true, 8343 true, FD); 8344 else 8345 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero); 8346 if (Comp.isInvalid()) 8347 return StmtError(); 8348 Sema::ConditionResult Cond = S.ActOnCondition( 8349 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 8350 if (Cond.isInvalid()) 8351 return StmtError(); 8352 8353 // return cmp; 8354 VDRef = getDecl(VD); 8355 if (VDRef.isInvalid()) 8356 return StmtError(); 8357 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 8358 if (ReturnStmt.isInvalid()) 8359 return StmtError(); 8360 8361 // if (...) 8362 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond, 8363 Loc, ReturnStmt.get(), 8364 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr); 8365 } 8366 8367 case DefaultedComparisonKind::NotEqual: 8368 case DefaultedComparisonKind::Relational: 8369 // C++2a [class.compare.secondary]p2: 8370 // Otherwise, the operator function yields x @ y. 8371 return Op.get(); 8372 } 8373 llvm_unreachable(""); 8374 } 8375 8376 /// Build "static_cast<R>(E)". 8377 ExprResult buildStaticCastToR(Expr *E) { 8378 QualType R = FD->getReturnType(); 8379 assert(!R->isUndeducedType() && "type should have been deduced already"); 8380 8381 // Don't bother forming a no-op cast in the common case. 8382 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R)) 8383 return E; 8384 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 8385 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 8386 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 8387 } 8388 }; 8389 } 8390 8391 /// Perform the unqualified lookups that might be needed to form a defaulted 8392 /// comparison function for the given operator. 8393 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 8394 UnresolvedSetImpl &Operators, 8395 OverloadedOperatorKind Op) { 8396 auto Lookup = [&](OverloadedOperatorKind OO) { 8397 Self.LookupOverloadedOperatorName(OO, S, Operators); 8398 }; 8399 8400 // Every defaulted operator looks up itself. 8401 Lookup(Op); 8402 // ... and the rewritten form of itself, if any. 8403 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 8404 Lookup(ExtraOp); 8405 8406 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 8407 // synthesize a three-way comparison from '<' and '=='. In a dependent 8408 // context, we also need to look up '==' in case we implicitly declare a 8409 // defaulted 'operator=='. 8410 if (Op == OO_Spaceship) { 8411 Lookup(OO_ExclaimEqual); 8412 Lookup(OO_Less); 8413 Lookup(OO_EqualEqual); 8414 } 8415 } 8416 8417 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 8418 DefaultedComparisonKind DCK) { 8419 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison"); 8420 8421 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 8422 assert(RD && "defaulted comparison is not defaulted in a class"); 8423 8424 // Perform any unqualified lookups we're going to need to default this 8425 // function. 8426 if (S) { 8427 UnresolvedSet<32> Operators; 8428 lookupOperatorsForDefaultedComparison(*this, S, Operators, 8429 FD->getOverloadedOperator()); 8430 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 8431 Context, Operators.pairs())); 8432 } 8433 8434 // C++2a [class.compare.default]p1: 8435 // A defaulted comparison operator function for some class C shall be a 8436 // non-template function declared in the member-specification of C that is 8437 // -- a non-static const member of C having one parameter of type 8438 // const C&, or 8439 // -- a friend of C having two parameters of type const C& or two 8440 // parameters of type C. 8441 QualType ExpectedParmType1 = Context.getRecordType(RD); 8442 QualType ExpectedParmType2 = 8443 Context.getLValueReferenceType(ExpectedParmType1.withConst()); 8444 if (isa<CXXMethodDecl>(FD)) 8445 ExpectedParmType1 = ExpectedParmType2; 8446 for (const ParmVarDecl *Param : FD->parameters()) { 8447 if (!Param->getType()->isDependentType() && 8448 !Context.hasSameType(Param->getType(), ExpectedParmType1) && 8449 !Context.hasSameType(Param->getType(), ExpectedParmType2)) { 8450 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8451 // corresponding defaulted 'operator<=>' already. 8452 if (!FD->isImplicit()) { 8453 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 8454 << (int)DCK << Param->getType() << ExpectedParmType1 8455 << !isa<CXXMethodDecl>(FD) 8456 << ExpectedParmType2 << Param->getSourceRange(); 8457 } 8458 return true; 8459 } 8460 } 8461 if (FD->getNumParams() == 2 && 8462 !Context.hasSameType(FD->getParamDecl(0)->getType(), 8463 FD->getParamDecl(1)->getType())) { 8464 if (!FD->isImplicit()) { 8465 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 8466 << (int)DCK 8467 << FD->getParamDecl(0)->getType() 8468 << FD->getParamDecl(0)->getSourceRange() 8469 << FD->getParamDecl(1)->getType() 8470 << FD->getParamDecl(1)->getSourceRange(); 8471 } 8472 return true; 8473 } 8474 8475 // ... non-static const member ... 8476 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 8477 assert(!MD->isStatic() && "comparison function cannot be a static member"); 8478 if (!MD->isConst()) { 8479 SourceLocation InsertLoc; 8480 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 8481 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 8482 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8483 // corresponding defaulted 'operator<=>' already. 8484 if (!MD->isImplicit()) { 8485 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 8486 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 8487 } 8488 8489 // Add the 'const' to the type to recover. 8490 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 8491 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8492 EPI.TypeQuals.addConst(); 8493 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8494 FPT->getParamTypes(), EPI)); 8495 } 8496 } else { 8497 // A non-member function declared in a class must be a friend. 8498 assert(FD->getFriendObjectKind() && "expected a friend declaration"); 8499 } 8500 8501 // C++2a [class.eq]p1, [class.rel]p1: 8502 // A [defaulted comparison other than <=>] shall have a declared return 8503 // type bool. 8504 if (DCK != DefaultedComparisonKind::ThreeWay && 8505 !FD->getDeclaredReturnType()->isDependentType() && 8506 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8507 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8508 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8509 << FD->getReturnTypeSourceRange(); 8510 return true; 8511 } 8512 // C++2a [class.spaceship]p2 [P2002R0]: 8513 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8514 // R shall not contain a placeholder type. 8515 if (DCK == DefaultedComparisonKind::ThreeWay && 8516 FD->getDeclaredReturnType()->getContainedDeducedType() && 8517 !Context.hasSameType(FD->getDeclaredReturnType(), 8518 Context.getAutoDeductType())) { 8519 Diag(FD->getLocation(), 8520 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8521 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8522 << FD->getReturnTypeSourceRange(); 8523 return true; 8524 } 8525 8526 // For a defaulted function in a dependent class, defer all remaining checks 8527 // until instantiation. 8528 if (RD->isDependentType()) 8529 return false; 8530 8531 // Determine whether the function should be defined as deleted. 8532 DefaultedComparisonInfo Info = 8533 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8534 8535 bool First = FD == FD->getCanonicalDecl(); 8536 8537 // If we want to delete the function, then do so; there's nothing else to 8538 // check in that case. 8539 if (Info.Deleted) { 8540 if (!First) { 8541 // C++11 [dcl.fct.def.default]p4: 8542 // [For a] user-provided explicitly-defaulted function [...] if such a 8543 // function is implicitly defined as deleted, the program is ill-formed. 8544 // 8545 // This is really just a consequence of the general rule that you can 8546 // only delete a function on its first declaration. 8547 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8548 << FD->isImplicit() << (int)DCK; 8549 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8550 DefaultedComparisonAnalyzer::ExplainDeleted) 8551 .visit(); 8552 return true; 8553 } 8554 8555 SetDeclDeleted(FD, FD->getLocation()); 8556 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8557 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8558 << (int)DCK; 8559 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8560 DefaultedComparisonAnalyzer::ExplainDeleted) 8561 .visit(); 8562 } 8563 return false; 8564 } 8565 8566 // C++2a [class.spaceship]p2: 8567 // The return type is deduced as the common comparison type of R0, R1, ... 8568 if (DCK == DefaultedComparisonKind::ThreeWay && 8569 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8570 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8571 if (RetLoc.isInvalid()) 8572 RetLoc = FD->getBeginLoc(); 8573 // FIXME: Should we really care whether we have the complete type and the 8574 // 'enumerator' constants here? A forward declaration seems sufficient. 8575 QualType Cat = CheckComparisonCategoryType( 8576 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8577 if (Cat.isNull()) 8578 return true; 8579 Context.adjustDeducedFunctionResultType( 8580 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8581 } 8582 8583 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8584 // An explicitly-defaulted function that is not defined as deleted may be 8585 // declared constexpr or consteval only if it is constexpr-compatible. 8586 // C++2a [class.compare.default]p3 [P2002R0]: 8587 // A defaulted comparison function is constexpr-compatible if it satisfies 8588 // the requirements for a constexpr function [...] 8589 // The only relevant requirements are that the parameter and return types are 8590 // literal types. The remaining conditions are checked by the analyzer. 8591 if (FD->isConstexpr()) { 8592 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8593 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8594 !Info.Constexpr) { 8595 Diag(FD->getBeginLoc(), 8596 diag::err_incorrect_defaulted_comparison_constexpr) 8597 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8598 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8599 DefaultedComparisonAnalyzer::ExplainConstexpr) 8600 .visit(); 8601 } 8602 } 8603 8604 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8605 // If a constexpr-compatible function is explicitly defaulted on its first 8606 // declaration, it is implicitly considered to be constexpr. 8607 // FIXME: Only applying this to the first declaration seems problematic, as 8608 // simple reorderings can affect the meaning of the program. 8609 if (First && !FD->isConstexpr() && Info.Constexpr) 8610 FD->setConstexprKind(ConstexprSpecKind::Constexpr); 8611 8612 // C++2a [except.spec]p3: 8613 // If a declaration of a function does not have a noexcept-specifier 8614 // [and] is defaulted on its first declaration, [...] the exception 8615 // specification is as specified below 8616 if (FD->getExceptionSpecType() == EST_None) { 8617 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8618 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8619 EPI.ExceptionSpec.Type = EST_Unevaluated; 8620 EPI.ExceptionSpec.SourceDecl = FD; 8621 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8622 FPT->getParamTypes(), EPI)); 8623 } 8624 8625 return false; 8626 } 8627 8628 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8629 FunctionDecl *Spaceship) { 8630 Sema::CodeSynthesisContext Ctx; 8631 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8632 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8633 Ctx.Entity = Spaceship; 8634 pushCodeSynthesisContext(Ctx); 8635 8636 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8637 EqualEqual->setImplicit(); 8638 8639 popCodeSynthesisContext(); 8640 } 8641 8642 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8643 DefaultedComparisonKind DCK) { 8644 assert(FD->isDefaulted() && !FD->isDeleted() && 8645 !FD->doesThisDeclarationHaveABody()); 8646 if (FD->willHaveBody() || FD->isInvalidDecl()) 8647 return; 8648 8649 SynthesizedFunctionScope Scope(*this, FD); 8650 8651 // Add a context note for diagnostics produced after this point. 8652 Scope.addContextNote(UseLoc); 8653 8654 { 8655 // Build and set up the function body. 8656 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8657 SourceLocation BodyLoc = 8658 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8659 StmtResult Body = 8660 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8661 if (Body.isInvalid()) { 8662 FD->setInvalidDecl(); 8663 return; 8664 } 8665 FD->setBody(Body.get()); 8666 FD->markUsed(Context); 8667 } 8668 8669 // The exception specification is needed because we are defining the 8670 // function. Note that this will reuse the body we just built. 8671 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8672 8673 if (ASTMutationListener *L = getASTMutationListener()) 8674 L->CompletedImplicitDefinition(FD); 8675 } 8676 8677 static Sema::ImplicitExceptionSpecification 8678 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8679 FunctionDecl *FD, 8680 Sema::DefaultedComparisonKind DCK) { 8681 ComputingExceptionSpec CES(S, FD, Loc); 8682 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8683 8684 if (FD->isInvalidDecl()) 8685 return ExceptSpec; 8686 8687 // The common case is that we just defined the comparison function. In that 8688 // case, just look at whether the body can throw. 8689 if (FD->hasBody()) { 8690 ExceptSpec.CalledStmt(FD->getBody()); 8691 } else { 8692 // Otherwise, build a body so we can check it. This should ideally only 8693 // happen when we're not actually marking the function referenced. (This is 8694 // only really important for efficiency: we don't want to build and throw 8695 // away bodies for comparison functions more than we strictly need to.) 8696 8697 // Pretend to synthesize the function body in an unevaluated context. 8698 // Note that we can't actually just go ahead and define the function here: 8699 // we are not permitted to mark its callees as referenced. 8700 Sema::SynthesizedFunctionScope Scope(S, FD); 8701 EnterExpressionEvaluationContext Context( 8702 S, Sema::ExpressionEvaluationContext::Unevaluated); 8703 8704 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8705 SourceLocation BodyLoc = 8706 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8707 StmtResult Body = 8708 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8709 if (!Body.isInvalid()) 8710 ExceptSpec.CalledStmt(Body.get()); 8711 8712 // FIXME: Can we hold onto this body and just transform it to potentially 8713 // evaluated when we're asked to define the function rather than rebuilding 8714 // it? Either that, or we should only build the bits of the body that we 8715 // need (the expressions, not the statements). 8716 } 8717 8718 return ExceptSpec; 8719 } 8720 8721 void Sema::CheckDelayedMemberExceptionSpecs() { 8722 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8723 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8724 8725 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8726 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8727 8728 // Perform any deferred checking of exception specifications for virtual 8729 // destructors. 8730 for (auto &Check : Overriding) 8731 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8732 8733 // Perform any deferred checking of exception specifications for befriended 8734 // special members. 8735 for (auto &Check : Equivalent) 8736 CheckEquivalentExceptionSpec(Check.second, Check.first); 8737 } 8738 8739 namespace { 8740 /// CRTP base class for visiting operations performed by a special member 8741 /// function (or inherited constructor). 8742 template<typename Derived> 8743 struct SpecialMemberVisitor { 8744 Sema &S; 8745 CXXMethodDecl *MD; 8746 Sema::CXXSpecialMember CSM; 8747 Sema::InheritedConstructorInfo *ICI; 8748 8749 // Properties of the special member, computed for convenience. 8750 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8751 8752 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8753 Sema::InheritedConstructorInfo *ICI) 8754 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8755 switch (CSM) { 8756 case Sema::CXXDefaultConstructor: 8757 case Sema::CXXCopyConstructor: 8758 case Sema::CXXMoveConstructor: 8759 IsConstructor = true; 8760 break; 8761 case Sema::CXXCopyAssignment: 8762 case Sema::CXXMoveAssignment: 8763 IsAssignment = true; 8764 break; 8765 case Sema::CXXDestructor: 8766 break; 8767 case Sema::CXXInvalid: 8768 llvm_unreachable("invalid special member kind"); 8769 } 8770 8771 if (MD->getNumParams()) { 8772 if (const ReferenceType *RT = 8773 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8774 ConstArg = RT->getPointeeType().isConstQualified(); 8775 } 8776 } 8777 8778 Derived &getDerived() { return static_cast<Derived&>(*this); } 8779 8780 /// Is this a "move" special member? 8781 bool isMove() const { 8782 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8783 } 8784 8785 /// Look up the corresponding special member in the given class. 8786 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8787 unsigned Quals, bool IsMutable) { 8788 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8789 ConstArg && !IsMutable); 8790 } 8791 8792 /// Look up the constructor for the specified base class to see if it's 8793 /// overridden due to this being an inherited constructor. 8794 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8795 if (!ICI) 8796 return {}; 8797 assert(CSM == Sema::CXXDefaultConstructor); 8798 auto *BaseCtor = 8799 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8800 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8801 return MD; 8802 return {}; 8803 } 8804 8805 /// A base or member subobject. 8806 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8807 8808 /// Get the location to use for a subobject in diagnostics. 8809 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8810 // FIXME: For an indirect virtual base, the direct base leading to 8811 // the indirect virtual base would be a more useful choice. 8812 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8813 return B->getBaseTypeLoc(); 8814 else 8815 return Subobj.get<FieldDecl*>()->getLocation(); 8816 } 8817 8818 enum BasesToVisit { 8819 /// Visit all non-virtual (direct) bases. 8820 VisitNonVirtualBases, 8821 /// Visit all direct bases, virtual or not. 8822 VisitDirectBases, 8823 /// Visit all non-virtual bases, and all virtual bases if the class 8824 /// is not abstract. 8825 VisitPotentiallyConstructedBases, 8826 /// Visit all direct or virtual bases. 8827 VisitAllBases 8828 }; 8829 8830 // Visit the bases and members of the class. 8831 bool visit(BasesToVisit Bases) { 8832 CXXRecordDecl *RD = MD->getParent(); 8833 8834 if (Bases == VisitPotentiallyConstructedBases) 8835 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8836 8837 for (auto &B : RD->bases()) 8838 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8839 getDerived().visitBase(&B)) 8840 return true; 8841 8842 if (Bases == VisitAllBases) 8843 for (auto &B : RD->vbases()) 8844 if (getDerived().visitBase(&B)) 8845 return true; 8846 8847 for (auto *F : RD->fields()) 8848 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8849 getDerived().visitField(F)) 8850 return true; 8851 8852 return false; 8853 } 8854 }; 8855 } 8856 8857 namespace { 8858 struct SpecialMemberDeletionInfo 8859 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8860 bool Diagnose; 8861 8862 SourceLocation Loc; 8863 8864 bool AllFieldsAreConst; 8865 8866 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 8867 Sema::CXXSpecialMember CSM, 8868 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 8869 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 8870 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 8871 8872 bool inUnion() const { return MD->getParent()->isUnion(); } 8873 8874 Sema::CXXSpecialMember getEffectiveCSM() { 8875 return ICI ? Sema::CXXInvalid : CSM; 8876 } 8877 8878 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 8879 8880 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 8881 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 8882 8883 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 8884 bool shouldDeleteForField(FieldDecl *FD); 8885 bool shouldDeleteForAllConstMembers(); 8886 8887 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 8888 unsigned Quals); 8889 bool shouldDeleteForSubobjectCall(Subobject Subobj, 8890 Sema::SpecialMemberOverloadResult SMOR, 8891 bool IsDtorCallInCtor); 8892 8893 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 8894 }; 8895 } 8896 8897 /// Is the given special member inaccessible when used on the given 8898 /// sub-object. 8899 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 8900 CXXMethodDecl *target) { 8901 /// If we're operating on a base class, the object type is the 8902 /// type of this special member. 8903 QualType objectTy; 8904 AccessSpecifier access = target->getAccess(); 8905 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 8906 objectTy = S.Context.getTypeDeclType(MD->getParent()); 8907 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 8908 8909 // If we're operating on a field, the object type is the type of the field. 8910 } else { 8911 objectTy = S.Context.getTypeDeclType(target->getParent()); 8912 } 8913 8914 return S.isMemberAccessibleForDeletion( 8915 target->getParent(), DeclAccessPair::make(target, access), objectTy); 8916 } 8917 8918 /// Check whether we should delete a special member due to the implicit 8919 /// definition containing a call to a special member of a subobject. 8920 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 8921 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 8922 bool IsDtorCallInCtor) { 8923 CXXMethodDecl *Decl = SMOR.getMethod(); 8924 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8925 8926 int DiagKind = -1; 8927 8928 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 8929 DiagKind = !Decl ? 0 : 1; 8930 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 8931 DiagKind = 2; 8932 else if (!isAccessible(Subobj, Decl)) 8933 DiagKind = 3; 8934 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 8935 !Decl->isTrivial()) { 8936 // A member of a union must have a trivial corresponding special member. 8937 // As a weird special case, a destructor call from a union's constructor 8938 // must be accessible and non-deleted, but need not be trivial. Such a 8939 // destructor is never actually called, but is semantically checked as 8940 // if it were. 8941 DiagKind = 4; 8942 } 8943 8944 if (DiagKind == -1) 8945 return false; 8946 8947 if (Diagnose) { 8948 if (Field) { 8949 S.Diag(Field->getLocation(), 8950 diag::note_deleted_special_member_class_subobject) 8951 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 8952 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 8953 } else { 8954 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 8955 S.Diag(Base->getBeginLoc(), 8956 diag::note_deleted_special_member_class_subobject) 8957 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8958 << Base->getType() << DiagKind << IsDtorCallInCtor 8959 << /*IsObjCPtr*/false; 8960 } 8961 8962 if (DiagKind == 1) 8963 S.NoteDeletedFunction(Decl); 8964 // FIXME: Explain inaccessibility if DiagKind == 3. 8965 } 8966 8967 return true; 8968 } 8969 8970 /// Check whether we should delete a special member function due to having a 8971 /// direct or virtual base class or non-static data member of class type M. 8972 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 8973 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 8974 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8975 bool IsMutable = Field && Field->isMutable(); 8976 8977 // C++11 [class.ctor]p5: 8978 // -- any direct or virtual base class, or non-static data member with no 8979 // brace-or-equal-initializer, has class type M (or array thereof) and 8980 // either M has no default constructor or overload resolution as applied 8981 // to M's default constructor results in an ambiguity or in a function 8982 // that is deleted or inaccessible 8983 // C++11 [class.copy]p11, C++11 [class.copy]p23: 8984 // -- a direct or virtual base class B that cannot be copied/moved because 8985 // overload resolution, as applied to B's corresponding special member, 8986 // results in an ambiguity or a function that is deleted or inaccessible 8987 // from the defaulted special member 8988 // C++11 [class.dtor]p5: 8989 // -- any direct or virtual base class [...] has a type with a destructor 8990 // that is deleted or inaccessible 8991 if (!(CSM == Sema::CXXDefaultConstructor && 8992 Field && Field->hasInClassInitializer()) && 8993 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 8994 false)) 8995 return true; 8996 8997 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 8998 // -- any direct or virtual base class or non-static data member has a 8999 // type with a destructor that is deleted or inaccessible 9000 if (IsConstructor) { 9001 Sema::SpecialMemberOverloadResult SMOR = 9002 S.LookupSpecialMember(Class, Sema::CXXDestructor, 9003 false, false, false, false, false); 9004 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 9005 return true; 9006 } 9007 9008 return false; 9009 } 9010 9011 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 9012 FieldDecl *FD, QualType FieldType) { 9013 // The defaulted special functions are defined as deleted if this is a variant 9014 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 9015 // type under ARC. 9016 if (!FieldType.hasNonTrivialObjCLifetime()) 9017 return false; 9018 9019 // Don't make the defaulted default constructor defined as deleted if the 9020 // member has an in-class initializer. 9021 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 9022 return false; 9023 9024 if (Diagnose) { 9025 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 9026 S.Diag(FD->getLocation(), 9027 diag::note_deleted_special_member_class_subobject) 9028 << getEffectiveCSM() << ParentClass << /*IsField*/true 9029 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 9030 } 9031 9032 return true; 9033 } 9034 9035 /// Check whether we should delete a special member function due to the class 9036 /// having a particular direct or virtual base class. 9037 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 9038 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 9039 // If program is correct, BaseClass cannot be null, but if it is, the error 9040 // must be reported elsewhere. 9041 if (!BaseClass) 9042 return false; 9043 // If we have an inheriting constructor, check whether we're calling an 9044 // inherited constructor instead of a default constructor. 9045 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 9046 if (auto *BaseCtor = SMOR.getMethod()) { 9047 // Note that we do not check access along this path; other than that, 9048 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 9049 // FIXME: Check that the base has a usable destructor! Sink this into 9050 // shouldDeleteForClassSubobject. 9051 if (BaseCtor->isDeleted() && Diagnose) { 9052 S.Diag(Base->getBeginLoc(), 9053 diag::note_deleted_special_member_class_subobject) 9054 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 9055 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 9056 << /*IsObjCPtr*/false; 9057 S.NoteDeletedFunction(BaseCtor); 9058 } 9059 return BaseCtor->isDeleted(); 9060 } 9061 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 9062 } 9063 9064 /// Check whether we should delete a special member function due to the class 9065 /// having a particular non-static data member. 9066 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 9067 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 9068 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 9069 9070 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 9071 return true; 9072 9073 if (CSM == Sema::CXXDefaultConstructor) { 9074 // For a default constructor, all references must be initialized in-class 9075 // and, if a union, it must have a non-const member. 9076 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 9077 if (Diagnose) 9078 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9079 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 9080 return true; 9081 } 9082 // C++11 [class.ctor]p5: any non-variant non-static data member of 9083 // const-qualified type (or array thereof) with no 9084 // brace-or-equal-initializer does not have a user-provided default 9085 // constructor. 9086 if (!inUnion() && FieldType.isConstQualified() && 9087 !FD->hasInClassInitializer() && 9088 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 9089 if (Diagnose) 9090 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9091 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 9092 return true; 9093 } 9094 9095 if (inUnion() && !FieldType.isConstQualified()) 9096 AllFieldsAreConst = false; 9097 } else if (CSM == Sema::CXXCopyConstructor) { 9098 // For a copy constructor, data members must not be of rvalue reference 9099 // type. 9100 if (FieldType->isRValueReferenceType()) { 9101 if (Diagnose) 9102 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 9103 << MD->getParent() << FD << FieldType; 9104 return true; 9105 } 9106 } else if (IsAssignment) { 9107 // For an assignment operator, data members must not be of reference type. 9108 if (FieldType->isReferenceType()) { 9109 if (Diagnose) 9110 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9111 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 9112 return true; 9113 } 9114 if (!FieldRecord && FieldType.isConstQualified()) { 9115 // C++11 [class.copy]p23: 9116 // -- a non-static data member of const non-class type (or array thereof) 9117 if (Diagnose) 9118 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9119 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 9120 return true; 9121 } 9122 } 9123 9124 if (FieldRecord) { 9125 // Some additional restrictions exist on the variant members. 9126 if (!inUnion() && FieldRecord->isUnion() && 9127 FieldRecord->isAnonymousStructOrUnion()) { 9128 bool AllVariantFieldsAreConst = true; 9129 9130 // FIXME: Handle anonymous unions declared within anonymous unions. 9131 for (auto *UI : FieldRecord->fields()) { 9132 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 9133 9134 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 9135 return true; 9136 9137 if (!UnionFieldType.isConstQualified()) 9138 AllVariantFieldsAreConst = false; 9139 9140 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 9141 if (UnionFieldRecord && 9142 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 9143 UnionFieldType.getCVRQualifiers())) 9144 return true; 9145 } 9146 9147 // At least one member in each anonymous union must be non-const 9148 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 9149 !FieldRecord->field_empty()) { 9150 if (Diagnose) 9151 S.Diag(FieldRecord->getLocation(), 9152 diag::note_deleted_default_ctor_all_const) 9153 << !!ICI << MD->getParent() << /*anonymous union*/1; 9154 return true; 9155 } 9156 9157 // Don't check the implicit member of the anonymous union type. 9158 // This is technically non-conformant, but sanity demands it. 9159 return false; 9160 } 9161 9162 if (shouldDeleteForClassSubobject(FieldRecord, FD, 9163 FieldType.getCVRQualifiers())) 9164 return true; 9165 } 9166 9167 return false; 9168 } 9169 9170 /// C++11 [class.ctor] p5: 9171 /// A defaulted default constructor for a class X is defined as deleted if 9172 /// X is a union and all of its variant members are of const-qualified type. 9173 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 9174 // This is a silly definition, because it gives an empty union a deleted 9175 // default constructor. Don't do that. 9176 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 9177 bool AnyFields = false; 9178 for (auto *F : MD->getParent()->fields()) 9179 if ((AnyFields = !F->isUnnamedBitfield())) 9180 break; 9181 if (!AnyFields) 9182 return false; 9183 if (Diagnose) 9184 S.Diag(MD->getParent()->getLocation(), 9185 diag::note_deleted_default_ctor_all_const) 9186 << !!ICI << MD->getParent() << /*not anonymous union*/0; 9187 return true; 9188 } 9189 return false; 9190 } 9191 9192 /// Determine whether a defaulted special member function should be defined as 9193 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 9194 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 9195 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 9196 InheritedConstructorInfo *ICI, 9197 bool Diagnose) { 9198 if (MD->isInvalidDecl()) 9199 return false; 9200 CXXRecordDecl *RD = MD->getParent(); 9201 assert(!RD->isDependentType() && "do deletion after instantiation"); 9202 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 9203 return false; 9204 9205 // C++11 [expr.lambda.prim]p19: 9206 // The closure type associated with a lambda-expression has a 9207 // deleted (8.4.3) default constructor and a deleted copy 9208 // assignment operator. 9209 // C++2a adds back these operators if the lambda has no lambda-capture. 9210 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 9211 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 9212 if (Diagnose) 9213 Diag(RD->getLocation(), diag::note_lambda_decl); 9214 return true; 9215 } 9216 9217 // For an anonymous struct or union, the copy and assignment special members 9218 // will never be used, so skip the check. For an anonymous union declared at 9219 // namespace scope, the constructor and destructor are used. 9220 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 9221 RD->isAnonymousStructOrUnion()) 9222 return false; 9223 9224 // C++11 [class.copy]p7, p18: 9225 // If the class definition declares a move constructor or move assignment 9226 // operator, an implicitly declared copy constructor or copy assignment 9227 // operator is defined as deleted. 9228 if (MD->isImplicit() && 9229 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 9230 CXXMethodDecl *UserDeclaredMove = nullptr; 9231 9232 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 9233 // deletion of the corresponding copy operation, not both copy operations. 9234 // MSVC 2015 has adopted the standards conforming behavior. 9235 bool DeletesOnlyMatchingCopy = 9236 getLangOpts().MSVCCompat && 9237 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 9238 9239 if (RD->hasUserDeclaredMoveConstructor() && 9240 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 9241 if (!Diagnose) return true; 9242 9243 // Find any user-declared move constructor. 9244 for (auto *I : RD->ctors()) { 9245 if (I->isMoveConstructor()) { 9246 UserDeclaredMove = I; 9247 break; 9248 } 9249 } 9250 assert(UserDeclaredMove); 9251 } else if (RD->hasUserDeclaredMoveAssignment() && 9252 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 9253 if (!Diagnose) return true; 9254 9255 // Find any user-declared move assignment operator. 9256 for (auto *I : RD->methods()) { 9257 if (I->isMoveAssignmentOperator()) { 9258 UserDeclaredMove = I; 9259 break; 9260 } 9261 } 9262 assert(UserDeclaredMove); 9263 } 9264 9265 if (UserDeclaredMove) { 9266 Diag(UserDeclaredMove->getLocation(), 9267 diag::note_deleted_copy_user_declared_move) 9268 << (CSM == CXXCopyAssignment) << RD 9269 << UserDeclaredMove->isMoveAssignmentOperator(); 9270 return true; 9271 } 9272 } 9273 9274 // Do access control from the special member function 9275 ContextRAII MethodContext(*this, MD); 9276 9277 // C++11 [class.dtor]p5: 9278 // -- for a virtual destructor, lookup of the non-array deallocation function 9279 // results in an ambiguity or in a function that is deleted or inaccessible 9280 if (CSM == CXXDestructor && MD->isVirtual()) { 9281 FunctionDecl *OperatorDelete = nullptr; 9282 DeclarationName Name = 9283 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 9284 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 9285 OperatorDelete, /*Diagnose*/false)) { 9286 if (Diagnose) 9287 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 9288 return true; 9289 } 9290 } 9291 9292 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 9293 9294 // Per DR1611, do not consider virtual bases of constructors of abstract 9295 // classes, since we are not going to construct them. 9296 // Per DR1658, do not consider virtual bases of destructors of abstract 9297 // classes either. 9298 // Per DR2180, for assignment operators we only assign (and thus only 9299 // consider) direct bases. 9300 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 9301 : SMI.VisitPotentiallyConstructedBases)) 9302 return true; 9303 9304 if (SMI.shouldDeleteForAllConstMembers()) 9305 return true; 9306 9307 if (getLangOpts().CUDA) { 9308 // We should delete the special member in CUDA mode if target inference 9309 // failed. 9310 // For inherited constructors (non-null ICI), CSM may be passed so that MD 9311 // is treated as certain special member, which may not reflect what special 9312 // member MD really is. However inferCUDATargetForImplicitSpecialMember 9313 // expects CSM to match MD, therefore recalculate CSM. 9314 assert(ICI || CSM == getSpecialMember(MD)); 9315 auto RealCSM = CSM; 9316 if (ICI) 9317 RealCSM = getSpecialMember(MD); 9318 9319 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 9320 SMI.ConstArg, Diagnose); 9321 } 9322 9323 return false; 9324 } 9325 9326 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 9327 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 9328 assert(DFK && "not a defaultable function"); 9329 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted"); 9330 9331 if (DFK.isSpecialMember()) { 9332 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 9333 nullptr, /*Diagnose=*/true); 9334 } else { 9335 DefaultedComparisonAnalyzer( 9336 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 9337 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 9338 .visit(); 9339 } 9340 } 9341 9342 /// Perform lookup for a special member of the specified kind, and determine 9343 /// whether it is trivial. If the triviality can be determined without the 9344 /// lookup, skip it. This is intended for use when determining whether a 9345 /// special member of a containing object is trivial, and thus does not ever 9346 /// perform overload resolution for default constructors. 9347 /// 9348 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 9349 /// member that was most likely to be intended to be trivial, if any. 9350 /// 9351 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 9352 /// determine whether the special member is trivial. 9353 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 9354 Sema::CXXSpecialMember CSM, unsigned Quals, 9355 bool ConstRHS, 9356 Sema::TrivialABIHandling TAH, 9357 CXXMethodDecl **Selected) { 9358 if (Selected) 9359 *Selected = nullptr; 9360 9361 switch (CSM) { 9362 case Sema::CXXInvalid: 9363 llvm_unreachable("not a special member"); 9364 9365 case Sema::CXXDefaultConstructor: 9366 // C++11 [class.ctor]p5: 9367 // A default constructor is trivial if: 9368 // - all the [direct subobjects] have trivial default constructors 9369 // 9370 // Note, no overload resolution is performed in this case. 9371 if (RD->hasTrivialDefaultConstructor()) 9372 return true; 9373 9374 if (Selected) { 9375 // If there's a default constructor which could have been trivial, dig it 9376 // out. Otherwise, if there's any user-provided default constructor, point 9377 // to that as an example of why there's not a trivial one. 9378 CXXConstructorDecl *DefCtor = nullptr; 9379 if (RD->needsImplicitDefaultConstructor()) 9380 S.DeclareImplicitDefaultConstructor(RD); 9381 for (auto *CI : RD->ctors()) { 9382 if (!CI->isDefaultConstructor()) 9383 continue; 9384 DefCtor = CI; 9385 if (!DefCtor->isUserProvided()) 9386 break; 9387 } 9388 9389 *Selected = DefCtor; 9390 } 9391 9392 return false; 9393 9394 case Sema::CXXDestructor: 9395 // C++11 [class.dtor]p5: 9396 // A destructor is trivial if: 9397 // - all the direct [subobjects] have trivial destructors 9398 if (RD->hasTrivialDestructor() || 9399 (TAH == Sema::TAH_ConsiderTrivialABI && 9400 RD->hasTrivialDestructorForCall())) 9401 return true; 9402 9403 if (Selected) { 9404 if (RD->needsImplicitDestructor()) 9405 S.DeclareImplicitDestructor(RD); 9406 *Selected = RD->getDestructor(); 9407 } 9408 9409 return false; 9410 9411 case Sema::CXXCopyConstructor: 9412 // C++11 [class.copy]p12: 9413 // A copy constructor is trivial if: 9414 // - the constructor selected to copy each direct [subobject] is trivial 9415 if (RD->hasTrivialCopyConstructor() || 9416 (TAH == Sema::TAH_ConsiderTrivialABI && 9417 RD->hasTrivialCopyConstructorForCall())) { 9418 if (Quals == Qualifiers::Const) 9419 // We must either select the trivial copy constructor or reach an 9420 // ambiguity; no need to actually perform overload resolution. 9421 return true; 9422 } else if (!Selected) { 9423 return false; 9424 } 9425 // In C++98, we are not supposed to perform overload resolution here, but we 9426 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 9427 // cases like B as having a non-trivial copy constructor: 9428 // struct A { template<typename T> A(T&); }; 9429 // struct B { mutable A a; }; 9430 goto NeedOverloadResolution; 9431 9432 case Sema::CXXCopyAssignment: 9433 // C++11 [class.copy]p25: 9434 // A copy assignment operator is trivial if: 9435 // - the assignment operator selected to copy each direct [subobject] is 9436 // trivial 9437 if (RD->hasTrivialCopyAssignment()) { 9438 if (Quals == Qualifiers::Const) 9439 return true; 9440 } else if (!Selected) { 9441 return false; 9442 } 9443 // In C++98, we are not supposed to perform overload resolution here, but we 9444 // treat that as a language defect. 9445 goto NeedOverloadResolution; 9446 9447 case Sema::CXXMoveConstructor: 9448 case Sema::CXXMoveAssignment: 9449 NeedOverloadResolution: 9450 Sema::SpecialMemberOverloadResult SMOR = 9451 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 9452 9453 // The standard doesn't describe how to behave if the lookup is ambiguous. 9454 // We treat it as not making the member non-trivial, just like the standard 9455 // mandates for the default constructor. This should rarely matter, because 9456 // the member will also be deleted. 9457 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9458 return true; 9459 9460 if (!SMOR.getMethod()) { 9461 assert(SMOR.getKind() == 9462 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 9463 return false; 9464 } 9465 9466 // We deliberately don't check if we found a deleted special member. We're 9467 // not supposed to! 9468 if (Selected) 9469 *Selected = SMOR.getMethod(); 9470 9471 if (TAH == Sema::TAH_ConsiderTrivialABI && 9472 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 9473 return SMOR.getMethod()->isTrivialForCall(); 9474 return SMOR.getMethod()->isTrivial(); 9475 } 9476 9477 llvm_unreachable("unknown special method kind"); 9478 } 9479 9480 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 9481 for (auto *CI : RD->ctors()) 9482 if (!CI->isImplicit()) 9483 return CI; 9484 9485 // Look for constructor templates. 9486 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 9487 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 9488 if (CXXConstructorDecl *CD = 9489 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 9490 return CD; 9491 } 9492 9493 return nullptr; 9494 } 9495 9496 /// The kind of subobject we are checking for triviality. The values of this 9497 /// enumeration are used in diagnostics. 9498 enum TrivialSubobjectKind { 9499 /// The subobject is a base class. 9500 TSK_BaseClass, 9501 /// The subobject is a non-static data member. 9502 TSK_Field, 9503 /// The object is actually the complete object. 9504 TSK_CompleteObject 9505 }; 9506 9507 /// Check whether the special member selected for a given type would be trivial. 9508 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9509 QualType SubType, bool ConstRHS, 9510 Sema::CXXSpecialMember CSM, 9511 TrivialSubobjectKind Kind, 9512 Sema::TrivialABIHandling TAH, bool Diagnose) { 9513 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9514 if (!SubRD) 9515 return true; 9516 9517 CXXMethodDecl *Selected; 9518 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9519 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9520 return true; 9521 9522 if (Diagnose) { 9523 if (ConstRHS) 9524 SubType.addConst(); 9525 9526 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9527 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9528 << Kind << SubType.getUnqualifiedType(); 9529 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9530 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9531 } else if (!Selected) 9532 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9533 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9534 else if (Selected->isUserProvided()) { 9535 if (Kind == TSK_CompleteObject) 9536 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9537 << Kind << SubType.getUnqualifiedType() << CSM; 9538 else { 9539 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9540 << Kind << SubType.getUnqualifiedType() << CSM; 9541 S.Diag(Selected->getLocation(), diag::note_declared_at); 9542 } 9543 } else { 9544 if (Kind != TSK_CompleteObject) 9545 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9546 << Kind << SubType.getUnqualifiedType() << CSM; 9547 9548 // Explain why the defaulted or deleted special member isn't trivial. 9549 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9550 Diagnose); 9551 } 9552 } 9553 9554 return false; 9555 } 9556 9557 /// Check whether the members of a class type allow a special member to be 9558 /// trivial. 9559 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9560 Sema::CXXSpecialMember CSM, 9561 bool ConstArg, 9562 Sema::TrivialABIHandling TAH, 9563 bool Diagnose) { 9564 for (const auto *FI : RD->fields()) { 9565 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9566 continue; 9567 9568 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9569 9570 // Pretend anonymous struct or union members are members of this class. 9571 if (FI->isAnonymousStructOrUnion()) { 9572 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9573 CSM, ConstArg, TAH, Diagnose)) 9574 return false; 9575 continue; 9576 } 9577 9578 // C++11 [class.ctor]p5: 9579 // A default constructor is trivial if [...] 9580 // -- no non-static data member of its class has a 9581 // brace-or-equal-initializer 9582 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9583 if (Diagnose) 9584 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init) 9585 << FI; 9586 return false; 9587 } 9588 9589 // Objective C ARC 4.3.5: 9590 // [...] nontrivally ownership-qualified types are [...] not trivially 9591 // default constructible, copy constructible, move constructible, copy 9592 // assignable, move assignable, or destructible [...] 9593 if (FieldType.hasNonTrivialObjCLifetime()) { 9594 if (Diagnose) 9595 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9596 << RD << FieldType.getObjCLifetime(); 9597 return false; 9598 } 9599 9600 bool ConstRHS = ConstArg && !FI->isMutable(); 9601 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9602 CSM, TSK_Field, TAH, Diagnose)) 9603 return false; 9604 } 9605 9606 return true; 9607 } 9608 9609 /// Diagnose why the specified class does not have a trivial special member of 9610 /// the given kind. 9611 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9612 QualType Ty = Context.getRecordType(RD); 9613 9614 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9615 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9616 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9617 /*Diagnose*/true); 9618 } 9619 9620 /// Determine whether a defaulted or deleted special member function is trivial, 9621 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9622 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9623 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9624 TrivialABIHandling TAH, bool Diagnose) { 9625 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 9626 9627 CXXRecordDecl *RD = MD->getParent(); 9628 9629 bool ConstArg = false; 9630 9631 // C++11 [class.copy]p12, p25: [DR1593] 9632 // A [special member] is trivial if [...] its parameter-type-list is 9633 // equivalent to the parameter-type-list of an implicit declaration [...] 9634 switch (CSM) { 9635 case CXXDefaultConstructor: 9636 case CXXDestructor: 9637 // Trivial default constructors and destructors cannot have parameters. 9638 break; 9639 9640 case CXXCopyConstructor: 9641 case CXXCopyAssignment: { 9642 // Trivial copy operations always have const, non-volatile parameter types. 9643 ConstArg = true; 9644 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9645 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9646 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 9647 if (Diagnose) 9648 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9649 << Param0->getSourceRange() << Param0->getType() 9650 << Context.getLValueReferenceType( 9651 Context.getRecordType(RD).withConst()); 9652 return false; 9653 } 9654 break; 9655 } 9656 9657 case CXXMoveConstructor: 9658 case CXXMoveAssignment: { 9659 // Trivial move operations always have non-cv-qualified parameters. 9660 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9661 const RValueReferenceType *RT = 9662 Param0->getType()->getAs<RValueReferenceType>(); 9663 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9664 if (Diagnose) 9665 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9666 << Param0->getSourceRange() << Param0->getType() 9667 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9668 return false; 9669 } 9670 break; 9671 } 9672 9673 case CXXInvalid: 9674 llvm_unreachable("not a special member"); 9675 } 9676 9677 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9678 if (Diagnose) 9679 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9680 diag::note_nontrivial_default_arg) 9681 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9682 return false; 9683 } 9684 if (MD->isVariadic()) { 9685 if (Diagnose) 9686 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9687 return false; 9688 } 9689 9690 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9691 // A copy/move [constructor or assignment operator] is trivial if 9692 // -- the [member] selected to copy/move each direct base class subobject 9693 // is trivial 9694 // 9695 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9696 // A [default constructor or destructor] is trivial if 9697 // -- all the direct base classes have trivial [default constructors or 9698 // destructors] 9699 for (const auto &BI : RD->bases()) 9700 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9701 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9702 return false; 9703 9704 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9705 // A copy/move [constructor or assignment operator] for a class X is 9706 // trivial if 9707 // -- for each non-static data member of X that is of class type (or array 9708 // thereof), the constructor selected to copy/move that member is 9709 // trivial 9710 // 9711 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9712 // A [default constructor or destructor] is trivial if 9713 // -- for all of the non-static data members of its class that are of class 9714 // type (or array thereof), each such class has a trivial [default 9715 // constructor or destructor] 9716 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9717 return false; 9718 9719 // C++11 [class.dtor]p5: 9720 // A destructor is trivial if [...] 9721 // -- the destructor is not virtual 9722 if (CSM == CXXDestructor && MD->isVirtual()) { 9723 if (Diagnose) 9724 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9725 return false; 9726 } 9727 9728 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9729 // A [special member] for class X is trivial if [...] 9730 // -- class X has no virtual functions and no virtual base classes 9731 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9732 if (!Diagnose) 9733 return false; 9734 9735 if (RD->getNumVBases()) { 9736 // Check for virtual bases. We already know that the corresponding 9737 // member in all bases is trivial, so vbases must all be direct. 9738 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9739 assert(BS.isVirtual()); 9740 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9741 return false; 9742 } 9743 9744 // Must have a virtual method. 9745 for (const auto *MI : RD->methods()) { 9746 if (MI->isVirtual()) { 9747 SourceLocation MLoc = MI->getBeginLoc(); 9748 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9749 return false; 9750 } 9751 } 9752 9753 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 9754 } 9755 9756 // Looks like it's trivial! 9757 return true; 9758 } 9759 9760 namespace { 9761 struct FindHiddenVirtualMethod { 9762 Sema *S; 9763 CXXMethodDecl *Method; 9764 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9765 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9766 9767 private: 9768 /// Check whether any most overridden method from MD in Methods 9769 static bool CheckMostOverridenMethods( 9770 const CXXMethodDecl *MD, 9771 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9772 if (MD->size_overridden_methods() == 0) 9773 return Methods.count(MD->getCanonicalDecl()); 9774 for (const CXXMethodDecl *O : MD->overridden_methods()) 9775 if (CheckMostOverridenMethods(O, Methods)) 9776 return true; 9777 return false; 9778 } 9779 9780 public: 9781 /// Member lookup function that determines whether a given C++ 9782 /// method overloads virtual methods in a base class without overriding any, 9783 /// to be used with CXXRecordDecl::lookupInBases(). 9784 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9785 RecordDecl *BaseRecord = 9786 Specifier->getType()->castAs<RecordType>()->getDecl(); 9787 9788 DeclarationName Name = Method->getDeclName(); 9789 assert(Name.getNameKind() == DeclarationName::Identifier); 9790 9791 bool foundSameNameMethod = false; 9792 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9793 for (Path.Decls = BaseRecord->lookup(Name).begin(); 9794 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) { 9795 NamedDecl *D = *Path.Decls; 9796 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9797 MD = MD->getCanonicalDecl(); 9798 foundSameNameMethod = true; 9799 // Interested only in hidden virtual methods. 9800 if (!MD->isVirtual()) 9801 continue; 9802 // If the method we are checking overrides a method from its base 9803 // don't warn about the other overloaded methods. Clang deviates from 9804 // GCC by only diagnosing overloads of inherited virtual functions that 9805 // do not override any other virtual functions in the base. GCC's 9806 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9807 // function from a base class. These cases may be better served by a 9808 // warning (not specific to virtual functions) on call sites when the 9809 // call would select a different function from the base class, were it 9810 // visible. 9811 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9812 if (!S->IsOverload(Method, MD, false)) 9813 return true; 9814 // Collect the overload only if its hidden. 9815 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9816 overloadedMethods.push_back(MD); 9817 } 9818 } 9819 9820 if (foundSameNameMethod) 9821 OverloadedMethods.append(overloadedMethods.begin(), 9822 overloadedMethods.end()); 9823 return foundSameNameMethod; 9824 } 9825 }; 9826 } // end anonymous namespace 9827 9828 /// Add the most overridden methods from MD to Methods 9829 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9830 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9831 if (MD->size_overridden_methods() == 0) 9832 Methods.insert(MD->getCanonicalDecl()); 9833 else 9834 for (const CXXMethodDecl *O : MD->overridden_methods()) 9835 AddMostOverridenMethods(O, Methods); 9836 } 9837 9838 /// Check if a method overloads virtual methods in a base class without 9839 /// overriding any. 9840 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9841 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9842 if (!MD->getDeclName().isIdentifier()) 9843 return; 9844 9845 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9846 /*bool RecordPaths=*/false, 9847 /*bool DetectVirtual=*/false); 9848 FindHiddenVirtualMethod FHVM; 9849 FHVM.Method = MD; 9850 FHVM.S = this; 9851 9852 // Keep the base methods that were overridden or introduced in the subclass 9853 // by 'using' in a set. A base method not in this set is hidden. 9854 CXXRecordDecl *DC = MD->getParent(); 9855 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9856 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9857 NamedDecl *ND = *I; 9858 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9859 ND = shad->getTargetDecl(); 9860 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9861 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9862 } 9863 9864 if (DC->lookupInBases(FHVM, Paths)) 9865 OverloadedMethods = FHVM.OverloadedMethods; 9866 } 9867 9868 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 9869 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9870 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 9871 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 9872 PartialDiagnostic PD = PDiag( 9873 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 9874 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 9875 Diag(overloadedMD->getLocation(), PD); 9876 } 9877 } 9878 9879 /// Diagnose methods which overload virtual methods in a base class 9880 /// without overriding any. 9881 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 9882 if (MD->isInvalidDecl()) 9883 return; 9884 9885 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 9886 return; 9887 9888 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9889 FindHiddenVirtualMethods(MD, OverloadedMethods); 9890 if (!OverloadedMethods.empty()) { 9891 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 9892 << MD << (OverloadedMethods.size() > 1); 9893 9894 NoteHiddenVirtualMethods(MD, OverloadedMethods); 9895 } 9896 } 9897 9898 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 9899 auto PrintDiagAndRemoveAttr = [&](unsigned N) { 9900 // No diagnostics if this is a template instantiation. 9901 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) { 9902 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9903 diag::ext_cannot_use_trivial_abi) << &RD; 9904 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9905 diag::note_cannot_use_trivial_abi_reason) << &RD << N; 9906 } 9907 RD.dropAttr<TrivialABIAttr>(); 9908 }; 9909 9910 // Ill-formed if the copy and move constructors are deleted. 9911 auto HasNonDeletedCopyOrMoveConstructor = [&]() { 9912 // If the type is dependent, then assume it might have 9913 // implicit copy or move ctor because we won't know yet at this point. 9914 if (RD.isDependentType()) 9915 return true; 9916 if (RD.needsImplicitCopyConstructor() && 9917 !RD.defaultedCopyConstructorIsDeleted()) 9918 return true; 9919 if (RD.needsImplicitMoveConstructor() && 9920 !RD.defaultedMoveConstructorIsDeleted()) 9921 return true; 9922 for (const CXXConstructorDecl *CD : RD.ctors()) 9923 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted()) 9924 return true; 9925 return false; 9926 }; 9927 9928 if (!HasNonDeletedCopyOrMoveConstructor()) { 9929 PrintDiagAndRemoveAttr(0); 9930 return; 9931 } 9932 9933 // Ill-formed if the struct has virtual functions. 9934 if (RD.isPolymorphic()) { 9935 PrintDiagAndRemoveAttr(1); 9936 return; 9937 } 9938 9939 for (const auto &B : RD.bases()) { 9940 // Ill-formed if the base class is non-trivial for the purpose of calls or a 9941 // virtual base. 9942 if (!B.getType()->isDependentType() && 9943 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) { 9944 PrintDiagAndRemoveAttr(2); 9945 return; 9946 } 9947 9948 if (B.isVirtual()) { 9949 PrintDiagAndRemoveAttr(3); 9950 return; 9951 } 9952 } 9953 9954 for (const auto *FD : RD.fields()) { 9955 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 9956 // non-trivial for the purpose of calls. 9957 QualType FT = FD->getType(); 9958 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 9959 PrintDiagAndRemoveAttr(4); 9960 return; 9961 } 9962 9963 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 9964 if (!RT->isDependentType() && 9965 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 9966 PrintDiagAndRemoveAttr(5); 9967 return; 9968 } 9969 } 9970 } 9971 9972 void Sema::ActOnFinishCXXMemberSpecification( 9973 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 9974 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 9975 if (!TagDecl) 9976 return; 9977 9978 AdjustDeclIfTemplate(TagDecl); 9979 9980 for (const ParsedAttr &AL : AttrList) { 9981 if (AL.getKind() != ParsedAttr::AT_Visibility) 9982 continue; 9983 AL.setInvalid(); 9984 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 9985 } 9986 9987 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 9988 // strict aliasing violation! 9989 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 9990 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 9991 9992 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 9993 } 9994 9995 /// Find the equality comparison functions that should be implicitly declared 9996 /// in a given class definition, per C++2a [class.compare.default]p3. 9997 static void findImplicitlyDeclaredEqualityComparisons( 9998 ASTContext &Ctx, CXXRecordDecl *RD, 9999 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 10000 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 10001 if (!RD->lookup(EqEq).empty()) 10002 // Member operator== explicitly declared: no implicit operator==s. 10003 return; 10004 10005 // Traverse friends looking for an '==' or a '<=>'. 10006 for (FriendDecl *Friend : RD->friends()) { 10007 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 10008 if (!FD) continue; 10009 10010 if (FD->getOverloadedOperator() == OO_EqualEqual) { 10011 // Friend operator== explicitly declared: no implicit operator==s. 10012 Spaceships.clear(); 10013 return; 10014 } 10015 10016 if (FD->getOverloadedOperator() == OO_Spaceship && 10017 FD->isExplicitlyDefaulted()) 10018 Spaceships.push_back(FD); 10019 } 10020 10021 // Look for members named 'operator<=>'. 10022 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 10023 for (NamedDecl *ND : RD->lookup(Cmp)) { 10024 // Note that we could find a non-function here (either a function template 10025 // or a using-declaration). Neither case results in an implicit 10026 // 'operator=='. 10027 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 10028 if (FD->isExplicitlyDefaulted()) 10029 Spaceships.push_back(FD); 10030 } 10031 } 10032 10033 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 10034 /// special functions, such as the default constructor, copy 10035 /// constructor, or destructor, to the given C++ class (C++ 10036 /// [special]p1). This routine can only be executed just before the 10037 /// definition of the class is complete. 10038 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 10039 // Don't add implicit special members to templated classes. 10040 // FIXME: This means unqualified lookups for 'operator=' within a class 10041 // template don't work properly. 10042 if (!ClassDecl->isDependentType()) { 10043 if (ClassDecl->needsImplicitDefaultConstructor()) { 10044 ++getASTContext().NumImplicitDefaultConstructors; 10045 10046 if (ClassDecl->hasInheritedConstructor()) 10047 DeclareImplicitDefaultConstructor(ClassDecl); 10048 } 10049 10050 if (ClassDecl->needsImplicitCopyConstructor()) { 10051 ++getASTContext().NumImplicitCopyConstructors; 10052 10053 // If the properties or semantics of the copy constructor couldn't be 10054 // determined while the class was being declared, force a declaration 10055 // of it now. 10056 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 10057 ClassDecl->hasInheritedConstructor()) 10058 DeclareImplicitCopyConstructor(ClassDecl); 10059 // For the MS ABI we need to know whether the copy ctor is deleted. A 10060 // prerequisite for deleting the implicit copy ctor is that the class has 10061 // a move ctor or move assignment that is either user-declared or whose 10062 // semantics are inherited from a subobject. FIXME: We should provide a 10063 // more direct way for CodeGen to ask whether the constructor was deleted. 10064 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 10065 (ClassDecl->hasUserDeclaredMoveConstructor() || 10066 ClassDecl->needsOverloadResolutionForMoveConstructor() || 10067 ClassDecl->hasUserDeclaredMoveAssignment() || 10068 ClassDecl->needsOverloadResolutionForMoveAssignment())) 10069 DeclareImplicitCopyConstructor(ClassDecl); 10070 } 10071 10072 if (getLangOpts().CPlusPlus11 && 10073 ClassDecl->needsImplicitMoveConstructor()) { 10074 ++getASTContext().NumImplicitMoveConstructors; 10075 10076 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 10077 ClassDecl->hasInheritedConstructor()) 10078 DeclareImplicitMoveConstructor(ClassDecl); 10079 } 10080 10081 if (ClassDecl->needsImplicitCopyAssignment()) { 10082 ++getASTContext().NumImplicitCopyAssignmentOperators; 10083 10084 // If we have a dynamic class, then the copy assignment operator may be 10085 // virtual, so we have to declare it immediately. This ensures that, e.g., 10086 // it shows up in the right place in the vtable and that we diagnose 10087 // problems with the implicit exception specification. 10088 if (ClassDecl->isDynamicClass() || 10089 ClassDecl->needsOverloadResolutionForCopyAssignment() || 10090 ClassDecl->hasInheritedAssignment()) 10091 DeclareImplicitCopyAssignment(ClassDecl); 10092 } 10093 10094 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 10095 ++getASTContext().NumImplicitMoveAssignmentOperators; 10096 10097 // Likewise for the move assignment operator. 10098 if (ClassDecl->isDynamicClass() || 10099 ClassDecl->needsOverloadResolutionForMoveAssignment() || 10100 ClassDecl->hasInheritedAssignment()) 10101 DeclareImplicitMoveAssignment(ClassDecl); 10102 } 10103 10104 if (ClassDecl->needsImplicitDestructor()) { 10105 ++getASTContext().NumImplicitDestructors; 10106 10107 // If we have a dynamic class, then the destructor may be virtual, so we 10108 // have to declare the destructor immediately. This ensures that, e.g., it 10109 // shows up in the right place in the vtable and that we diagnose problems 10110 // with the implicit exception specification. 10111 if (ClassDecl->isDynamicClass() || 10112 ClassDecl->needsOverloadResolutionForDestructor()) 10113 DeclareImplicitDestructor(ClassDecl); 10114 } 10115 } 10116 10117 // C++2a [class.compare.default]p3: 10118 // If the member-specification does not explicitly declare any member or 10119 // friend named operator==, an == operator function is declared implicitly 10120 // for each defaulted three-way comparison operator function defined in 10121 // the member-specification 10122 // FIXME: Consider doing this lazily. 10123 // We do this during the initial parse for a class template, not during 10124 // instantiation, so that we can handle unqualified lookups for 'operator==' 10125 // when parsing the template. 10126 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) { 10127 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships; 10128 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 10129 DefaultedSpaceships); 10130 for (auto *FD : DefaultedSpaceships) 10131 DeclareImplicitEqualityComparison(ClassDecl, FD); 10132 } 10133 } 10134 10135 unsigned 10136 Sema::ActOnReenterTemplateScope(Decl *D, 10137 llvm::function_ref<Scope *()> EnterScope) { 10138 if (!D) 10139 return 0; 10140 AdjustDeclIfTemplate(D); 10141 10142 // In order to get name lookup right, reenter template scopes in order from 10143 // outermost to innermost. 10144 SmallVector<TemplateParameterList *, 4> ParameterLists; 10145 DeclContext *LookupDC = dyn_cast<DeclContext>(D); 10146 10147 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 10148 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 10149 ParameterLists.push_back(DD->getTemplateParameterList(i)); 10150 10151 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10152 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 10153 ParameterLists.push_back(FTD->getTemplateParameters()); 10154 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 10155 LookupDC = VD->getDeclContext(); 10156 10157 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate()) 10158 ParameterLists.push_back(VTD->getTemplateParameters()); 10159 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) 10160 ParameterLists.push_back(PSD->getTemplateParameters()); 10161 } 10162 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 10163 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 10164 ParameterLists.push_back(TD->getTemplateParameterList(i)); 10165 10166 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 10167 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 10168 ParameterLists.push_back(CTD->getTemplateParameters()); 10169 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 10170 ParameterLists.push_back(PSD->getTemplateParameters()); 10171 } 10172 } 10173 // FIXME: Alias declarations and concepts. 10174 10175 unsigned Count = 0; 10176 Scope *InnermostTemplateScope = nullptr; 10177 for (TemplateParameterList *Params : ParameterLists) { 10178 // Ignore explicit specializations; they don't contribute to the template 10179 // depth. 10180 if (Params->size() == 0) 10181 continue; 10182 10183 InnermostTemplateScope = EnterScope(); 10184 for (NamedDecl *Param : *Params) { 10185 if (Param->getDeclName()) { 10186 InnermostTemplateScope->AddDecl(Param); 10187 IdResolver.AddDecl(Param); 10188 } 10189 } 10190 ++Count; 10191 } 10192 10193 // Associate the new template scopes with the corresponding entities. 10194 if (InnermostTemplateScope) { 10195 assert(LookupDC && "no enclosing DeclContext for template lookup"); 10196 EnterTemplatedContext(InnermostTemplateScope, LookupDC); 10197 } 10198 10199 return Count; 10200 } 10201 10202 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10203 if (!RecordD) return; 10204 AdjustDeclIfTemplate(RecordD); 10205 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 10206 PushDeclContext(S, Record); 10207 } 10208 10209 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10210 if (!RecordD) return; 10211 PopDeclContext(); 10212 } 10213 10214 /// This is used to implement the constant expression evaluation part of the 10215 /// attribute enable_if extension. There is nothing in standard C++ which would 10216 /// require reentering parameters. 10217 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 10218 if (!Param) 10219 return; 10220 10221 S->AddDecl(Param); 10222 if (Param->getDeclName()) 10223 IdResolver.AddDecl(Param); 10224 } 10225 10226 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 10227 /// parsing a top-level (non-nested) C++ class, and we are now 10228 /// parsing those parts of the given Method declaration that could 10229 /// not be parsed earlier (C++ [class.mem]p2), such as default 10230 /// arguments. This action should enter the scope of the given 10231 /// Method declaration as if we had just parsed the qualified method 10232 /// name. However, it should not bring the parameters into scope; 10233 /// that will be performed by ActOnDelayedCXXMethodParameter. 10234 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10235 } 10236 10237 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 10238 /// C++ method declaration. We're (re-)introducing the given 10239 /// function parameter into scope for use in parsing later parts of 10240 /// the method declaration. For example, we could see an 10241 /// ActOnParamDefaultArgument event for this parameter. 10242 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 10243 if (!ParamD) 10244 return; 10245 10246 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 10247 10248 S->AddDecl(Param); 10249 if (Param->getDeclName()) 10250 IdResolver.AddDecl(Param); 10251 } 10252 10253 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 10254 /// processing the delayed method declaration for Method. The method 10255 /// declaration is now considered finished. There may be a separate 10256 /// ActOnStartOfFunctionDef action later (not necessarily 10257 /// immediately!) for this method, if it was also defined inside the 10258 /// class body. 10259 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10260 if (!MethodD) 10261 return; 10262 10263 AdjustDeclIfTemplate(MethodD); 10264 10265 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 10266 10267 // Now that we have our default arguments, check the constructor 10268 // again. It could produce additional diagnostics or affect whether 10269 // the class has implicitly-declared destructors, among other 10270 // things. 10271 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 10272 CheckConstructor(Constructor); 10273 10274 // Check the default arguments, which we may have added. 10275 if (!Method->isInvalidDecl()) 10276 CheckCXXDefaultArguments(Method); 10277 } 10278 10279 // Emit the given diagnostic for each non-address-space qualifier. 10280 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 10281 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 10282 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10283 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 10284 bool DiagOccured = false; 10285 FTI.MethodQualifiers->forEachQualifier( 10286 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 10287 SourceLocation SL) { 10288 // This diagnostic should be emitted on any qualifier except an addr 10289 // space qualifier. However, forEachQualifier currently doesn't visit 10290 // addr space qualifiers, so there's no way to write this condition 10291 // right now; we just diagnose on everything. 10292 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 10293 DiagOccured = true; 10294 }); 10295 if (DiagOccured) 10296 D.setInvalidType(); 10297 } 10298 } 10299 10300 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 10301 /// the well-formedness of the constructor declarator @p D with type @p 10302 /// R. If there are any errors in the declarator, this routine will 10303 /// emit diagnostics and set the invalid bit to true. In any case, the type 10304 /// will be updated to reflect a well-formed type for the constructor and 10305 /// returned. 10306 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 10307 StorageClass &SC) { 10308 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 10309 10310 // C++ [class.ctor]p3: 10311 // A constructor shall not be virtual (10.3) or static (9.4). A 10312 // constructor can be invoked for a const, volatile or const 10313 // volatile object. A constructor shall not be declared const, 10314 // volatile, or const volatile (9.3.2). 10315 if (isVirtual) { 10316 if (!D.isInvalidType()) 10317 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10318 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 10319 << SourceRange(D.getIdentifierLoc()); 10320 D.setInvalidType(); 10321 } 10322 if (SC == SC_Static) { 10323 if (!D.isInvalidType()) 10324 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10325 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10326 << SourceRange(D.getIdentifierLoc()); 10327 D.setInvalidType(); 10328 SC = SC_None; 10329 } 10330 10331 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10332 diagnoseIgnoredQualifiers( 10333 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 10334 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 10335 D.getDeclSpec().getRestrictSpecLoc(), 10336 D.getDeclSpec().getAtomicSpecLoc()); 10337 D.setInvalidType(); 10338 } 10339 10340 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 10341 10342 // C++0x [class.ctor]p4: 10343 // A constructor shall not be declared with a ref-qualifier. 10344 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10345 if (FTI.hasRefQualifier()) { 10346 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 10347 << FTI.RefQualifierIsLValueRef 10348 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10349 D.setInvalidType(); 10350 } 10351 10352 // Rebuild the function type "R" without any type qualifiers (in 10353 // case any of the errors above fired) and with "void" as the 10354 // return type, since constructors don't have return types. 10355 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10356 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 10357 return R; 10358 10359 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10360 EPI.TypeQuals = Qualifiers(); 10361 EPI.RefQualifier = RQ_None; 10362 10363 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 10364 } 10365 10366 /// CheckConstructor - Checks a fully-formed constructor for 10367 /// well-formedness, issuing any diagnostics required. Returns true if 10368 /// the constructor declarator is invalid. 10369 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 10370 CXXRecordDecl *ClassDecl 10371 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 10372 if (!ClassDecl) 10373 return Constructor->setInvalidDecl(); 10374 10375 // C++ [class.copy]p3: 10376 // A declaration of a constructor for a class X is ill-formed if 10377 // its first parameter is of type (optionally cv-qualified) X and 10378 // either there are no other parameters or else all other 10379 // parameters have default arguments. 10380 if (!Constructor->isInvalidDecl() && 10381 Constructor->hasOneParamOrDefaultArgs() && 10382 Constructor->getTemplateSpecializationKind() != 10383 TSK_ImplicitInstantiation) { 10384 QualType ParamType = Constructor->getParamDecl(0)->getType(); 10385 QualType ClassTy = Context.getTagDeclType(ClassDecl); 10386 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 10387 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 10388 const char *ConstRef 10389 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 10390 : " const &"; 10391 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 10392 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 10393 10394 // FIXME: Rather that making the constructor invalid, we should endeavor 10395 // to fix the type. 10396 Constructor->setInvalidDecl(); 10397 } 10398 } 10399 } 10400 10401 /// CheckDestructor - Checks a fully-formed destructor definition for 10402 /// well-formedness, issuing any diagnostics required. Returns true 10403 /// on error. 10404 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 10405 CXXRecordDecl *RD = Destructor->getParent(); 10406 10407 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 10408 SourceLocation Loc; 10409 10410 if (!Destructor->isImplicit()) 10411 Loc = Destructor->getLocation(); 10412 else 10413 Loc = RD->getLocation(); 10414 10415 // If we have a virtual destructor, look up the deallocation function 10416 if (FunctionDecl *OperatorDelete = 10417 FindDeallocationFunctionForDestructor(Loc, RD)) { 10418 Expr *ThisArg = nullptr; 10419 10420 // If the notional 'delete this' expression requires a non-trivial 10421 // conversion from 'this' to the type of a destroying operator delete's 10422 // first parameter, perform that conversion now. 10423 if (OperatorDelete->isDestroyingOperatorDelete()) { 10424 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 10425 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 10426 // C++ [class.dtor]p13: 10427 // ... as if for the expression 'delete this' appearing in a 10428 // non-virtual destructor of the destructor's class. 10429 ContextRAII SwitchContext(*this, Destructor); 10430 ExprResult This = 10431 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 10432 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 10433 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 10434 if (This.isInvalid()) { 10435 // FIXME: Register this as a context note so that it comes out 10436 // in the right order. 10437 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 10438 return true; 10439 } 10440 ThisArg = This.get(); 10441 } 10442 } 10443 10444 DiagnoseUseOfDecl(OperatorDelete, Loc); 10445 MarkFunctionReferenced(Loc, OperatorDelete); 10446 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 10447 } 10448 } 10449 10450 return false; 10451 } 10452 10453 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 10454 /// the well-formednes of the destructor declarator @p D with type @p 10455 /// R. If there are any errors in the declarator, this routine will 10456 /// emit diagnostics and set the declarator to invalid. Even if this happens, 10457 /// will be updated to reflect a well-formed type for the destructor and 10458 /// returned. 10459 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 10460 StorageClass& SC) { 10461 // C++ [class.dtor]p1: 10462 // [...] A typedef-name that names a class is a class-name 10463 // (7.1.3); however, a typedef-name that names a class shall not 10464 // be used as the identifier in the declarator for a destructor 10465 // declaration. 10466 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 10467 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 10468 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10469 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 10470 else if (const TemplateSpecializationType *TST = 10471 DeclaratorType->getAs<TemplateSpecializationType>()) 10472 if (TST->isTypeAlias()) 10473 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10474 << DeclaratorType << 1; 10475 10476 // C++ [class.dtor]p2: 10477 // A destructor is used to destroy objects of its class type. A 10478 // destructor takes no parameters, and no return type can be 10479 // specified for it (not even void). The address of a destructor 10480 // shall not be taken. A destructor shall not be static. A 10481 // destructor can be invoked for a const, volatile or const 10482 // volatile object. A destructor shall not be declared const, 10483 // volatile or const volatile (9.3.2). 10484 if (SC == SC_Static) { 10485 if (!D.isInvalidType()) 10486 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 10487 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10488 << SourceRange(D.getIdentifierLoc()) 10489 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10490 10491 SC = SC_None; 10492 } 10493 if (!D.isInvalidType()) { 10494 // Destructors don't have return types, but the parser will 10495 // happily parse something like: 10496 // 10497 // class X { 10498 // float ~X(); 10499 // }; 10500 // 10501 // The return type will be eliminated later. 10502 if (D.getDeclSpec().hasTypeSpecifier()) 10503 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 10504 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 10505 << SourceRange(D.getIdentifierLoc()); 10506 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10507 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 10508 SourceLocation(), 10509 D.getDeclSpec().getConstSpecLoc(), 10510 D.getDeclSpec().getVolatileSpecLoc(), 10511 D.getDeclSpec().getRestrictSpecLoc(), 10512 D.getDeclSpec().getAtomicSpecLoc()); 10513 D.setInvalidType(); 10514 } 10515 } 10516 10517 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 10518 10519 // C++0x [class.dtor]p2: 10520 // A destructor shall not be declared with a ref-qualifier. 10521 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10522 if (FTI.hasRefQualifier()) { 10523 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 10524 << FTI.RefQualifierIsLValueRef 10525 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10526 D.setInvalidType(); 10527 } 10528 10529 // Make sure we don't have any parameters. 10530 if (FTIHasNonVoidParameters(FTI)) { 10531 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 10532 10533 // Delete the parameters. 10534 FTI.freeParams(); 10535 D.setInvalidType(); 10536 } 10537 10538 // Make sure the destructor isn't variadic. 10539 if (FTI.isVariadic) { 10540 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10541 D.setInvalidType(); 10542 } 10543 10544 // Rebuild the function type "R" without any type qualifiers or 10545 // parameters (in case any of the errors above fired) and with 10546 // "void" as the return type, since destructors don't have return 10547 // types. 10548 if (!D.isInvalidType()) 10549 return R; 10550 10551 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10552 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10553 EPI.Variadic = false; 10554 EPI.TypeQuals = Qualifiers(); 10555 EPI.RefQualifier = RQ_None; 10556 return Context.getFunctionType(Context.VoidTy, None, EPI); 10557 } 10558 10559 static void extendLeft(SourceRange &R, SourceRange Before) { 10560 if (Before.isInvalid()) 10561 return; 10562 R.setBegin(Before.getBegin()); 10563 if (R.getEnd().isInvalid()) 10564 R.setEnd(Before.getEnd()); 10565 } 10566 10567 static void extendRight(SourceRange &R, SourceRange After) { 10568 if (After.isInvalid()) 10569 return; 10570 if (R.getBegin().isInvalid()) 10571 R.setBegin(After.getBegin()); 10572 R.setEnd(After.getEnd()); 10573 } 10574 10575 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10576 /// well-formednes of the conversion function declarator @p D with 10577 /// type @p R. If there are any errors in the declarator, this routine 10578 /// will emit diagnostics and return true. Otherwise, it will return 10579 /// false. Either way, the type @p R will be updated to reflect a 10580 /// well-formed type for the conversion operator. 10581 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10582 StorageClass& SC) { 10583 // C++ [class.conv.fct]p1: 10584 // Neither parameter types nor return type can be specified. The 10585 // type of a conversion function (8.3.5) is "function taking no 10586 // parameter returning conversion-type-id." 10587 if (SC == SC_Static) { 10588 if (!D.isInvalidType()) 10589 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10590 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10591 << D.getName().getSourceRange(); 10592 D.setInvalidType(); 10593 SC = SC_None; 10594 } 10595 10596 TypeSourceInfo *ConvTSI = nullptr; 10597 QualType ConvType = 10598 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10599 10600 const DeclSpec &DS = D.getDeclSpec(); 10601 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10602 // Conversion functions don't have return types, but the parser will 10603 // happily parse something like: 10604 // 10605 // class X { 10606 // float operator bool(); 10607 // }; 10608 // 10609 // The return type will be changed later anyway. 10610 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10611 << SourceRange(DS.getTypeSpecTypeLoc()) 10612 << SourceRange(D.getIdentifierLoc()); 10613 D.setInvalidType(); 10614 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10615 // It's also plausible that the user writes type qualifiers in the wrong 10616 // place, such as: 10617 // struct S { const operator int(); }; 10618 // FIXME: we could provide a fixit to move the qualifiers onto the 10619 // conversion type. 10620 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10621 << SourceRange(D.getIdentifierLoc()) << 0; 10622 D.setInvalidType(); 10623 } 10624 10625 const auto *Proto = R->castAs<FunctionProtoType>(); 10626 10627 // Make sure we don't have any parameters. 10628 if (Proto->getNumParams() > 0) { 10629 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10630 10631 // Delete the parameters. 10632 D.getFunctionTypeInfo().freeParams(); 10633 D.setInvalidType(); 10634 } else if (Proto->isVariadic()) { 10635 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10636 D.setInvalidType(); 10637 } 10638 10639 // Diagnose "&operator bool()" and other such nonsense. This 10640 // is actually a gcc extension which we don't support. 10641 if (Proto->getReturnType() != ConvType) { 10642 bool NeedsTypedef = false; 10643 SourceRange Before, After; 10644 10645 // Walk the chunks and extract information on them for our diagnostic. 10646 bool PastFunctionChunk = false; 10647 for (auto &Chunk : D.type_objects()) { 10648 switch (Chunk.Kind) { 10649 case DeclaratorChunk::Function: 10650 if (!PastFunctionChunk) { 10651 if (Chunk.Fun.HasTrailingReturnType) { 10652 TypeSourceInfo *TRT = nullptr; 10653 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10654 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10655 } 10656 PastFunctionChunk = true; 10657 break; 10658 } 10659 LLVM_FALLTHROUGH; 10660 case DeclaratorChunk::Array: 10661 NeedsTypedef = true; 10662 extendRight(After, Chunk.getSourceRange()); 10663 break; 10664 10665 case DeclaratorChunk::Pointer: 10666 case DeclaratorChunk::BlockPointer: 10667 case DeclaratorChunk::Reference: 10668 case DeclaratorChunk::MemberPointer: 10669 case DeclaratorChunk::Pipe: 10670 extendLeft(Before, Chunk.getSourceRange()); 10671 break; 10672 10673 case DeclaratorChunk::Paren: 10674 extendLeft(Before, Chunk.Loc); 10675 extendRight(After, Chunk.EndLoc); 10676 break; 10677 } 10678 } 10679 10680 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10681 After.isValid() ? After.getBegin() : 10682 D.getIdentifierLoc(); 10683 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10684 DB << Before << After; 10685 10686 if (!NeedsTypedef) { 10687 DB << /*don't need a typedef*/0; 10688 10689 // If we can provide a correct fix-it hint, do so. 10690 if (After.isInvalid() && ConvTSI) { 10691 SourceLocation InsertLoc = 10692 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10693 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10694 << FixItHint::CreateInsertionFromRange( 10695 InsertLoc, CharSourceRange::getTokenRange(Before)) 10696 << FixItHint::CreateRemoval(Before); 10697 } 10698 } else if (!Proto->getReturnType()->isDependentType()) { 10699 DB << /*typedef*/1 << Proto->getReturnType(); 10700 } else if (getLangOpts().CPlusPlus11) { 10701 DB << /*alias template*/2 << Proto->getReturnType(); 10702 } else { 10703 DB << /*might not be fixable*/3; 10704 } 10705 10706 // Recover by incorporating the other type chunks into the result type. 10707 // Note, this does *not* change the name of the function. This is compatible 10708 // with the GCC extension: 10709 // struct S { &operator int(); } s; 10710 // int &r = s.operator int(); // ok in GCC 10711 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10712 ConvType = Proto->getReturnType(); 10713 } 10714 10715 // C++ [class.conv.fct]p4: 10716 // The conversion-type-id shall not represent a function type nor 10717 // an array type. 10718 if (ConvType->isArrayType()) { 10719 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10720 ConvType = Context.getPointerType(ConvType); 10721 D.setInvalidType(); 10722 } else if (ConvType->isFunctionType()) { 10723 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10724 ConvType = Context.getPointerType(ConvType); 10725 D.setInvalidType(); 10726 } 10727 10728 // Rebuild the function type "R" without any parameters (in case any 10729 // of the errors above fired) and with the conversion type as the 10730 // return type. 10731 if (D.isInvalidType()) 10732 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 10733 10734 // C++0x explicit conversion operators. 10735 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20) 10736 Diag(DS.getExplicitSpecLoc(), 10737 getLangOpts().CPlusPlus11 10738 ? diag::warn_cxx98_compat_explicit_conversion_functions 10739 : diag::ext_explicit_conversion_functions) 10740 << SourceRange(DS.getExplicitSpecRange()); 10741 } 10742 10743 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 10744 /// the declaration of the given C++ conversion function. This routine 10745 /// is responsible for recording the conversion function in the C++ 10746 /// class, if possible. 10747 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 10748 assert(Conversion && "Expected to receive a conversion function declaration"); 10749 10750 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 10751 10752 // Make sure we aren't redeclaring the conversion function. 10753 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 10754 // C++ [class.conv.fct]p1: 10755 // [...] A conversion function is never used to convert a 10756 // (possibly cv-qualified) object to the (possibly cv-qualified) 10757 // same object type (or a reference to it), to a (possibly 10758 // cv-qualified) base class of that type (or a reference to it), 10759 // or to (possibly cv-qualified) void. 10760 QualType ClassType 10761 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10762 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 10763 ConvType = ConvTypeRef->getPointeeType(); 10764 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 10765 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 10766 /* Suppress diagnostics for instantiations. */; 10767 else if (Conversion->size_overridden_methods() != 0) 10768 /* Suppress diagnostics for overriding virtual function in a base class. */; 10769 else if (ConvType->isRecordType()) { 10770 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 10771 if (ConvType == ClassType) 10772 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 10773 << ClassType; 10774 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 10775 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 10776 << ClassType << ConvType; 10777 } else if (ConvType->isVoidType()) { 10778 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 10779 << ClassType << ConvType; 10780 } 10781 10782 if (FunctionTemplateDecl *ConversionTemplate 10783 = Conversion->getDescribedFunctionTemplate()) 10784 return ConversionTemplate; 10785 10786 return Conversion; 10787 } 10788 10789 namespace { 10790 /// Utility class to accumulate and print a diagnostic listing the invalid 10791 /// specifier(s) on a declaration. 10792 struct BadSpecifierDiagnoser { 10793 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10794 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10795 ~BadSpecifierDiagnoser() { 10796 Diagnostic << Specifiers; 10797 } 10798 10799 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10800 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10801 } 10802 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10803 return check(SpecLoc, 10804 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10805 } 10806 void check(SourceLocation SpecLoc, const char *Spec) { 10807 if (SpecLoc.isInvalid()) return; 10808 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10809 if (!Specifiers.empty()) Specifiers += " "; 10810 Specifiers += Spec; 10811 } 10812 10813 Sema &S; 10814 Sema::SemaDiagnosticBuilder Diagnostic; 10815 std::string Specifiers; 10816 }; 10817 } 10818 10819 /// Check the validity of a declarator that we parsed for a deduction-guide. 10820 /// These aren't actually declarators in the grammar, so we need to check that 10821 /// the user didn't specify any pieces that are not part of the deduction-guide 10822 /// grammar. 10823 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10824 StorageClass &SC) { 10825 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10826 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10827 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 10828 10829 // C++ [temp.deduct.guide]p3: 10830 // A deduction-gide shall be declared in the same scope as the 10831 // corresponding class template. 10832 if (!CurContext->getRedeclContext()->Equals( 10833 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10834 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10835 << GuidedTemplateDecl; 10836 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10837 } 10838 10839 auto &DS = D.getMutableDeclSpec(); 10840 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10841 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10842 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10843 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10844 BadSpecifierDiagnoser Diagnoser( 10845 *this, D.getIdentifierLoc(), 10846 diag::err_deduction_guide_invalid_specifier); 10847 10848 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10849 DS.ClearStorageClassSpecs(); 10850 SC = SC_None; 10851 10852 // 'explicit' is permitted. 10853 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10854 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10855 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10856 DS.ClearConstexprSpec(); 10857 10858 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10859 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10860 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10861 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10862 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10863 DS.ClearTypeQualifiers(); 10864 10865 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 10866 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 10867 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 10868 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 10869 DS.ClearTypeSpecType(); 10870 } 10871 10872 if (D.isInvalidType()) 10873 return; 10874 10875 // Check the declarator is simple enough. 10876 bool FoundFunction = false; 10877 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 10878 if (Chunk.Kind == DeclaratorChunk::Paren) 10879 continue; 10880 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 10881 Diag(D.getDeclSpec().getBeginLoc(), 10882 diag::err_deduction_guide_with_complex_decl) 10883 << D.getSourceRange(); 10884 break; 10885 } 10886 if (!Chunk.Fun.hasTrailingReturnType()) { 10887 Diag(D.getName().getBeginLoc(), 10888 diag::err_deduction_guide_no_trailing_return_type); 10889 break; 10890 } 10891 10892 // Check that the return type is written as a specialization of 10893 // the template specified as the deduction-guide's name. 10894 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 10895 TypeSourceInfo *TSI = nullptr; 10896 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 10897 assert(TSI && "deduction guide has valid type but invalid return type?"); 10898 bool AcceptableReturnType = false; 10899 bool MightInstantiateToSpecialization = false; 10900 if (auto RetTST = 10901 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 10902 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 10903 bool TemplateMatches = 10904 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 10905 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 10906 AcceptableReturnType = true; 10907 else { 10908 // This could still instantiate to the right type, unless we know it 10909 // names the wrong class template. 10910 auto *TD = SpecifiedName.getAsTemplateDecl(); 10911 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 10912 !TemplateMatches); 10913 } 10914 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 10915 MightInstantiateToSpecialization = true; 10916 } 10917 10918 if (!AcceptableReturnType) { 10919 Diag(TSI->getTypeLoc().getBeginLoc(), 10920 diag::err_deduction_guide_bad_trailing_return_type) 10921 << GuidedTemplate << TSI->getType() 10922 << MightInstantiateToSpecialization 10923 << TSI->getTypeLoc().getSourceRange(); 10924 } 10925 10926 // Keep going to check that we don't have any inner declarator pieces (we 10927 // could still have a function returning a pointer to a function). 10928 FoundFunction = true; 10929 } 10930 10931 if (D.isFunctionDefinition()) 10932 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 10933 } 10934 10935 //===----------------------------------------------------------------------===// 10936 // Namespace Handling 10937 //===----------------------------------------------------------------------===// 10938 10939 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 10940 /// reopened. 10941 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 10942 SourceLocation Loc, 10943 IdentifierInfo *II, bool *IsInline, 10944 NamespaceDecl *PrevNS) { 10945 assert(*IsInline != PrevNS->isInline()); 10946 10947 if (PrevNS->isInline()) 10948 // The user probably just forgot the 'inline', so suggest that it 10949 // be added back. 10950 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 10951 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 10952 else 10953 S.Diag(Loc, diag::err_inline_namespace_mismatch); 10954 10955 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 10956 *IsInline = PrevNS->isInline(); 10957 } 10958 10959 /// ActOnStartNamespaceDef - This is called at the start of a namespace 10960 /// definition. 10961 Decl *Sema::ActOnStartNamespaceDef( 10962 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 10963 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 10964 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 10965 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 10966 // For anonymous namespace, take the location of the left brace. 10967 SourceLocation Loc = II ? IdentLoc : LBrace; 10968 bool IsInline = InlineLoc.isValid(); 10969 bool IsInvalid = false; 10970 bool IsStd = false; 10971 bool AddToKnown = false; 10972 Scope *DeclRegionScope = NamespcScope->getParent(); 10973 10974 NamespaceDecl *PrevNS = nullptr; 10975 if (II) { 10976 // C++ [namespace.def]p2: 10977 // The identifier in an original-namespace-definition shall not 10978 // have been previously defined in the declarative region in 10979 // which the original-namespace-definition appears. The 10980 // identifier in an original-namespace-definition is the name of 10981 // the namespace. Subsequently in that declarative region, it is 10982 // treated as an original-namespace-name. 10983 // 10984 // Since namespace names are unique in their scope, and we don't 10985 // look through using directives, just look for any ordinary names 10986 // as if by qualified name lookup. 10987 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 10988 ForExternalRedeclaration); 10989 LookupQualifiedName(R, CurContext->getRedeclContext()); 10990 NamedDecl *PrevDecl = 10991 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 10992 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 10993 10994 if (PrevNS) { 10995 // This is an extended namespace definition. 10996 if (IsInline != PrevNS->isInline()) 10997 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 10998 &IsInline, PrevNS); 10999 } else if (PrevDecl) { 11000 // This is an invalid name redefinition. 11001 Diag(Loc, diag::err_redefinition_different_kind) 11002 << II; 11003 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11004 IsInvalid = true; 11005 // Continue on to push Namespc as current DeclContext and return it. 11006 } else if (II->isStr("std") && 11007 CurContext->getRedeclContext()->isTranslationUnit()) { 11008 // This is the first "real" definition of the namespace "std", so update 11009 // our cache of the "std" namespace to point at this definition. 11010 PrevNS = getStdNamespace(); 11011 IsStd = true; 11012 AddToKnown = !IsInline; 11013 } else { 11014 // We've seen this namespace for the first time. 11015 AddToKnown = !IsInline; 11016 } 11017 } else { 11018 // Anonymous namespaces. 11019 11020 // Determine whether the parent already has an anonymous namespace. 11021 DeclContext *Parent = CurContext->getRedeclContext(); 11022 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11023 PrevNS = TU->getAnonymousNamespace(); 11024 } else { 11025 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 11026 PrevNS = ND->getAnonymousNamespace(); 11027 } 11028 11029 if (PrevNS && IsInline != PrevNS->isInline()) 11030 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 11031 &IsInline, PrevNS); 11032 } 11033 11034 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 11035 StartLoc, Loc, II, PrevNS); 11036 if (IsInvalid) 11037 Namespc->setInvalidDecl(); 11038 11039 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 11040 AddPragmaAttributes(DeclRegionScope, Namespc); 11041 11042 // FIXME: Should we be merging attributes? 11043 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 11044 PushNamespaceVisibilityAttr(Attr, Loc); 11045 11046 if (IsStd) 11047 StdNamespace = Namespc; 11048 if (AddToKnown) 11049 KnownNamespaces[Namespc] = false; 11050 11051 if (II) { 11052 PushOnScopeChains(Namespc, DeclRegionScope); 11053 } else { 11054 // Link the anonymous namespace into its parent. 11055 DeclContext *Parent = CurContext->getRedeclContext(); 11056 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11057 TU->setAnonymousNamespace(Namespc); 11058 } else { 11059 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 11060 } 11061 11062 CurContext->addDecl(Namespc); 11063 11064 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 11065 // behaves as if it were replaced by 11066 // namespace unique { /* empty body */ } 11067 // using namespace unique; 11068 // namespace unique { namespace-body } 11069 // where all occurrences of 'unique' in a translation unit are 11070 // replaced by the same identifier and this identifier differs 11071 // from all other identifiers in the entire program. 11072 11073 // We just create the namespace with an empty name and then add an 11074 // implicit using declaration, just like the standard suggests. 11075 // 11076 // CodeGen enforces the "universally unique" aspect by giving all 11077 // declarations semantically contained within an anonymous 11078 // namespace internal linkage. 11079 11080 if (!PrevNS) { 11081 UD = UsingDirectiveDecl::Create(Context, Parent, 11082 /* 'using' */ LBrace, 11083 /* 'namespace' */ SourceLocation(), 11084 /* qualifier */ NestedNameSpecifierLoc(), 11085 /* identifier */ SourceLocation(), 11086 Namespc, 11087 /* Ancestor */ Parent); 11088 UD->setImplicit(); 11089 Parent->addDecl(UD); 11090 } 11091 } 11092 11093 ActOnDocumentableDecl(Namespc); 11094 11095 // Although we could have an invalid decl (i.e. the namespace name is a 11096 // redefinition), push it as current DeclContext and try to continue parsing. 11097 // FIXME: We should be able to push Namespc here, so that the each DeclContext 11098 // for the namespace has the declarations that showed up in that particular 11099 // namespace definition. 11100 PushDeclContext(NamespcScope, Namespc); 11101 return Namespc; 11102 } 11103 11104 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 11105 /// is a namespace alias, returns the namespace it points to. 11106 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 11107 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 11108 return AD->getNamespace(); 11109 return dyn_cast_or_null<NamespaceDecl>(D); 11110 } 11111 11112 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 11113 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 11114 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 11115 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 11116 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 11117 Namespc->setRBraceLoc(RBrace); 11118 PopDeclContext(); 11119 if (Namespc->hasAttr<VisibilityAttr>()) 11120 PopPragmaVisibility(true, RBrace); 11121 // If this namespace contains an export-declaration, export it now. 11122 if (DeferredExportedNamespaces.erase(Namespc)) 11123 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 11124 } 11125 11126 CXXRecordDecl *Sema::getStdBadAlloc() const { 11127 return cast_or_null<CXXRecordDecl>( 11128 StdBadAlloc.get(Context.getExternalSource())); 11129 } 11130 11131 EnumDecl *Sema::getStdAlignValT() const { 11132 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 11133 } 11134 11135 NamespaceDecl *Sema::getStdNamespace() const { 11136 return cast_or_null<NamespaceDecl>( 11137 StdNamespace.get(Context.getExternalSource())); 11138 } 11139 11140 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 11141 if (!StdExperimentalNamespaceCache) { 11142 if (auto Std = getStdNamespace()) { 11143 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 11144 SourceLocation(), LookupNamespaceName); 11145 if (!LookupQualifiedName(Result, Std) || 11146 !(StdExperimentalNamespaceCache = 11147 Result.getAsSingle<NamespaceDecl>())) 11148 Result.suppressDiagnostics(); 11149 } 11150 } 11151 return StdExperimentalNamespaceCache; 11152 } 11153 11154 namespace { 11155 11156 enum UnsupportedSTLSelect { 11157 USS_InvalidMember, 11158 USS_MissingMember, 11159 USS_NonTrivial, 11160 USS_Other 11161 }; 11162 11163 struct InvalidSTLDiagnoser { 11164 Sema &S; 11165 SourceLocation Loc; 11166 QualType TyForDiags; 11167 11168 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 11169 const VarDecl *VD = nullptr) { 11170 { 11171 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 11172 << TyForDiags << ((int)Sel); 11173 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 11174 assert(!Name.empty()); 11175 D << Name; 11176 } 11177 } 11178 if (Sel == USS_InvalidMember) { 11179 S.Diag(VD->getLocation(), diag::note_var_declared_here) 11180 << VD << VD->getSourceRange(); 11181 } 11182 return QualType(); 11183 } 11184 }; 11185 } // namespace 11186 11187 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 11188 SourceLocation Loc, 11189 ComparisonCategoryUsage Usage) { 11190 assert(getLangOpts().CPlusPlus && 11191 "Looking for comparison category type outside of C++."); 11192 11193 // Use an elaborated type for diagnostics which has a name containing the 11194 // prepended 'std' namespace but not any inline namespace names. 11195 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 11196 auto *NNS = 11197 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 11198 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 11199 }; 11200 11201 // Check if we've already successfully checked the comparison category type 11202 // before. If so, skip checking it again. 11203 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 11204 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 11205 // The only thing we need to check is that the type has a reachable 11206 // definition in the current context. 11207 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11208 return QualType(); 11209 11210 return Info->getType(); 11211 } 11212 11213 // If lookup failed 11214 if (!Info) { 11215 std::string NameForDiags = "std::"; 11216 NameForDiags += ComparisonCategories::getCategoryString(Kind); 11217 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 11218 << NameForDiags << (int)Usage; 11219 return QualType(); 11220 } 11221 11222 assert(Info->Kind == Kind); 11223 assert(Info->Record); 11224 11225 // Update the Record decl in case we encountered a forward declaration on our 11226 // first pass. FIXME: This is a bit of a hack. 11227 if (Info->Record->hasDefinition()) 11228 Info->Record = Info->Record->getDefinition(); 11229 11230 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11231 return QualType(); 11232 11233 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 11234 11235 if (!Info->Record->isTriviallyCopyable()) 11236 return UnsupportedSTLError(USS_NonTrivial); 11237 11238 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 11239 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 11240 // Tolerate empty base classes. 11241 if (Base->isEmpty()) 11242 continue; 11243 // Reject STL implementations which have at least one non-empty base. 11244 return UnsupportedSTLError(); 11245 } 11246 11247 // Check that the STL has implemented the types using a single integer field. 11248 // This expectation allows better codegen for builtin operators. We require: 11249 // (1) The class has exactly one field. 11250 // (2) The field is an integral or enumeration type. 11251 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 11252 if (std::distance(FIt, FEnd) != 1 || 11253 !FIt->getType()->isIntegralOrEnumerationType()) { 11254 return UnsupportedSTLError(); 11255 } 11256 11257 // Build each of the require values and store them in Info. 11258 for (ComparisonCategoryResult CCR : 11259 ComparisonCategories::getPossibleResultsForType(Kind)) { 11260 StringRef MemName = ComparisonCategories::getResultString(CCR); 11261 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 11262 11263 if (!ValInfo) 11264 return UnsupportedSTLError(USS_MissingMember, MemName); 11265 11266 VarDecl *VD = ValInfo->VD; 11267 assert(VD && "should not be null!"); 11268 11269 // Attempt to diagnose reasons why the STL definition of this type 11270 // might be foobar, including it failing to be a constant expression. 11271 // TODO Handle more ways the lookup or result can be invalid. 11272 if (!VD->isStaticDataMember() || 11273 !VD->isUsableInConstantExpressions(Context)) 11274 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 11275 11276 // Attempt to evaluate the var decl as a constant expression and extract 11277 // the value of its first field as a ICE. If this fails, the STL 11278 // implementation is not supported. 11279 if (!ValInfo->hasValidIntValue()) 11280 return UnsupportedSTLError(); 11281 11282 MarkVariableReferenced(Loc, VD); 11283 } 11284 11285 // We've successfully built the required types and expressions. Update 11286 // the cache and return the newly cached value. 11287 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 11288 return Info->getType(); 11289 } 11290 11291 /// Retrieve the special "std" namespace, which may require us to 11292 /// implicitly define the namespace. 11293 NamespaceDecl *Sema::getOrCreateStdNamespace() { 11294 if (!StdNamespace) { 11295 // The "std" namespace has not yet been defined, so build one implicitly. 11296 StdNamespace = NamespaceDecl::Create(Context, 11297 Context.getTranslationUnitDecl(), 11298 /*Inline=*/false, 11299 SourceLocation(), SourceLocation(), 11300 &PP.getIdentifierTable().get("std"), 11301 /*PrevDecl=*/nullptr); 11302 getStdNamespace()->setImplicit(true); 11303 } 11304 11305 return getStdNamespace(); 11306 } 11307 11308 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 11309 assert(getLangOpts().CPlusPlus && 11310 "Looking for std::initializer_list outside of C++."); 11311 11312 // We're looking for implicit instantiations of 11313 // template <typename E> class std::initializer_list. 11314 11315 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 11316 return false; 11317 11318 ClassTemplateDecl *Template = nullptr; 11319 const TemplateArgument *Arguments = nullptr; 11320 11321 if (const RecordType *RT = Ty->getAs<RecordType>()) { 11322 11323 ClassTemplateSpecializationDecl *Specialization = 11324 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 11325 if (!Specialization) 11326 return false; 11327 11328 Template = Specialization->getSpecializedTemplate(); 11329 Arguments = Specialization->getTemplateArgs().data(); 11330 } else if (const TemplateSpecializationType *TST = 11331 Ty->getAs<TemplateSpecializationType>()) { 11332 Template = dyn_cast_or_null<ClassTemplateDecl>( 11333 TST->getTemplateName().getAsTemplateDecl()); 11334 Arguments = TST->getArgs(); 11335 } 11336 if (!Template) 11337 return false; 11338 11339 if (!StdInitializerList) { 11340 // Haven't recognized std::initializer_list yet, maybe this is it. 11341 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 11342 if (TemplateClass->getIdentifier() != 11343 &PP.getIdentifierTable().get("initializer_list") || 11344 !getStdNamespace()->InEnclosingNamespaceSetOf( 11345 TemplateClass->getDeclContext())) 11346 return false; 11347 // This is a template called std::initializer_list, but is it the right 11348 // template? 11349 TemplateParameterList *Params = Template->getTemplateParameters(); 11350 if (Params->getMinRequiredArguments() != 1) 11351 return false; 11352 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 11353 return false; 11354 11355 // It's the right template. 11356 StdInitializerList = Template; 11357 } 11358 11359 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 11360 return false; 11361 11362 // This is an instance of std::initializer_list. Find the argument type. 11363 if (Element) 11364 *Element = Arguments[0].getAsType(); 11365 return true; 11366 } 11367 11368 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 11369 NamespaceDecl *Std = S.getStdNamespace(); 11370 if (!Std) { 11371 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11372 return nullptr; 11373 } 11374 11375 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 11376 Loc, Sema::LookupOrdinaryName); 11377 if (!S.LookupQualifiedName(Result, Std)) { 11378 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11379 return nullptr; 11380 } 11381 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 11382 if (!Template) { 11383 Result.suppressDiagnostics(); 11384 // We found something weird. Complain about the first thing we found. 11385 NamedDecl *Found = *Result.begin(); 11386 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 11387 return nullptr; 11388 } 11389 11390 // We found some template called std::initializer_list. Now verify that it's 11391 // correct. 11392 TemplateParameterList *Params = Template->getTemplateParameters(); 11393 if (Params->getMinRequiredArguments() != 1 || 11394 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 11395 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 11396 return nullptr; 11397 } 11398 11399 return Template; 11400 } 11401 11402 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 11403 if (!StdInitializerList) { 11404 StdInitializerList = LookupStdInitializerList(*this, Loc); 11405 if (!StdInitializerList) 11406 return QualType(); 11407 } 11408 11409 TemplateArgumentListInfo Args(Loc, Loc); 11410 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 11411 Context.getTrivialTypeSourceInfo(Element, 11412 Loc))); 11413 return Context.getCanonicalType( 11414 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 11415 } 11416 11417 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 11418 // C++ [dcl.init.list]p2: 11419 // A constructor is an initializer-list constructor if its first parameter 11420 // is of type std::initializer_list<E> or reference to possibly cv-qualified 11421 // std::initializer_list<E> for some type E, and either there are no other 11422 // parameters or else all other parameters have default arguments. 11423 if (!Ctor->hasOneParamOrDefaultArgs()) 11424 return false; 11425 11426 QualType ArgType = Ctor->getParamDecl(0)->getType(); 11427 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 11428 ArgType = RT->getPointeeType().getUnqualifiedType(); 11429 11430 return isStdInitializerList(ArgType, nullptr); 11431 } 11432 11433 /// Determine whether a using statement is in a context where it will be 11434 /// apply in all contexts. 11435 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 11436 switch (CurContext->getDeclKind()) { 11437 case Decl::TranslationUnit: 11438 return true; 11439 case Decl::LinkageSpec: 11440 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 11441 default: 11442 return false; 11443 } 11444 } 11445 11446 namespace { 11447 11448 // Callback to only accept typo corrections that are namespaces. 11449 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 11450 public: 11451 bool ValidateCandidate(const TypoCorrection &candidate) override { 11452 if (NamedDecl *ND = candidate.getCorrectionDecl()) 11453 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 11454 return false; 11455 } 11456 11457 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11458 return std::make_unique<NamespaceValidatorCCC>(*this); 11459 } 11460 }; 11461 11462 } 11463 11464 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 11465 CXXScopeSpec &SS, 11466 SourceLocation IdentLoc, 11467 IdentifierInfo *Ident) { 11468 R.clear(); 11469 NamespaceValidatorCCC CCC{}; 11470 if (TypoCorrection Corrected = 11471 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 11472 Sema::CTK_ErrorRecovery)) { 11473 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 11474 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 11475 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 11476 Ident->getName().equals(CorrectedStr); 11477 S.diagnoseTypo(Corrected, 11478 S.PDiag(diag::err_using_directive_member_suggest) 11479 << Ident << DC << DroppedSpecifier << SS.getRange(), 11480 S.PDiag(diag::note_namespace_defined_here)); 11481 } else { 11482 S.diagnoseTypo(Corrected, 11483 S.PDiag(diag::err_using_directive_suggest) << Ident, 11484 S.PDiag(diag::note_namespace_defined_here)); 11485 } 11486 R.addDecl(Corrected.getFoundDecl()); 11487 return true; 11488 } 11489 return false; 11490 } 11491 11492 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 11493 SourceLocation NamespcLoc, CXXScopeSpec &SS, 11494 SourceLocation IdentLoc, 11495 IdentifierInfo *NamespcName, 11496 const ParsedAttributesView &AttrList) { 11497 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11498 assert(NamespcName && "Invalid NamespcName."); 11499 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 11500 11501 // This can only happen along a recovery path. 11502 while (S->isTemplateParamScope()) 11503 S = S->getParent(); 11504 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11505 11506 UsingDirectiveDecl *UDir = nullptr; 11507 NestedNameSpecifier *Qualifier = nullptr; 11508 if (SS.isSet()) 11509 Qualifier = SS.getScopeRep(); 11510 11511 // Lookup namespace name. 11512 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 11513 LookupParsedName(R, S, &SS); 11514 if (R.isAmbiguous()) 11515 return nullptr; 11516 11517 if (R.empty()) { 11518 R.clear(); 11519 // Allow "using namespace std;" or "using namespace ::std;" even if 11520 // "std" hasn't been defined yet, for GCC compatibility. 11521 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11522 NamespcName->isStr("std")) { 11523 Diag(IdentLoc, diag::ext_using_undefined_std); 11524 R.addDecl(getOrCreateStdNamespace()); 11525 R.resolveKind(); 11526 } 11527 // Otherwise, attempt typo correction. 11528 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11529 } 11530 11531 if (!R.empty()) { 11532 NamedDecl *Named = R.getRepresentativeDecl(); 11533 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11534 assert(NS && "expected namespace decl"); 11535 11536 // The use of a nested name specifier may trigger deprecation warnings. 11537 DiagnoseUseOfDecl(Named, IdentLoc); 11538 11539 // C++ [namespace.udir]p1: 11540 // A using-directive specifies that the names in the nominated 11541 // namespace can be used in the scope in which the 11542 // using-directive appears after the using-directive. During 11543 // unqualified name lookup (3.4.1), the names appear as if they 11544 // were declared in the nearest enclosing namespace which 11545 // contains both the using-directive and the nominated 11546 // namespace. [Note: in this context, "contains" means "contains 11547 // directly or indirectly". ] 11548 11549 // Find enclosing context containing both using-directive and 11550 // nominated namespace. 11551 DeclContext *CommonAncestor = NS; 11552 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11553 CommonAncestor = CommonAncestor->getParent(); 11554 11555 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11556 SS.getWithLocInContext(Context), 11557 IdentLoc, Named, CommonAncestor); 11558 11559 if (IsUsingDirectiveInToplevelContext(CurContext) && 11560 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11561 Diag(IdentLoc, diag::warn_using_directive_in_header); 11562 } 11563 11564 PushUsingDirective(S, UDir); 11565 } else { 11566 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11567 } 11568 11569 if (UDir) 11570 ProcessDeclAttributeList(S, UDir, AttrList); 11571 11572 return UDir; 11573 } 11574 11575 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11576 // If the scope has an associated entity and the using directive is at 11577 // namespace or translation unit scope, add the UsingDirectiveDecl into 11578 // its lookup structure so qualified name lookup can find it. 11579 DeclContext *Ctx = S->getEntity(); 11580 if (Ctx && !Ctx->isFunctionOrMethod()) 11581 Ctx->addDecl(UDir); 11582 else 11583 // Otherwise, it is at block scope. The using-directives will affect lookup 11584 // only to the end of the scope. 11585 S->PushUsingDirective(UDir); 11586 } 11587 11588 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11589 SourceLocation UsingLoc, 11590 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11591 UnqualifiedId &Name, 11592 SourceLocation EllipsisLoc, 11593 const ParsedAttributesView &AttrList) { 11594 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11595 11596 if (SS.isEmpty()) { 11597 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11598 return nullptr; 11599 } 11600 11601 switch (Name.getKind()) { 11602 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11603 case UnqualifiedIdKind::IK_Identifier: 11604 case UnqualifiedIdKind::IK_OperatorFunctionId: 11605 case UnqualifiedIdKind::IK_LiteralOperatorId: 11606 case UnqualifiedIdKind::IK_ConversionFunctionId: 11607 break; 11608 11609 case UnqualifiedIdKind::IK_ConstructorName: 11610 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11611 // C++11 inheriting constructors. 11612 Diag(Name.getBeginLoc(), 11613 getLangOpts().CPlusPlus11 11614 ? diag::warn_cxx98_compat_using_decl_constructor 11615 : diag::err_using_decl_constructor) 11616 << SS.getRange(); 11617 11618 if (getLangOpts().CPlusPlus11) break; 11619 11620 return nullptr; 11621 11622 case UnqualifiedIdKind::IK_DestructorName: 11623 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11624 return nullptr; 11625 11626 case UnqualifiedIdKind::IK_TemplateId: 11627 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11628 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11629 return nullptr; 11630 11631 case UnqualifiedIdKind::IK_DeductionGuideName: 11632 llvm_unreachable("cannot parse qualified deduction guide name"); 11633 } 11634 11635 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11636 DeclarationName TargetName = TargetNameInfo.getName(); 11637 if (!TargetName) 11638 return nullptr; 11639 11640 // Warn about access declarations. 11641 if (UsingLoc.isInvalid()) { 11642 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11643 ? diag::err_access_decl 11644 : diag::warn_access_decl_deprecated) 11645 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11646 } 11647 11648 if (EllipsisLoc.isInvalid()) { 11649 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11650 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11651 return nullptr; 11652 } else { 11653 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11654 !TargetNameInfo.containsUnexpandedParameterPack()) { 11655 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11656 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11657 EllipsisLoc = SourceLocation(); 11658 } 11659 } 11660 11661 NamedDecl *UD = 11662 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 11663 SS, TargetNameInfo, EllipsisLoc, AttrList, 11664 /*IsInstantiation*/ false, 11665 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists)); 11666 if (UD) 11667 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11668 11669 return UD; 11670 } 11671 11672 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 11673 SourceLocation UsingLoc, 11674 SourceLocation EnumLoc, 11675 const DeclSpec &DS) { 11676 switch (DS.getTypeSpecType()) { 11677 case DeclSpec::TST_error: 11678 // This will already have been diagnosed 11679 return nullptr; 11680 11681 case DeclSpec::TST_enum: 11682 break; 11683 11684 case DeclSpec::TST_typename: 11685 Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent); 11686 return nullptr; 11687 11688 default: 11689 llvm_unreachable("unexpected DeclSpec type"); 11690 } 11691 11692 // As with enum-decls, we ignore attributes for now. 11693 auto *Enum = cast<EnumDecl>(DS.getRepAsDecl()); 11694 if (auto *Def = Enum->getDefinition()) 11695 Enum = Def; 11696 11697 auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, 11698 DS.getTypeSpecTypeNameLoc(), Enum); 11699 if (UD) 11700 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11701 11702 return UD; 11703 } 11704 11705 /// Determine whether a using declaration considers the given 11706 /// declarations as "equivalent", e.g., if they are redeclarations of 11707 /// the same entity or are both typedefs of the same type. 11708 static bool 11709 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11710 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11711 return true; 11712 11713 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11714 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11715 return Context.hasSameType(TD1->getUnderlyingType(), 11716 TD2->getUnderlyingType()); 11717 11718 // Two using_if_exists using-declarations are equivalent if both are 11719 // unresolved. 11720 if (isa<UnresolvedUsingIfExistsDecl>(D1) && 11721 isa<UnresolvedUsingIfExistsDecl>(D2)) 11722 return true; 11723 11724 return false; 11725 } 11726 11727 11728 /// Determines whether to create a using shadow decl for a particular 11729 /// decl, given the set of decls existing prior to this using lookup. 11730 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig, 11731 const LookupResult &Previous, 11732 UsingShadowDecl *&PrevShadow) { 11733 // Diagnose finding a decl which is not from a base class of the 11734 // current class. We do this now because there are cases where this 11735 // function will silently decide not to build a shadow decl, which 11736 // will pre-empt further diagnostics. 11737 // 11738 // We don't need to do this in C++11 because we do the check once on 11739 // the qualifier. 11740 // 11741 // FIXME: diagnose the following if we care enough: 11742 // struct A { int foo; }; 11743 // struct B : A { using A::foo; }; 11744 // template <class T> struct C : A {}; 11745 // template <class T> struct D : C<T> { using B::foo; } // <--- 11746 // This is invalid (during instantiation) in C++03 because B::foo 11747 // resolves to the using decl in B, which is not a base class of D<T>. 11748 // We can't diagnose it immediately because C<T> is an unknown 11749 // specialization. The UsingShadowDecl in D<T> then points directly 11750 // to A::foo, which will look well-formed when we instantiate. 11751 // The right solution is to not collapse the shadow-decl chain. 11752 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) 11753 if (auto *Using = dyn_cast<UsingDecl>(BUD)) { 11754 DeclContext *OrigDC = Orig->getDeclContext(); 11755 11756 // Handle enums and anonymous structs. 11757 if (isa<EnumDecl>(OrigDC)) 11758 OrigDC = OrigDC->getParent(); 11759 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 11760 while (OrigRec->isAnonymousStructOrUnion()) 11761 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 11762 11763 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 11764 if (OrigDC == CurContext) { 11765 Diag(Using->getLocation(), 11766 diag::err_using_decl_nested_name_specifier_is_current_class) 11767 << Using->getQualifierLoc().getSourceRange(); 11768 Diag(Orig->getLocation(), diag::note_using_decl_target); 11769 Using->setInvalidDecl(); 11770 return true; 11771 } 11772 11773 Diag(Using->getQualifierLoc().getBeginLoc(), 11774 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11775 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext) 11776 << Using->getQualifierLoc().getSourceRange(); 11777 Diag(Orig->getLocation(), diag::note_using_decl_target); 11778 Using->setInvalidDecl(); 11779 return true; 11780 } 11781 } 11782 11783 if (Previous.empty()) return false; 11784 11785 NamedDecl *Target = Orig; 11786 if (isa<UsingShadowDecl>(Target)) 11787 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11788 11789 // If the target happens to be one of the previous declarations, we 11790 // don't have a conflict. 11791 // 11792 // FIXME: but we might be increasing its access, in which case we 11793 // should redeclare it. 11794 NamedDecl *NonTag = nullptr, *Tag = nullptr; 11795 bool FoundEquivalentDecl = false; 11796 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 11797 I != E; ++I) { 11798 NamedDecl *D = (*I)->getUnderlyingDecl(); 11799 // We can have UsingDecls in our Previous results because we use the same 11800 // LookupResult for checking whether the UsingDecl itself is a valid 11801 // redeclaration. 11802 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D)) 11803 continue; 11804 11805 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 11806 // C++ [class.mem]p19: 11807 // If T is the name of a class, then [every named member other than 11808 // a non-static data member] shall have a name different from T 11809 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11810 !isa<IndirectFieldDecl>(Target) && 11811 !isa<UnresolvedUsingValueDecl>(Target) && 11812 DiagnoseClassNameShadow( 11813 CurContext, 11814 DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation()))) 11815 return true; 11816 } 11817 11818 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11819 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11820 PrevShadow = Shadow; 11821 FoundEquivalentDecl = true; 11822 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11823 // We don't conflict with an existing using shadow decl of an equivalent 11824 // declaration, but we're not a redeclaration of it. 11825 FoundEquivalentDecl = true; 11826 } 11827 11828 if (isVisible(D)) 11829 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11830 } 11831 11832 if (FoundEquivalentDecl) 11833 return false; 11834 11835 // Always emit a diagnostic for a mismatch between an unresolved 11836 // using_if_exists and a resolved using declaration in either direction. 11837 if (isa<UnresolvedUsingIfExistsDecl>(Target) != 11838 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) { 11839 if (!NonTag && !Tag) 11840 return false; 11841 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11842 Diag(Target->getLocation(), diag::note_using_decl_target); 11843 Diag((NonTag ? NonTag : Tag)->getLocation(), 11844 diag::note_using_decl_conflict); 11845 BUD->setInvalidDecl(); 11846 return true; 11847 } 11848 11849 if (FunctionDecl *FD = Target->getAsFunction()) { 11850 NamedDecl *OldDecl = nullptr; 11851 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11852 /*IsForUsingDecl*/ true)) { 11853 case Ovl_Overload: 11854 return false; 11855 11856 case Ovl_NonFunction: 11857 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11858 break; 11859 11860 // We found a decl with the exact signature. 11861 case Ovl_Match: 11862 // If we're in a record, we want to hide the target, so we 11863 // return true (without a diagnostic) to tell the caller not to 11864 // build a shadow decl. 11865 if (CurContext->isRecord()) 11866 return true; 11867 11868 // If we're not in a record, this is an error. 11869 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11870 break; 11871 } 11872 11873 Diag(Target->getLocation(), diag::note_using_decl_target); 11874 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 11875 BUD->setInvalidDecl(); 11876 return true; 11877 } 11878 11879 // Target is not a function. 11880 11881 if (isa<TagDecl>(Target)) { 11882 // No conflict between a tag and a non-tag. 11883 if (!Tag) return false; 11884 11885 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11886 Diag(Target->getLocation(), diag::note_using_decl_target); 11887 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 11888 BUD->setInvalidDecl(); 11889 return true; 11890 } 11891 11892 // No conflict between a tag and a non-tag. 11893 if (!NonTag) return false; 11894 11895 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11896 Diag(Target->getLocation(), diag::note_using_decl_target); 11897 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 11898 BUD->setInvalidDecl(); 11899 return true; 11900 } 11901 11902 /// Determine whether a direct base class is a virtual base class. 11903 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 11904 if (!Derived->getNumVBases()) 11905 return false; 11906 for (auto &B : Derived->bases()) 11907 if (B.getType()->getAsCXXRecordDecl() == Base) 11908 return B.isVirtual(); 11909 llvm_unreachable("not a direct base class"); 11910 } 11911 11912 /// Builds a shadow declaration corresponding to a 'using' declaration. 11913 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, 11914 NamedDecl *Orig, 11915 UsingShadowDecl *PrevDecl) { 11916 // If we resolved to another shadow declaration, just coalesce them. 11917 NamedDecl *Target = Orig; 11918 if (isa<UsingShadowDecl>(Target)) { 11919 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11920 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 11921 } 11922 11923 NamedDecl *NonTemplateTarget = Target; 11924 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 11925 NonTemplateTarget = TargetTD->getTemplatedDecl(); 11926 11927 UsingShadowDecl *Shadow; 11928 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 11929 UsingDecl *Using = cast<UsingDecl>(BUD); 11930 bool IsVirtualBase = 11931 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 11932 Using->getQualifier()->getAsRecordDecl()); 11933 Shadow = ConstructorUsingShadowDecl::Create( 11934 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase); 11935 } else { 11936 Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(), 11937 Target->getDeclName(), BUD, Target); 11938 } 11939 BUD->addShadowDecl(Shadow); 11940 11941 Shadow->setAccess(BUD->getAccess()); 11942 if (Orig->isInvalidDecl() || BUD->isInvalidDecl()) 11943 Shadow->setInvalidDecl(); 11944 11945 Shadow->setPreviousDecl(PrevDecl); 11946 11947 if (S) 11948 PushOnScopeChains(Shadow, S); 11949 else 11950 CurContext->addDecl(Shadow); 11951 11952 11953 return Shadow; 11954 } 11955 11956 /// Hides a using shadow declaration. This is required by the current 11957 /// using-decl implementation when a resolvable using declaration in a 11958 /// class is followed by a declaration which would hide or override 11959 /// one or more of the using decl's targets; for example: 11960 /// 11961 /// struct Base { void foo(int); }; 11962 /// struct Derived : Base { 11963 /// using Base::foo; 11964 /// void foo(int); 11965 /// }; 11966 /// 11967 /// The governing language is C++03 [namespace.udecl]p12: 11968 /// 11969 /// When a using-declaration brings names from a base class into a 11970 /// derived class scope, member functions in the derived class 11971 /// override and/or hide member functions with the same name and 11972 /// parameter types in a base class (rather than conflicting). 11973 /// 11974 /// There are two ways to implement this: 11975 /// (1) optimistically create shadow decls when they're not hidden 11976 /// by existing declarations, or 11977 /// (2) don't create any shadow decls (or at least don't make them 11978 /// visible) until we've fully parsed/instantiated the class. 11979 /// The problem with (1) is that we might have to retroactively remove 11980 /// a shadow decl, which requires several O(n) operations because the 11981 /// decl structures are (very reasonably) not designed for removal. 11982 /// (2) avoids this but is very fiddly and phase-dependent. 11983 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 11984 if (Shadow->getDeclName().getNameKind() == 11985 DeclarationName::CXXConversionFunctionName) 11986 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 11987 11988 // Remove it from the DeclContext... 11989 Shadow->getDeclContext()->removeDecl(Shadow); 11990 11991 // ...and the scope, if applicable... 11992 if (S) { 11993 S->RemoveDecl(Shadow); 11994 IdResolver.RemoveDecl(Shadow); 11995 } 11996 11997 // ...and the using decl. 11998 Shadow->getIntroducer()->removeShadowDecl(Shadow); 11999 12000 // TODO: complain somehow if Shadow was used. It shouldn't 12001 // be possible for this to happen, because...? 12002 } 12003 12004 /// Find the base specifier for a base class with the given type. 12005 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 12006 QualType DesiredBase, 12007 bool &AnyDependentBases) { 12008 // Check whether the named type is a direct base class. 12009 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 12010 .getUnqualifiedType(); 12011 for (auto &Base : Derived->bases()) { 12012 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 12013 if (CanonicalDesiredBase == BaseType) 12014 return &Base; 12015 if (BaseType->isDependentType()) 12016 AnyDependentBases = true; 12017 } 12018 return nullptr; 12019 } 12020 12021 namespace { 12022 class UsingValidatorCCC final : public CorrectionCandidateCallback { 12023 public: 12024 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 12025 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 12026 : HasTypenameKeyword(HasTypenameKeyword), 12027 IsInstantiation(IsInstantiation), OldNNS(NNS), 12028 RequireMemberOf(RequireMemberOf) {} 12029 12030 bool ValidateCandidate(const TypoCorrection &Candidate) override { 12031 NamedDecl *ND = Candidate.getCorrectionDecl(); 12032 12033 // Keywords are not valid here. 12034 if (!ND || isa<NamespaceDecl>(ND)) 12035 return false; 12036 12037 // Completely unqualified names are invalid for a 'using' declaration. 12038 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 12039 return false; 12040 12041 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 12042 // reject. 12043 12044 if (RequireMemberOf) { 12045 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 12046 if (FoundRecord && FoundRecord->isInjectedClassName()) { 12047 // No-one ever wants a using-declaration to name an injected-class-name 12048 // of a base class, unless they're declaring an inheriting constructor. 12049 ASTContext &Ctx = ND->getASTContext(); 12050 if (!Ctx.getLangOpts().CPlusPlus11) 12051 return false; 12052 QualType FoundType = Ctx.getRecordType(FoundRecord); 12053 12054 // Check that the injected-class-name is named as a member of its own 12055 // type; we don't want to suggest 'using Derived::Base;', since that 12056 // means something else. 12057 NestedNameSpecifier *Specifier = 12058 Candidate.WillReplaceSpecifier() 12059 ? Candidate.getCorrectionSpecifier() 12060 : OldNNS; 12061 if (!Specifier->getAsType() || 12062 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 12063 return false; 12064 12065 // Check that this inheriting constructor declaration actually names a 12066 // direct base class of the current class. 12067 bool AnyDependentBases = false; 12068 if (!findDirectBaseWithType(RequireMemberOf, 12069 Ctx.getRecordType(FoundRecord), 12070 AnyDependentBases) && 12071 !AnyDependentBases) 12072 return false; 12073 } else { 12074 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 12075 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 12076 return false; 12077 12078 // FIXME: Check that the base class member is accessible? 12079 } 12080 } else { 12081 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 12082 if (FoundRecord && FoundRecord->isInjectedClassName()) 12083 return false; 12084 } 12085 12086 if (isa<TypeDecl>(ND)) 12087 return HasTypenameKeyword || !IsInstantiation; 12088 12089 return !HasTypenameKeyword; 12090 } 12091 12092 std::unique_ptr<CorrectionCandidateCallback> clone() override { 12093 return std::make_unique<UsingValidatorCCC>(*this); 12094 } 12095 12096 private: 12097 bool HasTypenameKeyword; 12098 bool IsInstantiation; 12099 NestedNameSpecifier *OldNNS; 12100 CXXRecordDecl *RequireMemberOf; 12101 }; 12102 } // end anonymous namespace 12103 12104 /// Remove decls we can't actually see from a lookup being used to declare 12105 /// shadow using decls. 12106 /// 12107 /// \param S - The scope of the potential shadow decl 12108 /// \param Previous - The lookup of a potential shadow decl's name. 12109 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) { 12110 // It is really dumb that we have to do this. 12111 LookupResult::Filter F = Previous.makeFilter(); 12112 while (F.hasNext()) { 12113 NamedDecl *D = F.next(); 12114 if (!isDeclInScope(D, CurContext, S)) 12115 F.erase(); 12116 // If we found a local extern declaration that's not ordinarily visible, 12117 // and this declaration is being added to a non-block scope, ignore it. 12118 // We're only checking for scope conflicts here, not also for violations 12119 // of the linkage rules. 12120 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 12121 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 12122 F.erase(); 12123 } 12124 F.done(); 12125 } 12126 12127 /// Builds a using declaration. 12128 /// 12129 /// \param IsInstantiation - Whether this call arises from an 12130 /// instantiation of an unresolved using declaration. We treat 12131 /// the lookup differently for these declarations. 12132 NamedDecl *Sema::BuildUsingDeclaration( 12133 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 12134 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 12135 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 12136 const ParsedAttributesView &AttrList, bool IsInstantiation, 12137 bool IsUsingIfExists) { 12138 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 12139 SourceLocation IdentLoc = NameInfo.getLoc(); 12140 assert(IdentLoc.isValid() && "Invalid TargetName location."); 12141 12142 // FIXME: We ignore attributes for now. 12143 12144 // For an inheriting constructor declaration, the name of the using 12145 // declaration is the name of a constructor in this class, not in the 12146 // base class. 12147 DeclarationNameInfo UsingName = NameInfo; 12148 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 12149 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 12150 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12151 Context.getCanonicalType(Context.getRecordType(RD)))); 12152 12153 // Do the redeclaration lookup in the current scope. 12154 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 12155 ForVisibleRedeclaration); 12156 Previous.setHideTags(false); 12157 if (S) { 12158 LookupName(Previous, S); 12159 12160 FilterUsingLookup(S, Previous); 12161 } else { 12162 assert(IsInstantiation && "no scope in non-instantiation"); 12163 if (CurContext->isRecord()) 12164 LookupQualifiedName(Previous, CurContext); 12165 else { 12166 // No redeclaration check is needed here; in non-member contexts we 12167 // diagnosed all possible conflicts with other using-declarations when 12168 // building the template: 12169 // 12170 // For a dependent non-type using declaration, the only valid case is 12171 // if we instantiate to a single enumerator. We check for conflicts 12172 // between shadow declarations we introduce, and we check in the template 12173 // definition for conflicts between a non-type using declaration and any 12174 // other declaration, which together covers all cases. 12175 // 12176 // A dependent typename using declaration will never successfully 12177 // instantiate, since it will always name a class member, so we reject 12178 // that in the template definition. 12179 } 12180 } 12181 12182 // Check for invalid redeclarations. 12183 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 12184 SS, IdentLoc, Previous)) 12185 return nullptr; 12186 12187 // 'using_if_exists' doesn't make sense on an inherited constructor. 12188 if (IsUsingIfExists && UsingName.getName().getNameKind() == 12189 DeclarationName::CXXConstructorName) { 12190 Diag(UsingLoc, diag::err_using_if_exists_on_ctor); 12191 return nullptr; 12192 } 12193 12194 DeclContext *LookupContext = computeDeclContext(SS); 12195 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12196 if (!LookupContext || EllipsisLoc.isValid()) { 12197 NamedDecl *D; 12198 // Dependent scope, or an unexpanded pack 12199 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, 12200 SS, NameInfo, IdentLoc)) 12201 return nullptr; 12202 12203 if (HasTypenameKeyword) { 12204 // FIXME: not all declaration name kinds are legal here 12205 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 12206 UsingLoc, TypenameLoc, 12207 QualifierLoc, 12208 IdentLoc, NameInfo.getName(), 12209 EllipsisLoc); 12210 } else { 12211 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 12212 QualifierLoc, NameInfo, EllipsisLoc); 12213 } 12214 D->setAccess(AS); 12215 CurContext->addDecl(D); 12216 ProcessDeclAttributeList(S, D, AttrList); 12217 return D; 12218 } 12219 12220 auto Build = [&](bool Invalid) { 12221 UsingDecl *UD = 12222 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 12223 UsingName, HasTypenameKeyword); 12224 UD->setAccess(AS); 12225 CurContext->addDecl(UD); 12226 ProcessDeclAttributeList(S, UD, AttrList); 12227 UD->setInvalidDecl(Invalid); 12228 return UD; 12229 }; 12230 auto BuildInvalid = [&]{ return Build(true); }; 12231 auto BuildValid = [&]{ return Build(false); }; 12232 12233 if (RequireCompleteDeclContext(SS, LookupContext)) 12234 return BuildInvalid(); 12235 12236 // Look up the target name. 12237 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12238 12239 // Unlike most lookups, we don't always want to hide tag 12240 // declarations: tag names are visible through the using declaration 12241 // even if hidden by ordinary names, *except* in a dependent context 12242 // where it's important for the sanity of two-phase lookup. 12243 if (!IsInstantiation) 12244 R.setHideTags(false); 12245 12246 // For the purposes of this lookup, we have a base object type 12247 // equal to that of the current context. 12248 if (CurContext->isRecord()) { 12249 R.setBaseObjectType( 12250 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 12251 } 12252 12253 LookupQualifiedName(R, LookupContext); 12254 12255 // Validate the context, now we have a lookup 12256 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 12257 IdentLoc, &R)) 12258 return nullptr; 12259 12260 if (R.empty() && IsUsingIfExists) 12261 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc, 12262 UsingName.getName()), 12263 AS_public); 12264 12265 // Try to correct typos if possible. If constructor name lookup finds no 12266 // results, that means the named class has no explicit constructors, and we 12267 // suppressed declaring implicit ones (probably because it's dependent or 12268 // invalid). 12269 if (R.empty() && 12270 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 12271 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of 12272 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where 12273 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later. 12274 auto *II = NameInfo.getName().getAsIdentifierInfo(); 12275 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 12276 CurContext->isStdNamespace() && 12277 isa<TranslationUnitDecl>(LookupContext) && 12278 getSourceManager().isInSystemHeader(UsingLoc)) 12279 return nullptr; 12280 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 12281 dyn_cast<CXXRecordDecl>(CurContext)); 12282 if (TypoCorrection Corrected = 12283 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 12284 CTK_ErrorRecovery)) { 12285 // We reject candidates where DroppedSpecifier == true, hence the 12286 // literal '0' below. 12287 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 12288 << NameInfo.getName() << LookupContext << 0 12289 << SS.getRange()); 12290 12291 // If we picked a correction with no attached Decl we can't do anything 12292 // useful with it, bail out. 12293 NamedDecl *ND = Corrected.getCorrectionDecl(); 12294 if (!ND) 12295 return BuildInvalid(); 12296 12297 // If we corrected to an inheriting constructor, handle it as one. 12298 auto *RD = dyn_cast<CXXRecordDecl>(ND); 12299 if (RD && RD->isInjectedClassName()) { 12300 // The parent of the injected class name is the class itself. 12301 RD = cast<CXXRecordDecl>(RD->getParent()); 12302 12303 // Fix up the information we'll use to build the using declaration. 12304 if (Corrected.WillReplaceSpecifier()) { 12305 NestedNameSpecifierLocBuilder Builder; 12306 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 12307 QualifierLoc.getSourceRange()); 12308 QualifierLoc = Builder.getWithLocInContext(Context); 12309 } 12310 12311 // In this case, the name we introduce is the name of a derived class 12312 // constructor. 12313 auto *CurClass = cast<CXXRecordDecl>(CurContext); 12314 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12315 Context.getCanonicalType(Context.getRecordType(CurClass)))); 12316 UsingName.setNamedTypeInfo(nullptr); 12317 for (auto *Ctor : LookupConstructors(RD)) 12318 R.addDecl(Ctor); 12319 R.resolveKind(); 12320 } else { 12321 // FIXME: Pick up all the declarations if we found an overloaded 12322 // function. 12323 UsingName.setName(ND->getDeclName()); 12324 R.addDecl(ND); 12325 } 12326 } else { 12327 Diag(IdentLoc, diag::err_no_member) 12328 << NameInfo.getName() << LookupContext << SS.getRange(); 12329 return BuildInvalid(); 12330 } 12331 } 12332 12333 if (R.isAmbiguous()) 12334 return BuildInvalid(); 12335 12336 if (HasTypenameKeyword) { 12337 // If we asked for a typename and got a non-type decl, error out. 12338 if (!R.getAsSingle<TypeDecl>() && 12339 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) { 12340 Diag(IdentLoc, diag::err_using_typename_non_type); 12341 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12342 Diag((*I)->getUnderlyingDecl()->getLocation(), 12343 diag::note_using_decl_target); 12344 return BuildInvalid(); 12345 } 12346 } else { 12347 // If we asked for a non-typename and we got a type, error out, 12348 // but only if this is an instantiation of an unresolved using 12349 // decl. Otherwise just silently find the type name. 12350 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 12351 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 12352 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 12353 return BuildInvalid(); 12354 } 12355 } 12356 12357 // C++14 [namespace.udecl]p6: 12358 // A using-declaration shall not name a namespace. 12359 if (R.getAsSingle<NamespaceDecl>()) { 12360 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 12361 << SS.getRange(); 12362 return BuildInvalid(); 12363 } 12364 12365 UsingDecl *UD = BuildValid(); 12366 12367 // Some additional rules apply to inheriting constructors. 12368 if (UsingName.getName().getNameKind() == 12369 DeclarationName::CXXConstructorName) { 12370 // Suppress access diagnostics; the access check is instead performed at the 12371 // point of use for an inheriting constructor. 12372 R.suppressDiagnostics(); 12373 if (CheckInheritingConstructorUsingDecl(UD)) 12374 return UD; 12375 } 12376 12377 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 12378 UsingShadowDecl *PrevDecl = nullptr; 12379 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 12380 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 12381 } 12382 12383 return UD; 12384 } 12385 12386 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 12387 SourceLocation UsingLoc, 12388 SourceLocation EnumLoc, 12389 SourceLocation NameLoc, 12390 EnumDecl *ED) { 12391 bool Invalid = false; 12392 12393 if (CurContext->getRedeclContext()->isRecord()) { 12394 /// In class scope, check if this is a duplicate, for better a diagnostic. 12395 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc); 12396 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName, 12397 ForVisibleRedeclaration); 12398 12399 LookupName(Previous, S); 12400 12401 for (NamedDecl *D : Previous) 12402 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D)) 12403 if (UED->getEnumDecl() == ED) { 12404 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration) 12405 << SourceRange(EnumLoc, NameLoc); 12406 Diag(D->getLocation(), diag::note_using_enum_decl) << 1; 12407 Invalid = true; 12408 break; 12409 } 12410 } 12411 12412 if (RequireCompleteEnumDecl(ED, NameLoc)) 12413 Invalid = true; 12414 12415 UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc, 12416 EnumLoc, NameLoc, ED); 12417 UD->setAccess(AS); 12418 CurContext->addDecl(UD); 12419 12420 if (Invalid) { 12421 UD->setInvalidDecl(); 12422 return UD; 12423 } 12424 12425 // Create the shadow decls for each enumerator 12426 for (EnumConstantDecl *EC : ED->enumerators()) { 12427 UsingShadowDecl *PrevDecl = nullptr; 12428 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation()); 12429 LookupResult Previous(*this, DNI, LookupOrdinaryName, 12430 ForVisibleRedeclaration); 12431 LookupName(Previous, S); 12432 FilterUsingLookup(S, Previous); 12433 12434 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl)) 12435 BuildUsingShadowDecl(S, UD, EC, PrevDecl); 12436 } 12437 12438 return UD; 12439 } 12440 12441 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 12442 ArrayRef<NamedDecl *> Expansions) { 12443 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 12444 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 12445 isa<UsingPackDecl>(InstantiatedFrom)); 12446 12447 auto *UPD = 12448 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 12449 UPD->setAccess(InstantiatedFrom->getAccess()); 12450 CurContext->addDecl(UPD); 12451 return UPD; 12452 } 12453 12454 /// Additional checks for a using declaration referring to a constructor name. 12455 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 12456 assert(!UD->hasTypename() && "expecting a constructor name"); 12457 12458 const Type *SourceType = UD->getQualifier()->getAsType(); 12459 assert(SourceType && 12460 "Using decl naming constructor doesn't have type in scope spec."); 12461 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 12462 12463 // Check whether the named type is a direct base class. 12464 bool AnyDependentBases = false; 12465 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 12466 AnyDependentBases); 12467 if (!Base && !AnyDependentBases) { 12468 Diag(UD->getUsingLoc(), 12469 diag::err_using_decl_constructor_not_in_direct_base) 12470 << UD->getNameInfo().getSourceRange() 12471 << QualType(SourceType, 0) << TargetClass; 12472 UD->setInvalidDecl(); 12473 return true; 12474 } 12475 12476 if (Base) 12477 Base->setInheritConstructors(); 12478 12479 return false; 12480 } 12481 12482 /// Checks that the given using declaration is not an invalid 12483 /// redeclaration. Note that this is checking only for the using decl 12484 /// itself, not for any ill-formedness among the UsingShadowDecls. 12485 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 12486 bool HasTypenameKeyword, 12487 const CXXScopeSpec &SS, 12488 SourceLocation NameLoc, 12489 const LookupResult &Prev) { 12490 NestedNameSpecifier *Qual = SS.getScopeRep(); 12491 12492 // C++03 [namespace.udecl]p8: 12493 // C++0x [namespace.udecl]p10: 12494 // A using-declaration is a declaration and can therefore be used 12495 // repeatedly where (and only where) multiple declarations are 12496 // allowed. 12497 // 12498 // That's in non-member contexts. 12499 if (!CurContext->getRedeclContext()->isRecord()) { 12500 // A dependent qualifier outside a class can only ever resolve to an 12501 // enumeration type. Therefore it conflicts with any other non-type 12502 // declaration in the same scope. 12503 // FIXME: How should we check for dependent type-type conflicts at block 12504 // scope? 12505 if (Qual->isDependent() && !HasTypenameKeyword) { 12506 for (auto *D : Prev) { 12507 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 12508 bool OldCouldBeEnumerator = 12509 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 12510 Diag(NameLoc, 12511 OldCouldBeEnumerator ? diag::err_redefinition 12512 : diag::err_redefinition_different_kind) 12513 << Prev.getLookupName(); 12514 Diag(D->getLocation(), diag::note_previous_definition); 12515 return true; 12516 } 12517 } 12518 } 12519 return false; 12520 } 12521 12522 const NestedNameSpecifier *CNNS = 12523 Context.getCanonicalNestedNameSpecifier(Qual); 12524 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 12525 NamedDecl *D = *I; 12526 12527 bool DTypename; 12528 NestedNameSpecifier *DQual; 12529 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 12530 DTypename = UD->hasTypename(); 12531 DQual = UD->getQualifier(); 12532 } else if (UnresolvedUsingValueDecl *UD 12533 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 12534 DTypename = false; 12535 DQual = UD->getQualifier(); 12536 } else if (UnresolvedUsingTypenameDecl *UD 12537 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 12538 DTypename = true; 12539 DQual = UD->getQualifier(); 12540 } else continue; 12541 12542 // using decls differ if one says 'typename' and the other doesn't. 12543 // FIXME: non-dependent using decls? 12544 if (HasTypenameKeyword != DTypename) continue; 12545 12546 // using decls differ if they name different scopes (but note that 12547 // template instantiation can cause this check to trigger when it 12548 // didn't before instantiation). 12549 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual)) 12550 continue; 12551 12552 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 12553 Diag(D->getLocation(), diag::note_using_decl) << 1; 12554 return true; 12555 } 12556 12557 return false; 12558 } 12559 12560 /// Checks that the given nested-name qualifier used in a using decl 12561 /// in the current context is appropriately related to the current 12562 /// scope. If an error is found, diagnoses it and returns true. 12563 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the 12564 /// result of that lookup. UD is likewise nullptr, except when we have an 12565 /// already-populated UsingDecl whose shadow decls contain the same information 12566 /// (i.e. we're instantiating a UsingDecl with non-dependent scope). 12567 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, 12568 const CXXScopeSpec &SS, 12569 const DeclarationNameInfo &NameInfo, 12570 SourceLocation NameLoc, 12571 const LookupResult *R, const UsingDecl *UD) { 12572 DeclContext *NamedContext = computeDeclContext(SS); 12573 assert(bool(NamedContext) == (R || UD) && !(R && UD) && 12574 "resolvable context must have exactly one set of decls"); 12575 12576 // C++ 20 permits using an enumerator that does not have a class-hierarchy 12577 // relationship. 12578 bool Cxx20Enumerator = false; 12579 if (NamedContext) { 12580 EnumConstantDecl *EC = nullptr; 12581 if (R) 12582 EC = R->getAsSingle<EnumConstantDecl>(); 12583 else if (UD && UD->shadow_size() == 1) 12584 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl()); 12585 if (EC) 12586 Cxx20Enumerator = getLangOpts().CPlusPlus20; 12587 12588 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) { 12589 // C++14 [namespace.udecl]p7: 12590 // A using-declaration shall not name a scoped enumerator. 12591 // C++20 p1099 permits enumerators. 12592 if (EC && R && ED->isScoped()) 12593 Diag(SS.getBeginLoc(), 12594 getLangOpts().CPlusPlus20 12595 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator 12596 : diag::ext_using_decl_scoped_enumerator) 12597 << SS.getRange(); 12598 12599 // We want to consider the scope of the enumerator 12600 NamedContext = ED->getDeclContext(); 12601 } 12602 } 12603 12604 if (!CurContext->isRecord()) { 12605 // C++03 [namespace.udecl]p3: 12606 // C++0x [namespace.udecl]p8: 12607 // A using-declaration for a class member shall be a member-declaration. 12608 // C++20 [namespace.udecl]p7 12609 // ... other than an enumerator ... 12610 12611 // If we weren't able to compute a valid scope, it might validly be a 12612 // dependent class or enumeration scope. If we have a 'typename' keyword, 12613 // the scope must resolve to a class type. 12614 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord() 12615 : !HasTypename) 12616 return false; // OK 12617 12618 Diag(NameLoc, 12619 Cxx20Enumerator 12620 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator 12621 : diag::err_using_decl_can_not_refer_to_class_member) 12622 << SS.getRange(); 12623 12624 if (Cxx20Enumerator) 12625 return false; // OK 12626 12627 auto *RD = NamedContext 12628 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 12629 : nullptr; 12630 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) { 12631 // See if there's a helpful fixit 12632 12633 if (!R) { 12634 // We will have already diagnosed the problem on the template 12635 // definition, Maybe we should do so again? 12636 } else if (R->getAsSingle<TypeDecl>()) { 12637 if (getLangOpts().CPlusPlus11) { 12638 // Convert 'using X::Y;' to 'using Y = X::Y;'. 12639 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 12640 << 0 // alias declaration 12641 << FixItHint::CreateInsertion(SS.getBeginLoc(), 12642 NameInfo.getName().getAsString() + 12643 " = "); 12644 } else { 12645 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 12646 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 12647 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 12648 << 1 // typedef declaration 12649 << FixItHint::CreateReplacement(UsingLoc, "typedef") 12650 << FixItHint::CreateInsertion( 12651 InsertLoc, " " + NameInfo.getName().getAsString()); 12652 } 12653 } else if (R->getAsSingle<VarDecl>()) { 12654 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12655 // repeating the type of the static data member here. 12656 FixItHint FixIt; 12657 if (getLangOpts().CPlusPlus11) { 12658 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12659 FixIt = FixItHint::CreateReplacement( 12660 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 12661 } 12662 12663 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12664 << 2 // reference declaration 12665 << FixIt; 12666 } else if (R->getAsSingle<EnumConstantDecl>()) { 12667 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12668 // repeating the type of the enumeration here, and we can't do so if 12669 // the type is anonymous. 12670 FixItHint FixIt; 12671 if (getLangOpts().CPlusPlus11) { 12672 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12673 FixIt = FixItHint::CreateReplacement( 12674 UsingLoc, 12675 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 12676 } 12677 12678 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12679 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 12680 << FixIt; 12681 } 12682 } 12683 12684 return true; // Fail 12685 } 12686 12687 // If the named context is dependent, we can't decide much. 12688 if (!NamedContext) { 12689 // FIXME: in C++0x, we can diagnose if we can prove that the 12690 // nested-name-specifier does not refer to a base class, which is 12691 // still possible in some cases. 12692 12693 // Otherwise we have to conservatively report that things might be 12694 // okay. 12695 return false; 12696 } 12697 12698 // The current scope is a record. 12699 if (!NamedContext->isRecord()) { 12700 // Ideally this would point at the last name in the specifier, 12701 // but we don't have that level of source info. 12702 Diag(SS.getBeginLoc(), 12703 Cxx20Enumerator 12704 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator 12705 : diag::err_using_decl_nested_name_specifier_is_not_class) 12706 << SS.getScopeRep() << SS.getRange(); 12707 12708 if (Cxx20Enumerator) 12709 return false; // OK 12710 12711 return true; 12712 } 12713 12714 if (!NamedContext->isDependentContext() && 12715 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 12716 return true; 12717 12718 if (getLangOpts().CPlusPlus11) { 12719 // C++11 [namespace.udecl]p3: 12720 // In a using-declaration used as a member-declaration, the 12721 // nested-name-specifier shall name a base class of the class 12722 // being defined. 12723 12724 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 12725 cast<CXXRecordDecl>(NamedContext))) { 12726 12727 if (Cxx20Enumerator) { 12728 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator) 12729 << SS.getRange(); 12730 return false; 12731 } 12732 12733 if (CurContext == NamedContext) { 12734 Diag(SS.getBeginLoc(), 12735 diag::err_using_decl_nested_name_specifier_is_current_class) 12736 << SS.getRange(); 12737 return !getLangOpts().CPlusPlus20; 12738 } 12739 12740 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 12741 Diag(SS.getBeginLoc(), 12742 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12743 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext) 12744 << SS.getRange(); 12745 } 12746 return true; 12747 } 12748 12749 return false; 12750 } 12751 12752 // C++03 [namespace.udecl]p4: 12753 // A using-declaration used as a member-declaration shall refer 12754 // to a member of a base class of the class being defined [etc.]. 12755 12756 // Salient point: SS doesn't have to name a base class as long as 12757 // lookup only finds members from base classes. Therefore we can 12758 // diagnose here only if we can prove that that can't happen, 12759 // i.e. if the class hierarchies provably don't intersect. 12760 12761 // TODO: it would be nice if "definitely valid" results were cached 12762 // in the UsingDecl and UsingShadowDecl so that these checks didn't 12763 // need to be repeated. 12764 12765 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 12766 auto Collect = [&Bases](const CXXRecordDecl *Base) { 12767 Bases.insert(Base); 12768 return true; 12769 }; 12770 12771 // Collect all bases. Return false if we find a dependent base. 12772 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 12773 return false; 12774 12775 // Returns true if the base is dependent or is one of the accumulated base 12776 // classes. 12777 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 12778 return !Bases.count(Base); 12779 }; 12780 12781 // Return false if the class has a dependent base or if it or one 12782 // of its bases is present in the base set of the current context. 12783 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 12784 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 12785 return false; 12786 12787 Diag(SS.getRange().getBegin(), 12788 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12789 << SS.getScopeRep() 12790 << cast<CXXRecordDecl>(CurContext) 12791 << SS.getRange(); 12792 12793 return true; 12794 } 12795 12796 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 12797 MultiTemplateParamsArg TemplateParamLists, 12798 SourceLocation UsingLoc, UnqualifiedId &Name, 12799 const ParsedAttributesView &AttrList, 12800 TypeResult Type, Decl *DeclFromDeclSpec) { 12801 // Skip up to the relevant declaration scope. 12802 while (S->isTemplateParamScope()) 12803 S = S->getParent(); 12804 assert((S->getFlags() & Scope::DeclScope) && 12805 "got alias-declaration outside of declaration scope"); 12806 12807 if (Type.isInvalid()) 12808 return nullptr; 12809 12810 bool Invalid = false; 12811 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 12812 TypeSourceInfo *TInfo = nullptr; 12813 GetTypeFromParser(Type.get(), &TInfo); 12814 12815 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 12816 return nullptr; 12817 12818 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 12819 UPPC_DeclarationType)) { 12820 Invalid = true; 12821 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12822 TInfo->getTypeLoc().getBeginLoc()); 12823 } 12824 12825 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12826 TemplateParamLists.size() 12827 ? forRedeclarationInCurContext() 12828 : ForVisibleRedeclaration); 12829 LookupName(Previous, S); 12830 12831 // Warn about shadowing the name of a template parameter. 12832 if (Previous.isSingleResult() && 12833 Previous.getFoundDecl()->isTemplateParameter()) { 12834 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 12835 Previous.clear(); 12836 } 12837 12838 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 12839 "name in alias declaration must be an identifier"); 12840 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 12841 Name.StartLocation, 12842 Name.Identifier, TInfo); 12843 12844 NewTD->setAccess(AS); 12845 12846 if (Invalid) 12847 NewTD->setInvalidDecl(); 12848 12849 ProcessDeclAttributeList(S, NewTD, AttrList); 12850 AddPragmaAttributes(S, NewTD); 12851 12852 CheckTypedefForVariablyModifiedType(S, NewTD); 12853 Invalid |= NewTD->isInvalidDecl(); 12854 12855 bool Redeclaration = false; 12856 12857 NamedDecl *NewND; 12858 if (TemplateParamLists.size()) { 12859 TypeAliasTemplateDecl *OldDecl = nullptr; 12860 TemplateParameterList *OldTemplateParams = nullptr; 12861 12862 if (TemplateParamLists.size() != 1) { 12863 Diag(UsingLoc, diag::err_alias_template_extra_headers) 12864 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 12865 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 12866 } 12867 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 12868 12869 // Check that we can declare a template here. 12870 if (CheckTemplateDeclScope(S, TemplateParams)) 12871 return nullptr; 12872 12873 // Only consider previous declarations in the same scope. 12874 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 12875 /*ExplicitInstantiationOrSpecialization*/false); 12876 if (!Previous.empty()) { 12877 Redeclaration = true; 12878 12879 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 12880 if (!OldDecl && !Invalid) { 12881 Diag(UsingLoc, diag::err_redefinition_different_kind) 12882 << Name.Identifier; 12883 12884 NamedDecl *OldD = Previous.getRepresentativeDecl(); 12885 if (OldD->getLocation().isValid()) 12886 Diag(OldD->getLocation(), diag::note_previous_definition); 12887 12888 Invalid = true; 12889 } 12890 12891 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 12892 if (TemplateParameterListsAreEqual(TemplateParams, 12893 OldDecl->getTemplateParameters(), 12894 /*Complain=*/true, 12895 TPL_TemplateMatch)) 12896 OldTemplateParams = 12897 OldDecl->getMostRecentDecl()->getTemplateParameters(); 12898 else 12899 Invalid = true; 12900 12901 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 12902 if (!Invalid && 12903 !Context.hasSameType(OldTD->getUnderlyingType(), 12904 NewTD->getUnderlyingType())) { 12905 // FIXME: The C++0x standard does not clearly say this is ill-formed, 12906 // but we can't reasonably accept it. 12907 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 12908 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 12909 if (OldTD->getLocation().isValid()) 12910 Diag(OldTD->getLocation(), diag::note_previous_definition); 12911 Invalid = true; 12912 } 12913 } 12914 } 12915 12916 // Merge any previous default template arguments into our parameters, 12917 // and check the parameter list. 12918 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 12919 TPC_TypeAliasTemplate)) 12920 return nullptr; 12921 12922 TypeAliasTemplateDecl *NewDecl = 12923 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 12924 Name.Identifier, TemplateParams, 12925 NewTD); 12926 NewTD->setDescribedAliasTemplate(NewDecl); 12927 12928 NewDecl->setAccess(AS); 12929 12930 if (Invalid) 12931 NewDecl->setInvalidDecl(); 12932 else if (OldDecl) { 12933 NewDecl->setPreviousDecl(OldDecl); 12934 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 12935 } 12936 12937 NewND = NewDecl; 12938 } else { 12939 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 12940 setTagNameForLinkagePurposes(TD, NewTD); 12941 handleTagNumbering(TD, S); 12942 } 12943 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 12944 NewND = NewTD; 12945 } 12946 12947 PushOnScopeChains(NewND, S); 12948 ActOnDocumentableDecl(NewND); 12949 return NewND; 12950 } 12951 12952 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 12953 SourceLocation AliasLoc, 12954 IdentifierInfo *Alias, CXXScopeSpec &SS, 12955 SourceLocation IdentLoc, 12956 IdentifierInfo *Ident) { 12957 12958 // Lookup the namespace name. 12959 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 12960 LookupParsedName(R, S, &SS); 12961 12962 if (R.isAmbiguous()) 12963 return nullptr; 12964 12965 if (R.empty()) { 12966 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 12967 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 12968 return nullptr; 12969 } 12970 } 12971 assert(!R.isAmbiguous() && !R.empty()); 12972 NamedDecl *ND = R.getRepresentativeDecl(); 12973 12974 // Check if we have a previous declaration with the same name. 12975 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 12976 ForVisibleRedeclaration); 12977 LookupName(PrevR, S); 12978 12979 // Check we're not shadowing a template parameter. 12980 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 12981 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 12982 PrevR.clear(); 12983 } 12984 12985 // Filter out any other lookup result from an enclosing scope. 12986 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 12987 /*AllowInlineNamespace*/false); 12988 12989 // Find the previous declaration and check that we can redeclare it. 12990 NamespaceAliasDecl *Prev = nullptr; 12991 if (PrevR.isSingleResult()) { 12992 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 12993 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 12994 // We already have an alias with the same name that points to the same 12995 // namespace; check that it matches. 12996 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 12997 Prev = AD; 12998 } else if (isVisible(PrevDecl)) { 12999 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 13000 << Alias; 13001 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 13002 << AD->getNamespace(); 13003 return nullptr; 13004 } 13005 } else if (isVisible(PrevDecl)) { 13006 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 13007 ? diag::err_redefinition 13008 : diag::err_redefinition_different_kind; 13009 Diag(AliasLoc, DiagID) << Alias; 13010 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13011 return nullptr; 13012 } 13013 } 13014 13015 // The use of a nested name specifier may trigger deprecation warnings. 13016 DiagnoseUseOfDecl(ND, IdentLoc); 13017 13018 NamespaceAliasDecl *AliasDecl = 13019 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 13020 Alias, SS.getWithLocInContext(Context), 13021 IdentLoc, ND); 13022 if (Prev) 13023 AliasDecl->setPreviousDecl(Prev); 13024 13025 PushOnScopeChains(AliasDecl, S); 13026 return AliasDecl; 13027 } 13028 13029 namespace { 13030 struct SpecialMemberExceptionSpecInfo 13031 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 13032 SourceLocation Loc; 13033 Sema::ImplicitExceptionSpecification ExceptSpec; 13034 13035 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 13036 Sema::CXXSpecialMember CSM, 13037 Sema::InheritedConstructorInfo *ICI, 13038 SourceLocation Loc) 13039 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 13040 13041 bool visitBase(CXXBaseSpecifier *Base); 13042 bool visitField(FieldDecl *FD); 13043 13044 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 13045 unsigned Quals); 13046 13047 void visitSubobjectCall(Subobject Subobj, 13048 Sema::SpecialMemberOverloadResult SMOR); 13049 }; 13050 } 13051 13052 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 13053 auto *RT = Base->getType()->getAs<RecordType>(); 13054 if (!RT) 13055 return false; 13056 13057 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 13058 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 13059 if (auto *BaseCtor = SMOR.getMethod()) { 13060 visitSubobjectCall(Base, BaseCtor); 13061 return false; 13062 } 13063 13064 visitClassSubobject(BaseClass, Base, 0); 13065 return false; 13066 } 13067 13068 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 13069 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 13070 Expr *E = FD->getInClassInitializer(); 13071 if (!E) 13072 // FIXME: It's a little wasteful to build and throw away a 13073 // CXXDefaultInitExpr here. 13074 // FIXME: We should have a single context note pointing at Loc, and 13075 // this location should be MD->getLocation() instead, since that's 13076 // the location where we actually use the default init expression. 13077 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 13078 if (E) 13079 ExceptSpec.CalledExpr(E); 13080 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 13081 ->getAs<RecordType>()) { 13082 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 13083 FD->getType().getCVRQualifiers()); 13084 } 13085 return false; 13086 } 13087 13088 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 13089 Subobject Subobj, 13090 unsigned Quals) { 13091 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 13092 bool IsMutable = Field && Field->isMutable(); 13093 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 13094 } 13095 13096 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 13097 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 13098 // Note, if lookup fails, it doesn't matter what exception specification we 13099 // choose because the special member will be deleted. 13100 if (CXXMethodDecl *MD = SMOR.getMethod()) 13101 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 13102 } 13103 13104 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 13105 llvm::APSInt Result; 13106 ExprResult Converted = CheckConvertedConstantExpression( 13107 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 13108 ExplicitSpec.setExpr(Converted.get()); 13109 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 13110 ExplicitSpec.setKind(Result.getBoolValue() 13111 ? ExplicitSpecKind::ResolvedTrue 13112 : ExplicitSpecKind::ResolvedFalse); 13113 return true; 13114 } 13115 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 13116 return false; 13117 } 13118 13119 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 13120 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 13121 if (!ExplicitExpr->isTypeDependent()) 13122 tryResolveExplicitSpecifier(ES); 13123 return ES; 13124 } 13125 13126 static Sema::ImplicitExceptionSpecification 13127 ComputeDefaultedSpecialMemberExceptionSpec( 13128 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 13129 Sema::InheritedConstructorInfo *ICI) { 13130 ComputingExceptionSpec CES(S, MD, Loc); 13131 13132 CXXRecordDecl *ClassDecl = MD->getParent(); 13133 13134 // C++ [except.spec]p14: 13135 // An implicitly declared special member function (Clause 12) shall have an 13136 // exception-specification. [...] 13137 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 13138 if (ClassDecl->isInvalidDecl()) 13139 return Info.ExceptSpec; 13140 13141 // FIXME: If this diagnostic fires, we're probably missing a check for 13142 // attempting to resolve an exception specification before it's known 13143 // at a higher level. 13144 if (S.RequireCompleteType(MD->getLocation(), 13145 S.Context.getRecordType(ClassDecl), 13146 diag::err_exception_spec_incomplete_type)) 13147 return Info.ExceptSpec; 13148 13149 // C++1z [except.spec]p7: 13150 // [Look for exceptions thrown by] a constructor selected [...] to 13151 // initialize a potentially constructed subobject, 13152 // C++1z [except.spec]p8: 13153 // The exception specification for an implicitly-declared destructor, or a 13154 // destructor without a noexcept-specifier, is potentially-throwing if and 13155 // only if any of the destructors for any of its potentially constructed 13156 // subojects is potentially throwing. 13157 // FIXME: We respect the first rule but ignore the "potentially constructed" 13158 // in the second rule to resolve a core issue (no number yet) that would have 13159 // us reject: 13160 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 13161 // struct B : A {}; 13162 // struct C : B { void f(); }; 13163 // ... due to giving B::~B() a non-throwing exception specification. 13164 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 13165 : Info.VisitAllBases); 13166 13167 return Info.ExceptSpec; 13168 } 13169 13170 namespace { 13171 /// RAII object to register a special member as being currently declared. 13172 struct DeclaringSpecialMember { 13173 Sema &S; 13174 Sema::SpecialMemberDecl D; 13175 Sema::ContextRAII SavedContext; 13176 bool WasAlreadyBeingDeclared; 13177 13178 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 13179 : S(S), D(RD, CSM), SavedContext(S, RD) { 13180 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 13181 if (WasAlreadyBeingDeclared) 13182 // This almost never happens, but if it does, ensure that our cache 13183 // doesn't contain a stale result. 13184 S.SpecialMemberCache.clear(); 13185 else { 13186 // Register a note to be produced if we encounter an error while 13187 // declaring the special member. 13188 Sema::CodeSynthesisContext Ctx; 13189 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 13190 // FIXME: We don't have a location to use here. Using the class's 13191 // location maintains the fiction that we declare all special members 13192 // with the class, but (1) it's not clear that lying about that helps our 13193 // users understand what's going on, and (2) there may be outer contexts 13194 // on the stack (some of which are relevant) and printing them exposes 13195 // our lies. 13196 Ctx.PointOfInstantiation = RD->getLocation(); 13197 Ctx.Entity = RD; 13198 Ctx.SpecialMember = CSM; 13199 S.pushCodeSynthesisContext(Ctx); 13200 } 13201 } 13202 ~DeclaringSpecialMember() { 13203 if (!WasAlreadyBeingDeclared) { 13204 S.SpecialMembersBeingDeclared.erase(D); 13205 S.popCodeSynthesisContext(); 13206 } 13207 } 13208 13209 /// Are we already trying to declare this special member? 13210 bool isAlreadyBeingDeclared() const { 13211 return WasAlreadyBeingDeclared; 13212 } 13213 }; 13214 } 13215 13216 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 13217 // Look up any existing declarations, but don't trigger declaration of all 13218 // implicit special members with this name. 13219 DeclarationName Name = FD->getDeclName(); 13220 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 13221 ForExternalRedeclaration); 13222 for (auto *D : FD->getParent()->lookup(Name)) 13223 if (auto *Acceptable = R.getAcceptableDecl(D)) 13224 R.addDecl(Acceptable); 13225 R.resolveKind(); 13226 R.suppressDiagnostics(); 13227 13228 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 13229 } 13230 13231 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 13232 QualType ResultTy, 13233 ArrayRef<QualType> Args) { 13234 // Build an exception specification pointing back at this constructor. 13235 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 13236 13237 LangAS AS = getDefaultCXXMethodAddrSpace(); 13238 if (AS != LangAS::Default) { 13239 EPI.TypeQuals.addAddressSpace(AS); 13240 } 13241 13242 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 13243 SpecialMem->setType(QT); 13244 13245 // During template instantiation of implicit special member functions we need 13246 // a reliable TypeSourceInfo for the function prototype in order to allow 13247 // functions to be substituted. 13248 if (inTemplateInstantiation() && 13249 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) { 13250 TypeSourceInfo *TSI = 13251 Context.getTrivialTypeSourceInfo(SpecialMem->getType()); 13252 SpecialMem->setTypeSourceInfo(TSI); 13253 } 13254 } 13255 13256 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 13257 CXXRecordDecl *ClassDecl) { 13258 // C++ [class.ctor]p5: 13259 // A default constructor for a class X is a constructor of class X 13260 // that can be called without an argument. If there is no 13261 // user-declared constructor for class X, a default constructor is 13262 // implicitly declared. An implicitly-declared default constructor 13263 // is an inline public member of its class. 13264 assert(ClassDecl->needsImplicitDefaultConstructor() && 13265 "Should not build implicit default constructor!"); 13266 13267 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 13268 if (DSM.isAlreadyBeingDeclared()) 13269 return nullptr; 13270 13271 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13272 CXXDefaultConstructor, 13273 false); 13274 13275 // Create the actual constructor declaration. 13276 CanQualType ClassType 13277 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13278 SourceLocation ClassLoc = ClassDecl->getLocation(); 13279 DeclarationName Name 13280 = Context.DeclarationNames.getCXXConstructorName(ClassType); 13281 DeclarationNameInfo NameInfo(Name, ClassLoc); 13282 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 13283 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 13284 /*TInfo=*/nullptr, ExplicitSpecifier(), 13285 getCurFPFeatures().isFPConstrained(), 13286 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 13287 Constexpr ? ConstexprSpecKind::Constexpr 13288 : ConstexprSpecKind::Unspecified); 13289 DefaultCon->setAccess(AS_public); 13290 DefaultCon->setDefaulted(); 13291 13292 if (getLangOpts().CUDA) { 13293 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 13294 DefaultCon, 13295 /* ConstRHS */ false, 13296 /* Diagnose */ false); 13297 } 13298 13299 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 13300 13301 // We don't need to use SpecialMemberIsTrivial here; triviality for default 13302 // constructors is easy to compute. 13303 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 13304 13305 // Note that we have declared this constructor. 13306 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 13307 13308 Scope *S = getScopeForContext(ClassDecl); 13309 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 13310 13311 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 13312 SetDeclDeleted(DefaultCon, ClassLoc); 13313 13314 if (S) 13315 PushOnScopeChains(DefaultCon, S, false); 13316 ClassDecl->addDecl(DefaultCon); 13317 13318 return DefaultCon; 13319 } 13320 13321 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 13322 CXXConstructorDecl *Constructor) { 13323 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 13324 !Constructor->doesThisDeclarationHaveABody() && 13325 !Constructor->isDeleted()) && 13326 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 13327 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13328 return; 13329 13330 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13331 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 13332 13333 SynthesizedFunctionScope Scope(*this, Constructor); 13334 13335 // The exception specification is needed because we are defining the 13336 // function. 13337 ResolveExceptionSpec(CurrentLocation, 13338 Constructor->getType()->castAs<FunctionProtoType>()); 13339 MarkVTableUsed(CurrentLocation, ClassDecl); 13340 13341 // Add a context note for diagnostics produced after this point. 13342 Scope.addContextNote(CurrentLocation); 13343 13344 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 13345 Constructor->setInvalidDecl(); 13346 return; 13347 } 13348 13349 SourceLocation Loc = Constructor->getEndLoc().isValid() 13350 ? Constructor->getEndLoc() 13351 : Constructor->getLocation(); 13352 Constructor->setBody(new (Context) CompoundStmt(Loc)); 13353 Constructor->markUsed(Context); 13354 13355 if (ASTMutationListener *L = getASTMutationListener()) { 13356 L->CompletedImplicitDefinition(Constructor); 13357 } 13358 13359 DiagnoseUninitializedFields(*this, Constructor); 13360 } 13361 13362 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 13363 // Perform any delayed checks on exception specifications. 13364 CheckDelayedMemberExceptionSpecs(); 13365 } 13366 13367 /// Find or create the fake constructor we synthesize to model constructing an 13368 /// object of a derived class via a constructor of a base class. 13369 CXXConstructorDecl * 13370 Sema::findInheritingConstructor(SourceLocation Loc, 13371 CXXConstructorDecl *BaseCtor, 13372 ConstructorUsingShadowDecl *Shadow) { 13373 CXXRecordDecl *Derived = Shadow->getParent(); 13374 SourceLocation UsingLoc = Shadow->getLocation(); 13375 13376 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 13377 // For now we use the name of the base class constructor as a member of the 13378 // derived class to indicate a (fake) inherited constructor name. 13379 DeclarationName Name = BaseCtor->getDeclName(); 13380 13381 // Check to see if we already have a fake constructor for this inherited 13382 // constructor call. 13383 for (NamedDecl *Ctor : Derived->lookup(Name)) 13384 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 13385 ->getInheritedConstructor() 13386 .getConstructor(), 13387 BaseCtor)) 13388 return cast<CXXConstructorDecl>(Ctor); 13389 13390 DeclarationNameInfo NameInfo(Name, UsingLoc); 13391 TypeSourceInfo *TInfo = 13392 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 13393 FunctionProtoTypeLoc ProtoLoc = 13394 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 13395 13396 // Check the inherited constructor is valid and find the list of base classes 13397 // from which it was inherited. 13398 InheritedConstructorInfo ICI(*this, Loc, Shadow); 13399 13400 bool Constexpr = 13401 BaseCtor->isConstexpr() && 13402 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 13403 false, BaseCtor, &ICI); 13404 13405 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 13406 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 13407 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 13408 /*isInline=*/true, 13409 /*isImplicitlyDeclared=*/true, 13410 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified, 13411 InheritedConstructor(Shadow, BaseCtor), 13412 BaseCtor->getTrailingRequiresClause()); 13413 if (Shadow->isInvalidDecl()) 13414 DerivedCtor->setInvalidDecl(); 13415 13416 // Build an unevaluated exception specification for this fake constructor. 13417 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 13418 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13419 EPI.ExceptionSpec.Type = EST_Unevaluated; 13420 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 13421 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 13422 FPT->getParamTypes(), EPI)); 13423 13424 // Build the parameter declarations. 13425 SmallVector<ParmVarDecl *, 16> ParamDecls; 13426 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 13427 TypeSourceInfo *TInfo = 13428 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 13429 ParmVarDecl *PD = ParmVarDecl::Create( 13430 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 13431 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 13432 PD->setScopeInfo(0, I); 13433 PD->setImplicit(); 13434 // Ensure attributes are propagated onto parameters (this matters for 13435 // format, pass_object_size, ...). 13436 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 13437 ParamDecls.push_back(PD); 13438 ProtoLoc.setParam(I, PD); 13439 } 13440 13441 // Set up the new constructor. 13442 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 13443 DerivedCtor->setAccess(BaseCtor->getAccess()); 13444 DerivedCtor->setParams(ParamDecls); 13445 Derived->addDecl(DerivedCtor); 13446 13447 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 13448 SetDeclDeleted(DerivedCtor, UsingLoc); 13449 13450 return DerivedCtor; 13451 } 13452 13453 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 13454 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 13455 Ctor->getInheritedConstructor().getShadowDecl()); 13456 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 13457 /*Diagnose*/true); 13458 } 13459 13460 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 13461 CXXConstructorDecl *Constructor) { 13462 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13463 assert(Constructor->getInheritedConstructor() && 13464 !Constructor->doesThisDeclarationHaveABody() && 13465 !Constructor->isDeleted()); 13466 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13467 return; 13468 13469 // Initializations are performed "as if by a defaulted default constructor", 13470 // so enter the appropriate scope. 13471 SynthesizedFunctionScope Scope(*this, Constructor); 13472 13473 // The exception specification is needed because we are defining the 13474 // function. 13475 ResolveExceptionSpec(CurrentLocation, 13476 Constructor->getType()->castAs<FunctionProtoType>()); 13477 MarkVTableUsed(CurrentLocation, ClassDecl); 13478 13479 // Add a context note for diagnostics produced after this point. 13480 Scope.addContextNote(CurrentLocation); 13481 13482 ConstructorUsingShadowDecl *Shadow = 13483 Constructor->getInheritedConstructor().getShadowDecl(); 13484 CXXConstructorDecl *InheritedCtor = 13485 Constructor->getInheritedConstructor().getConstructor(); 13486 13487 // [class.inhctor.init]p1: 13488 // initialization proceeds as if a defaulted default constructor is used to 13489 // initialize the D object and each base class subobject from which the 13490 // constructor was inherited 13491 13492 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 13493 CXXRecordDecl *RD = Shadow->getParent(); 13494 SourceLocation InitLoc = Shadow->getLocation(); 13495 13496 // Build explicit initializers for all base classes from which the 13497 // constructor was inherited. 13498 SmallVector<CXXCtorInitializer*, 8> Inits; 13499 for (bool VBase : {false, true}) { 13500 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 13501 if (B.isVirtual() != VBase) 13502 continue; 13503 13504 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 13505 if (!BaseRD) 13506 continue; 13507 13508 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 13509 if (!BaseCtor.first) 13510 continue; 13511 13512 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 13513 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 13514 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 13515 13516 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 13517 Inits.push_back(new (Context) CXXCtorInitializer( 13518 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 13519 SourceLocation())); 13520 } 13521 } 13522 13523 // We now proceed as if for a defaulted default constructor, with the relevant 13524 // initializers replaced. 13525 13526 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 13527 Constructor->setInvalidDecl(); 13528 return; 13529 } 13530 13531 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 13532 Constructor->markUsed(Context); 13533 13534 if (ASTMutationListener *L = getASTMutationListener()) { 13535 L->CompletedImplicitDefinition(Constructor); 13536 } 13537 13538 DiagnoseUninitializedFields(*this, Constructor); 13539 } 13540 13541 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 13542 // C++ [class.dtor]p2: 13543 // If a class has no user-declared destructor, a destructor is 13544 // declared implicitly. An implicitly-declared destructor is an 13545 // inline public member of its class. 13546 assert(ClassDecl->needsImplicitDestructor()); 13547 13548 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 13549 if (DSM.isAlreadyBeingDeclared()) 13550 return nullptr; 13551 13552 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13553 CXXDestructor, 13554 false); 13555 13556 // Create the actual destructor declaration. 13557 CanQualType ClassType 13558 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13559 SourceLocation ClassLoc = ClassDecl->getLocation(); 13560 DeclarationName Name 13561 = Context.DeclarationNames.getCXXDestructorName(ClassType); 13562 DeclarationNameInfo NameInfo(Name, ClassLoc); 13563 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create( 13564 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr, 13565 getCurFPFeatures().isFPConstrained(), 13566 /*isInline=*/true, 13567 /*isImplicitlyDeclared=*/true, 13568 Constexpr ? ConstexprSpecKind::Constexpr 13569 : ConstexprSpecKind::Unspecified); 13570 Destructor->setAccess(AS_public); 13571 Destructor->setDefaulted(); 13572 13573 if (getLangOpts().CUDA) { 13574 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 13575 Destructor, 13576 /* ConstRHS */ false, 13577 /* Diagnose */ false); 13578 } 13579 13580 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 13581 13582 // We don't need to use SpecialMemberIsTrivial here; triviality for 13583 // destructors is easy to compute. 13584 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 13585 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 13586 ClassDecl->hasTrivialDestructorForCall()); 13587 13588 // Note that we have declared this destructor. 13589 ++getASTContext().NumImplicitDestructorsDeclared; 13590 13591 Scope *S = getScopeForContext(ClassDecl); 13592 CheckImplicitSpecialMemberDeclaration(S, Destructor); 13593 13594 // We can't check whether an implicit destructor is deleted before we complete 13595 // the definition of the class, because its validity depends on the alignment 13596 // of the class. We'll check this from ActOnFields once the class is complete. 13597 if (ClassDecl->isCompleteDefinition() && 13598 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 13599 SetDeclDeleted(Destructor, ClassLoc); 13600 13601 // Introduce this destructor into its scope. 13602 if (S) 13603 PushOnScopeChains(Destructor, S, false); 13604 ClassDecl->addDecl(Destructor); 13605 13606 return Destructor; 13607 } 13608 13609 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 13610 CXXDestructorDecl *Destructor) { 13611 assert((Destructor->isDefaulted() && 13612 !Destructor->doesThisDeclarationHaveABody() && 13613 !Destructor->isDeleted()) && 13614 "DefineImplicitDestructor - call it for implicit default dtor"); 13615 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 13616 return; 13617 13618 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13619 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 13620 13621 SynthesizedFunctionScope Scope(*this, Destructor); 13622 13623 // The exception specification is needed because we are defining the 13624 // function. 13625 ResolveExceptionSpec(CurrentLocation, 13626 Destructor->getType()->castAs<FunctionProtoType>()); 13627 MarkVTableUsed(CurrentLocation, ClassDecl); 13628 13629 // Add a context note for diagnostics produced after this point. 13630 Scope.addContextNote(CurrentLocation); 13631 13632 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13633 Destructor->getParent()); 13634 13635 if (CheckDestructor(Destructor)) { 13636 Destructor->setInvalidDecl(); 13637 return; 13638 } 13639 13640 SourceLocation Loc = Destructor->getEndLoc().isValid() 13641 ? Destructor->getEndLoc() 13642 : Destructor->getLocation(); 13643 Destructor->setBody(new (Context) CompoundStmt(Loc)); 13644 Destructor->markUsed(Context); 13645 13646 if (ASTMutationListener *L = getASTMutationListener()) { 13647 L->CompletedImplicitDefinition(Destructor); 13648 } 13649 } 13650 13651 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 13652 CXXDestructorDecl *Destructor) { 13653 if (Destructor->isInvalidDecl()) 13654 return; 13655 13656 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13657 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() && 13658 "implicit complete dtors unneeded outside MS ABI"); 13659 assert(ClassDecl->getNumVBases() > 0 && 13660 "complete dtor only exists for classes with vbases"); 13661 13662 SynthesizedFunctionScope Scope(*this, Destructor); 13663 13664 // Add a context note for diagnostics produced after this point. 13665 Scope.addContextNote(CurrentLocation); 13666 13667 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl); 13668 } 13669 13670 /// Perform any semantic analysis which needs to be delayed until all 13671 /// pending class member declarations have been parsed. 13672 void Sema::ActOnFinishCXXMemberDecls() { 13673 // If the context is an invalid C++ class, just suppress these checks. 13674 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 13675 if (Record->isInvalidDecl()) { 13676 DelayedOverridingExceptionSpecChecks.clear(); 13677 DelayedEquivalentExceptionSpecChecks.clear(); 13678 return; 13679 } 13680 checkForMultipleExportedDefaultConstructors(*this, Record); 13681 } 13682 } 13683 13684 void Sema::ActOnFinishCXXNonNestedClass() { 13685 referenceDLLExportedClassMethods(); 13686 13687 if (!DelayedDllExportMemberFunctions.empty()) { 13688 SmallVector<CXXMethodDecl*, 4> WorkList; 13689 std::swap(DelayedDllExportMemberFunctions, WorkList); 13690 for (CXXMethodDecl *M : WorkList) { 13691 DefineDefaultedFunction(*this, M, M->getLocation()); 13692 13693 // Pass the method to the consumer to get emitted. This is not necessary 13694 // for explicit instantiation definitions, as they will get emitted 13695 // anyway. 13696 if (M->getParent()->getTemplateSpecializationKind() != 13697 TSK_ExplicitInstantiationDefinition) 13698 ActOnFinishInlineFunctionDef(M); 13699 } 13700 } 13701 } 13702 13703 void Sema::referenceDLLExportedClassMethods() { 13704 if (!DelayedDllExportClasses.empty()) { 13705 // Calling ReferenceDllExportedMembers might cause the current function to 13706 // be called again, so use a local copy of DelayedDllExportClasses. 13707 SmallVector<CXXRecordDecl *, 4> WorkList; 13708 std::swap(DelayedDllExportClasses, WorkList); 13709 for (CXXRecordDecl *Class : WorkList) 13710 ReferenceDllExportedMembers(*this, Class); 13711 } 13712 } 13713 13714 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 13715 assert(getLangOpts().CPlusPlus11 && 13716 "adjusting dtor exception specs was introduced in c++11"); 13717 13718 if (Destructor->isDependentContext()) 13719 return; 13720 13721 // C++11 [class.dtor]p3: 13722 // A declaration of a destructor that does not have an exception- 13723 // specification is implicitly considered to have the same exception- 13724 // specification as an implicit declaration. 13725 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); 13726 if (DtorType->hasExceptionSpec()) 13727 return; 13728 13729 // Replace the destructor's type, building off the existing one. Fortunately, 13730 // the only thing of interest in the destructor type is its extended info. 13731 // The return and arguments are fixed. 13732 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 13733 EPI.ExceptionSpec.Type = EST_Unevaluated; 13734 EPI.ExceptionSpec.SourceDecl = Destructor; 13735 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 13736 13737 // FIXME: If the destructor has a body that could throw, and the newly created 13738 // spec doesn't allow exceptions, we should emit a warning, because this 13739 // change in behavior can break conforming C++03 programs at runtime. 13740 // However, we don't have a body or an exception specification yet, so it 13741 // needs to be done somewhere else. 13742 } 13743 13744 namespace { 13745 /// An abstract base class for all helper classes used in building the 13746 // copy/move operators. These classes serve as factory functions and help us 13747 // avoid using the same Expr* in the AST twice. 13748 class ExprBuilder { 13749 ExprBuilder(const ExprBuilder&) = delete; 13750 ExprBuilder &operator=(const ExprBuilder&) = delete; 13751 13752 protected: 13753 static Expr *assertNotNull(Expr *E) { 13754 assert(E && "Expression construction must not fail."); 13755 return E; 13756 } 13757 13758 public: 13759 ExprBuilder() {} 13760 virtual ~ExprBuilder() {} 13761 13762 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 13763 }; 13764 13765 class RefBuilder: public ExprBuilder { 13766 VarDecl *Var; 13767 QualType VarType; 13768 13769 public: 13770 Expr *build(Sema &S, SourceLocation Loc) const override { 13771 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 13772 } 13773 13774 RefBuilder(VarDecl *Var, QualType VarType) 13775 : Var(Var), VarType(VarType) {} 13776 }; 13777 13778 class ThisBuilder: public ExprBuilder { 13779 public: 13780 Expr *build(Sema &S, SourceLocation Loc) const override { 13781 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 13782 } 13783 }; 13784 13785 class CastBuilder: public ExprBuilder { 13786 const ExprBuilder &Builder; 13787 QualType Type; 13788 ExprValueKind Kind; 13789 const CXXCastPath &Path; 13790 13791 public: 13792 Expr *build(Sema &S, SourceLocation Loc) const override { 13793 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 13794 CK_UncheckedDerivedToBase, Kind, 13795 &Path).get()); 13796 } 13797 13798 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 13799 const CXXCastPath &Path) 13800 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 13801 }; 13802 13803 class DerefBuilder: public ExprBuilder { 13804 const ExprBuilder &Builder; 13805 13806 public: 13807 Expr *build(Sema &S, SourceLocation Loc) const override { 13808 return assertNotNull( 13809 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 13810 } 13811 13812 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13813 }; 13814 13815 class MemberBuilder: public ExprBuilder { 13816 const ExprBuilder &Builder; 13817 QualType Type; 13818 CXXScopeSpec SS; 13819 bool IsArrow; 13820 LookupResult &MemberLookup; 13821 13822 public: 13823 Expr *build(Sema &S, SourceLocation Loc) const override { 13824 return assertNotNull(S.BuildMemberReferenceExpr( 13825 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 13826 nullptr, MemberLookup, nullptr, nullptr).get()); 13827 } 13828 13829 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 13830 LookupResult &MemberLookup) 13831 : Builder(Builder), Type(Type), IsArrow(IsArrow), 13832 MemberLookup(MemberLookup) {} 13833 }; 13834 13835 class MoveCastBuilder: public ExprBuilder { 13836 const ExprBuilder &Builder; 13837 13838 public: 13839 Expr *build(Sema &S, SourceLocation Loc) const override { 13840 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 13841 } 13842 13843 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13844 }; 13845 13846 class LvalueConvBuilder: public ExprBuilder { 13847 const ExprBuilder &Builder; 13848 13849 public: 13850 Expr *build(Sema &S, SourceLocation Loc) const override { 13851 return assertNotNull( 13852 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 13853 } 13854 13855 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13856 }; 13857 13858 class SubscriptBuilder: public ExprBuilder { 13859 const ExprBuilder &Base; 13860 const ExprBuilder &Index; 13861 13862 public: 13863 Expr *build(Sema &S, SourceLocation Loc) const override { 13864 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 13865 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 13866 } 13867 13868 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 13869 : Base(Base), Index(Index) {} 13870 }; 13871 13872 } // end anonymous namespace 13873 13874 /// When generating a defaulted copy or move assignment operator, if a field 13875 /// should be copied with __builtin_memcpy rather than via explicit assignments, 13876 /// do so. This optimization only applies for arrays of scalars, and for arrays 13877 /// of class type where the selected copy/move-assignment operator is trivial. 13878 static StmtResult 13879 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 13880 const ExprBuilder &ToB, const ExprBuilder &FromB) { 13881 // Compute the size of the memory buffer to be copied. 13882 QualType SizeType = S.Context.getSizeType(); 13883 llvm::APInt Size(S.Context.getTypeSize(SizeType), 13884 S.Context.getTypeSizeInChars(T).getQuantity()); 13885 13886 // Take the address of the field references for "from" and "to". We 13887 // directly construct UnaryOperators here because semantic analysis 13888 // does not permit us to take the address of an xvalue. 13889 Expr *From = FromB.build(S, Loc); 13890 From = UnaryOperator::Create( 13891 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()), 13892 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13893 Expr *To = ToB.build(S, Loc); 13894 To = UnaryOperator::Create( 13895 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()), 13896 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13897 13898 const Type *E = T->getBaseElementTypeUnsafe(); 13899 bool NeedsCollectableMemCpy = 13900 E->isRecordType() && 13901 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 13902 13903 // Create a reference to the __builtin_objc_memmove_collectable function 13904 StringRef MemCpyName = NeedsCollectableMemCpy ? 13905 "__builtin_objc_memmove_collectable" : 13906 "__builtin_memcpy"; 13907 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 13908 Sema::LookupOrdinaryName); 13909 S.LookupName(R, S.TUScope, true); 13910 13911 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 13912 if (!MemCpy) 13913 // Something went horribly wrong earlier, and we will have complained 13914 // about it. 13915 return StmtError(); 13916 13917 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 13918 VK_PRValue, Loc, nullptr); 13919 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 13920 13921 Expr *CallArgs[] = { 13922 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 13923 }; 13924 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 13925 Loc, CallArgs, Loc); 13926 13927 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 13928 return Call.getAs<Stmt>(); 13929 } 13930 13931 /// Builds a statement that copies/moves the given entity from \p From to 13932 /// \c To. 13933 /// 13934 /// This routine is used to copy/move the members of a class with an 13935 /// implicitly-declared copy/move assignment operator. When the entities being 13936 /// copied are arrays, this routine builds for loops to copy them. 13937 /// 13938 /// \param S The Sema object used for type-checking. 13939 /// 13940 /// \param Loc The location where the implicit copy/move is being generated. 13941 /// 13942 /// \param T The type of the expressions being copied/moved. Both expressions 13943 /// must have this type. 13944 /// 13945 /// \param To The expression we are copying/moving to. 13946 /// 13947 /// \param From The expression we are copying/moving from. 13948 /// 13949 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 13950 /// Otherwise, it's a non-static member subobject. 13951 /// 13952 /// \param Copying Whether we're copying or moving. 13953 /// 13954 /// \param Depth Internal parameter recording the depth of the recursion. 13955 /// 13956 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 13957 /// if a memcpy should be used instead. 13958 static StmtResult 13959 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 13960 const ExprBuilder &To, const ExprBuilder &From, 13961 bool CopyingBaseSubobject, bool Copying, 13962 unsigned Depth = 0) { 13963 // C++11 [class.copy]p28: 13964 // Each subobject is assigned in the manner appropriate to its type: 13965 // 13966 // - if the subobject is of class type, as if by a call to operator= with 13967 // the subobject as the object expression and the corresponding 13968 // subobject of x as a single function argument (as if by explicit 13969 // qualification; that is, ignoring any possible virtual overriding 13970 // functions in more derived classes); 13971 // 13972 // C++03 [class.copy]p13: 13973 // - if the subobject is of class type, the copy assignment operator for 13974 // the class is used (as if by explicit qualification; that is, 13975 // ignoring any possible virtual overriding functions in more derived 13976 // classes); 13977 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 13978 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 13979 13980 // Look for operator=. 13981 DeclarationName Name 13982 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13983 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 13984 S.LookupQualifiedName(OpLookup, ClassDecl, false); 13985 13986 // Prior to C++11, filter out any result that isn't a copy/move-assignment 13987 // operator. 13988 if (!S.getLangOpts().CPlusPlus11) { 13989 LookupResult::Filter F = OpLookup.makeFilter(); 13990 while (F.hasNext()) { 13991 NamedDecl *D = F.next(); 13992 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 13993 if (Method->isCopyAssignmentOperator() || 13994 (!Copying && Method->isMoveAssignmentOperator())) 13995 continue; 13996 13997 F.erase(); 13998 } 13999 F.done(); 14000 } 14001 14002 // Suppress the protected check (C++ [class.protected]) for each of the 14003 // assignment operators we found. This strange dance is required when 14004 // we're assigning via a base classes's copy-assignment operator. To 14005 // ensure that we're getting the right base class subobject (without 14006 // ambiguities), we need to cast "this" to that subobject type; to 14007 // ensure that we don't go through the virtual call mechanism, we need 14008 // to qualify the operator= name with the base class (see below). However, 14009 // this means that if the base class has a protected copy assignment 14010 // operator, the protected member access check will fail. So, we 14011 // rewrite "protected" access to "public" access in this case, since we 14012 // know by construction that we're calling from a derived class. 14013 if (CopyingBaseSubobject) { 14014 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 14015 L != LEnd; ++L) { 14016 if (L.getAccess() == AS_protected) 14017 L.setAccess(AS_public); 14018 } 14019 } 14020 14021 // Create the nested-name-specifier that will be used to qualify the 14022 // reference to operator=; this is required to suppress the virtual 14023 // call mechanism. 14024 CXXScopeSpec SS; 14025 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 14026 SS.MakeTrivial(S.Context, 14027 NestedNameSpecifier::Create(S.Context, nullptr, false, 14028 CanonicalT), 14029 Loc); 14030 14031 // Create the reference to operator=. 14032 ExprResult OpEqualRef 14033 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 14034 SS, /*TemplateKWLoc=*/SourceLocation(), 14035 /*FirstQualifierInScope=*/nullptr, 14036 OpLookup, 14037 /*TemplateArgs=*/nullptr, /*S*/nullptr, 14038 /*SuppressQualifierCheck=*/true); 14039 if (OpEqualRef.isInvalid()) 14040 return StmtError(); 14041 14042 // Build the call to the assignment operator. 14043 14044 Expr *FromInst = From.build(S, Loc); 14045 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 14046 OpEqualRef.getAs<Expr>(), 14047 Loc, FromInst, Loc); 14048 if (Call.isInvalid()) 14049 return StmtError(); 14050 14051 // If we built a call to a trivial 'operator=' while copying an array, 14052 // bail out. We'll replace the whole shebang with a memcpy. 14053 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 14054 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 14055 return StmtResult((Stmt*)nullptr); 14056 14057 // Convert to an expression-statement, and clean up any produced 14058 // temporaries. 14059 return S.ActOnExprStmt(Call); 14060 } 14061 14062 // - if the subobject is of scalar type, the built-in assignment 14063 // operator is used. 14064 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 14065 if (!ArrayTy) { 14066 ExprResult Assignment = S.CreateBuiltinBinOp( 14067 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 14068 if (Assignment.isInvalid()) 14069 return StmtError(); 14070 return S.ActOnExprStmt(Assignment); 14071 } 14072 14073 // - if the subobject is an array, each element is assigned, in the 14074 // manner appropriate to the element type; 14075 14076 // Construct a loop over the array bounds, e.g., 14077 // 14078 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 14079 // 14080 // that will copy each of the array elements. 14081 QualType SizeType = S.Context.getSizeType(); 14082 14083 // Create the iteration variable. 14084 IdentifierInfo *IterationVarName = nullptr; 14085 { 14086 SmallString<8> Str; 14087 llvm::raw_svector_ostream OS(Str); 14088 OS << "__i" << Depth; 14089 IterationVarName = &S.Context.Idents.get(OS.str()); 14090 } 14091 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 14092 IterationVarName, SizeType, 14093 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 14094 SC_None); 14095 14096 // Initialize the iteration variable to zero. 14097 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 14098 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 14099 14100 // Creates a reference to the iteration variable. 14101 RefBuilder IterationVarRef(IterationVar, SizeType); 14102 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 14103 14104 // Create the DeclStmt that holds the iteration variable. 14105 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 14106 14107 // Subscript the "from" and "to" expressions with the iteration variable. 14108 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 14109 MoveCastBuilder FromIndexMove(FromIndexCopy); 14110 const ExprBuilder *FromIndex; 14111 if (Copying) 14112 FromIndex = &FromIndexCopy; 14113 else 14114 FromIndex = &FromIndexMove; 14115 14116 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 14117 14118 // Build the copy/move for an individual element of the array. 14119 StmtResult Copy = 14120 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 14121 ToIndex, *FromIndex, CopyingBaseSubobject, 14122 Copying, Depth + 1); 14123 // Bail out if copying fails or if we determined that we should use memcpy. 14124 if (Copy.isInvalid() || !Copy.get()) 14125 return Copy; 14126 14127 // Create the comparison against the array bound. 14128 llvm::APInt Upper 14129 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 14130 Expr *Comparison = BinaryOperator::Create( 14131 S.Context, IterationVarRefRVal.build(S, Loc), 14132 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE, 14133 S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc, 14134 S.CurFPFeatureOverrides()); 14135 14136 // Create the pre-increment of the iteration variable. We can determine 14137 // whether the increment will overflow based on the value of the array 14138 // bound. 14139 Expr *Increment = UnaryOperator::Create( 14140 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue, 14141 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides()); 14142 14143 // Construct the loop that copies all elements of this array. 14144 return S.ActOnForStmt( 14145 Loc, Loc, InitStmt, 14146 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 14147 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 14148 } 14149 14150 static StmtResult 14151 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 14152 const ExprBuilder &To, const ExprBuilder &From, 14153 bool CopyingBaseSubobject, bool Copying) { 14154 // Maybe we should use a memcpy? 14155 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 14156 T.isTriviallyCopyableType(S.Context)) 14157 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 14158 14159 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 14160 CopyingBaseSubobject, 14161 Copying, 0)); 14162 14163 // If we ended up picking a trivial assignment operator for an array of a 14164 // non-trivially-copyable class type, just emit a memcpy. 14165 if (!Result.isInvalid() && !Result.get()) 14166 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 14167 14168 return Result; 14169 } 14170 14171 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 14172 // Note: The following rules are largely analoguous to the copy 14173 // constructor rules. Note that virtual bases are not taken into account 14174 // for determining the argument type of the operator. Note also that 14175 // operators taking an object instead of a reference are allowed. 14176 assert(ClassDecl->needsImplicitCopyAssignment()); 14177 14178 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 14179 if (DSM.isAlreadyBeingDeclared()) 14180 return nullptr; 14181 14182 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14183 LangAS AS = getDefaultCXXMethodAddrSpace(); 14184 if (AS != LangAS::Default) 14185 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14186 QualType RetType = Context.getLValueReferenceType(ArgType); 14187 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 14188 if (Const) 14189 ArgType = ArgType.withConst(); 14190 14191 ArgType = Context.getLValueReferenceType(ArgType); 14192 14193 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14194 CXXCopyAssignment, 14195 Const); 14196 14197 // An implicitly-declared copy assignment operator is an inline public 14198 // member of its class. 14199 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14200 SourceLocation ClassLoc = ClassDecl->getLocation(); 14201 DeclarationNameInfo NameInfo(Name, ClassLoc); 14202 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 14203 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14204 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14205 getCurFPFeatures().isFPConstrained(), 14206 /*isInline=*/true, 14207 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14208 SourceLocation()); 14209 CopyAssignment->setAccess(AS_public); 14210 CopyAssignment->setDefaulted(); 14211 CopyAssignment->setImplicit(); 14212 14213 if (getLangOpts().CUDA) { 14214 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 14215 CopyAssignment, 14216 /* ConstRHS */ Const, 14217 /* Diagnose */ false); 14218 } 14219 14220 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 14221 14222 // Add the parameter to the operator. 14223 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 14224 ClassLoc, ClassLoc, 14225 /*Id=*/nullptr, ArgType, 14226 /*TInfo=*/nullptr, SC_None, 14227 nullptr); 14228 CopyAssignment->setParams(FromParam); 14229 14230 CopyAssignment->setTrivial( 14231 ClassDecl->needsOverloadResolutionForCopyAssignment() 14232 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 14233 : ClassDecl->hasTrivialCopyAssignment()); 14234 14235 // Note that we have added this copy-assignment operator. 14236 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 14237 14238 Scope *S = getScopeForContext(ClassDecl); 14239 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 14240 14241 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) { 14242 ClassDecl->setImplicitCopyAssignmentIsDeleted(); 14243 SetDeclDeleted(CopyAssignment, ClassLoc); 14244 } 14245 14246 if (S) 14247 PushOnScopeChains(CopyAssignment, S, false); 14248 ClassDecl->addDecl(CopyAssignment); 14249 14250 return CopyAssignment; 14251 } 14252 14253 /// Diagnose an implicit copy operation for a class which is odr-used, but 14254 /// which is deprecated because the class has a user-declared copy constructor, 14255 /// copy assignment operator, or destructor. 14256 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 14257 assert(CopyOp->isImplicit()); 14258 14259 CXXRecordDecl *RD = CopyOp->getParent(); 14260 CXXMethodDecl *UserDeclaredOperation = nullptr; 14261 14262 // In Microsoft mode, assignment operations don't affect constructors and 14263 // vice versa. 14264 if (RD->hasUserDeclaredDestructor()) { 14265 UserDeclaredOperation = RD->getDestructor(); 14266 } else if (!isa<CXXConstructorDecl>(CopyOp) && 14267 RD->hasUserDeclaredCopyConstructor() && 14268 !S.getLangOpts().MSVCCompat) { 14269 // Find any user-declared copy constructor. 14270 for (auto *I : RD->ctors()) { 14271 if (I->isCopyConstructor()) { 14272 UserDeclaredOperation = I; 14273 break; 14274 } 14275 } 14276 assert(UserDeclaredOperation); 14277 } else if (isa<CXXConstructorDecl>(CopyOp) && 14278 RD->hasUserDeclaredCopyAssignment() && 14279 !S.getLangOpts().MSVCCompat) { 14280 // Find any user-declared move assignment operator. 14281 for (auto *I : RD->methods()) { 14282 if (I->isCopyAssignmentOperator()) { 14283 UserDeclaredOperation = I; 14284 break; 14285 } 14286 } 14287 assert(UserDeclaredOperation); 14288 } 14289 14290 if (UserDeclaredOperation) { 14291 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided(); 14292 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation); 14293 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp); 14294 unsigned DiagID = 14295 (UDOIsUserProvided && UDOIsDestructor) 14296 ? diag::warn_deprecated_copy_with_user_provided_dtor 14297 : (UDOIsUserProvided && !UDOIsDestructor) 14298 ? diag::warn_deprecated_copy_with_user_provided_copy 14299 : (!UDOIsUserProvided && UDOIsDestructor) 14300 ? diag::warn_deprecated_copy_with_dtor 14301 : diag::warn_deprecated_copy; 14302 S.Diag(UserDeclaredOperation->getLocation(), DiagID) 14303 << RD << IsCopyAssignment; 14304 } 14305 } 14306 14307 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 14308 CXXMethodDecl *CopyAssignOperator) { 14309 assert((CopyAssignOperator->isDefaulted() && 14310 CopyAssignOperator->isOverloadedOperator() && 14311 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 14312 !CopyAssignOperator->doesThisDeclarationHaveABody() && 14313 !CopyAssignOperator->isDeleted()) && 14314 "DefineImplicitCopyAssignment called for wrong function"); 14315 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 14316 return; 14317 14318 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 14319 if (ClassDecl->isInvalidDecl()) { 14320 CopyAssignOperator->setInvalidDecl(); 14321 return; 14322 } 14323 14324 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 14325 14326 // The exception specification is needed because we are defining the 14327 // function. 14328 ResolveExceptionSpec(CurrentLocation, 14329 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 14330 14331 // Add a context note for diagnostics produced after this point. 14332 Scope.addContextNote(CurrentLocation); 14333 14334 // C++11 [class.copy]p18: 14335 // The [definition of an implicitly declared copy assignment operator] is 14336 // deprecated if the class has a user-declared copy constructor or a 14337 // user-declared destructor. 14338 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 14339 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 14340 14341 // C++0x [class.copy]p30: 14342 // The implicitly-defined or explicitly-defaulted copy assignment operator 14343 // for a non-union class X performs memberwise copy assignment of its 14344 // subobjects. The direct base classes of X are assigned first, in the 14345 // order of their declaration in the base-specifier-list, and then the 14346 // immediate non-static data members of X are assigned, in the order in 14347 // which they were declared in the class definition. 14348 14349 // The statements that form the synthesized function body. 14350 SmallVector<Stmt*, 8> Statements; 14351 14352 // The parameter for the "other" object, which we are copying from. 14353 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 14354 Qualifiers OtherQuals = Other->getType().getQualifiers(); 14355 QualType OtherRefType = Other->getType(); 14356 if (const LValueReferenceType *OtherRef 14357 = OtherRefType->getAs<LValueReferenceType>()) { 14358 OtherRefType = OtherRef->getPointeeType(); 14359 OtherQuals = OtherRefType.getQualifiers(); 14360 } 14361 14362 // Our location for everything implicitly-generated. 14363 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 14364 ? CopyAssignOperator->getEndLoc() 14365 : CopyAssignOperator->getLocation(); 14366 14367 // Builds a DeclRefExpr for the "other" object. 14368 RefBuilder OtherRef(Other, OtherRefType); 14369 14370 // Builds the "this" pointer. 14371 ThisBuilder This; 14372 14373 // Assign base classes. 14374 bool Invalid = false; 14375 for (auto &Base : ClassDecl->bases()) { 14376 // Form the assignment: 14377 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 14378 QualType BaseType = Base.getType().getUnqualifiedType(); 14379 if (!BaseType->isRecordType()) { 14380 Invalid = true; 14381 continue; 14382 } 14383 14384 CXXCastPath BasePath; 14385 BasePath.push_back(&Base); 14386 14387 // Construct the "from" expression, which is an implicit cast to the 14388 // appropriately-qualified base type. 14389 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 14390 VK_LValue, BasePath); 14391 14392 // Dereference "this". 14393 DerefBuilder DerefThis(This); 14394 CastBuilder To(DerefThis, 14395 Context.getQualifiedType( 14396 BaseType, CopyAssignOperator->getMethodQualifiers()), 14397 VK_LValue, BasePath); 14398 14399 // Build the copy. 14400 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 14401 To, From, 14402 /*CopyingBaseSubobject=*/true, 14403 /*Copying=*/true); 14404 if (Copy.isInvalid()) { 14405 CopyAssignOperator->setInvalidDecl(); 14406 return; 14407 } 14408 14409 // Success! Record the copy. 14410 Statements.push_back(Copy.getAs<Expr>()); 14411 } 14412 14413 // Assign non-static members. 14414 for (auto *Field : ClassDecl->fields()) { 14415 // FIXME: We should form some kind of AST representation for the implied 14416 // memcpy in a union copy operation. 14417 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14418 continue; 14419 14420 if (Field->isInvalidDecl()) { 14421 Invalid = true; 14422 continue; 14423 } 14424 14425 // Check for members of reference type; we can't copy those. 14426 if (Field->getType()->isReferenceType()) { 14427 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14428 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14429 Diag(Field->getLocation(), diag::note_declared_at); 14430 Invalid = true; 14431 continue; 14432 } 14433 14434 // Check for members of const-qualified, non-class type. 14435 QualType BaseType = Context.getBaseElementType(Field->getType()); 14436 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14437 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14438 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14439 Diag(Field->getLocation(), diag::note_declared_at); 14440 Invalid = true; 14441 continue; 14442 } 14443 14444 // Suppress assigning zero-width bitfields. 14445 if (Field->isZeroLengthBitField(Context)) 14446 continue; 14447 14448 QualType FieldType = Field->getType().getNonReferenceType(); 14449 if (FieldType->isIncompleteArrayType()) { 14450 assert(ClassDecl->hasFlexibleArrayMember() && 14451 "Incomplete array type is not valid"); 14452 continue; 14453 } 14454 14455 // Build references to the field in the object we're copying from and to. 14456 CXXScopeSpec SS; // Intentionally empty 14457 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14458 LookupMemberName); 14459 MemberLookup.addDecl(Field); 14460 MemberLookup.resolveKind(); 14461 14462 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 14463 14464 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 14465 14466 // Build the copy of this field. 14467 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 14468 To, From, 14469 /*CopyingBaseSubobject=*/false, 14470 /*Copying=*/true); 14471 if (Copy.isInvalid()) { 14472 CopyAssignOperator->setInvalidDecl(); 14473 return; 14474 } 14475 14476 // Success! Record the copy. 14477 Statements.push_back(Copy.getAs<Stmt>()); 14478 } 14479 14480 if (!Invalid) { 14481 // Add a "return *this;" 14482 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14483 14484 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14485 if (Return.isInvalid()) 14486 Invalid = true; 14487 else 14488 Statements.push_back(Return.getAs<Stmt>()); 14489 } 14490 14491 if (Invalid) { 14492 CopyAssignOperator->setInvalidDecl(); 14493 return; 14494 } 14495 14496 StmtResult Body; 14497 { 14498 CompoundScopeRAII CompoundScope(*this); 14499 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14500 /*isStmtExpr=*/false); 14501 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14502 } 14503 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 14504 CopyAssignOperator->markUsed(Context); 14505 14506 if (ASTMutationListener *L = getASTMutationListener()) { 14507 L->CompletedImplicitDefinition(CopyAssignOperator); 14508 } 14509 } 14510 14511 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 14512 assert(ClassDecl->needsImplicitMoveAssignment()); 14513 14514 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 14515 if (DSM.isAlreadyBeingDeclared()) 14516 return nullptr; 14517 14518 // Note: The following rules are largely analoguous to the move 14519 // constructor rules. 14520 14521 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14522 LangAS AS = getDefaultCXXMethodAddrSpace(); 14523 if (AS != LangAS::Default) 14524 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14525 QualType RetType = Context.getLValueReferenceType(ArgType); 14526 ArgType = Context.getRValueReferenceType(ArgType); 14527 14528 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14529 CXXMoveAssignment, 14530 false); 14531 14532 // An implicitly-declared move assignment operator is an inline public 14533 // member of its class. 14534 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14535 SourceLocation ClassLoc = ClassDecl->getLocation(); 14536 DeclarationNameInfo NameInfo(Name, ClassLoc); 14537 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 14538 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14539 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14540 getCurFPFeatures().isFPConstrained(), 14541 /*isInline=*/true, 14542 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14543 SourceLocation()); 14544 MoveAssignment->setAccess(AS_public); 14545 MoveAssignment->setDefaulted(); 14546 MoveAssignment->setImplicit(); 14547 14548 if (getLangOpts().CUDA) { 14549 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 14550 MoveAssignment, 14551 /* ConstRHS */ false, 14552 /* Diagnose */ false); 14553 } 14554 14555 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType); 14556 14557 // Add the parameter to the operator. 14558 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 14559 ClassLoc, ClassLoc, 14560 /*Id=*/nullptr, ArgType, 14561 /*TInfo=*/nullptr, SC_None, 14562 nullptr); 14563 MoveAssignment->setParams(FromParam); 14564 14565 MoveAssignment->setTrivial( 14566 ClassDecl->needsOverloadResolutionForMoveAssignment() 14567 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 14568 : ClassDecl->hasTrivialMoveAssignment()); 14569 14570 // Note that we have added this copy-assignment operator. 14571 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 14572 14573 Scope *S = getScopeForContext(ClassDecl); 14574 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 14575 14576 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 14577 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 14578 SetDeclDeleted(MoveAssignment, ClassLoc); 14579 } 14580 14581 if (S) 14582 PushOnScopeChains(MoveAssignment, S, false); 14583 ClassDecl->addDecl(MoveAssignment); 14584 14585 return MoveAssignment; 14586 } 14587 14588 /// Check if we're implicitly defining a move assignment operator for a class 14589 /// with virtual bases. Such a move assignment might move-assign the virtual 14590 /// base multiple times. 14591 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 14592 SourceLocation CurrentLocation) { 14593 assert(!Class->isDependentContext() && "should not define dependent move"); 14594 14595 // Only a virtual base could get implicitly move-assigned multiple times. 14596 // Only a non-trivial move assignment can observe this. We only want to 14597 // diagnose if we implicitly define an assignment operator that assigns 14598 // two base classes, both of which move-assign the same virtual base. 14599 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 14600 Class->getNumBases() < 2) 14601 return; 14602 14603 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 14604 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 14605 VBaseMap VBases; 14606 14607 for (auto &BI : Class->bases()) { 14608 Worklist.push_back(&BI); 14609 while (!Worklist.empty()) { 14610 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 14611 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 14612 14613 // If the base has no non-trivial move assignment operators, 14614 // we don't care about moves from it. 14615 if (!Base->hasNonTrivialMoveAssignment()) 14616 continue; 14617 14618 // If there's nothing virtual here, skip it. 14619 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 14620 continue; 14621 14622 // If we're not actually going to call a move assignment for this base, 14623 // or the selected move assignment is trivial, skip it. 14624 Sema::SpecialMemberOverloadResult SMOR = 14625 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 14626 /*ConstArg*/false, /*VolatileArg*/false, 14627 /*RValueThis*/true, /*ConstThis*/false, 14628 /*VolatileThis*/false); 14629 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 14630 !SMOR.getMethod()->isMoveAssignmentOperator()) 14631 continue; 14632 14633 if (BaseSpec->isVirtual()) { 14634 // We're going to move-assign this virtual base, and its move 14635 // assignment operator is not trivial. If this can happen for 14636 // multiple distinct direct bases of Class, diagnose it. (If it 14637 // only happens in one base, we'll diagnose it when synthesizing 14638 // that base class's move assignment operator.) 14639 CXXBaseSpecifier *&Existing = 14640 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 14641 .first->second; 14642 if (Existing && Existing != &BI) { 14643 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 14644 << Class << Base; 14645 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 14646 << (Base->getCanonicalDecl() == 14647 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14648 << Base << Existing->getType() << Existing->getSourceRange(); 14649 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 14650 << (Base->getCanonicalDecl() == 14651 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14652 << Base << BI.getType() << BaseSpec->getSourceRange(); 14653 14654 // Only diagnose each vbase once. 14655 Existing = nullptr; 14656 } 14657 } else { 14658 // Only walk over bases that have defaulted move assignment operators. 14659 // We assume that any user-provided move assignment operator handles 14660 // the multiple-moves-of-vbase case itself somehow. 14661 if (!SMOR.getMethod()->isDefaulted()) 14662 continue; 14663 14664 // We're going to move the base classes of Base. Add them to the list. 14665 for (auto &BI : Base->bases()) 14666 Worklist.push_back(&BI); 14667 } 14668 } 14669 } 14670 } 14671 14672 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 14673 CXXMethodDecl *MoveAssignOperator) { 14674 assert((MoveAssignOperator->isDefaulted() && 14675 MoveAssignOperator->isOverloadedOperator() && 14676 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 14677 !MoveAssignOperator->doesThisDeclarationHaveABody() && 14678 !MoveAssignOperator->isDeleted()) && 14679 "DefineImplicitMoveAssignment called for wrong function"); 14680 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 14681 return; 14682 14683 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 14684 if (ClassDecl->isInvalidDecl()) { 14685 MoveAssignOperator->setInvalidDecl(); 14686 return; 14687 } 14688 14689 // C++0x [class.copy]p28: 14690 // The implicitly-defined or move assignment operator for a non-union class 14691 // X performs memberwise move assignment of its subobjects. The direct base 14692 // classes of X are assigned first, in the order of their declaration in the 14693 // base-specifier-list, and then the immediate non-static data members of X 14694 // are assigned, in the order in which they were declared in the class 14695 // definition. 14696 14697 // Issue a warning if our implicit move assignment operator will move 14698 // from a virtual base more than once. 14699 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 14700 14701 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 14702 14703 // The exception specification is needed because we are defining the 14704 // function. 14705 ResolveExceptionSpec(CurrentLocation, 14706 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 14707 14708 // Add a context note for diagnostics produced after this point. 14709 Scope.addContextNote(CurrentLocation); 14710 14711 // The statements that form the synthesized function body. 14712 SmallVector<Stmt*, 8> Statements; 14713 14714 // The parameter for the "other" object, which we are move from. 14715 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 14716 QualType OtherRefType = 14717 Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); 14718 14719 // Our location for everything implicitly-generated. 14720 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 14721 ? MoveAssignOperator->getEndLoc() 14722 : MoveAssignOperator->getLocation(); 14723 14724 // Builds a reference to the "other" object. 14725 RefBuilder OtherRef(Other, OtherRefType); 14726 // Cast to rvalue. 14727 MoveCastBuilder MoveOther(OtherRef); 14728 14729 // Builds the "this" pointer. 14730 ThisBuilder This; 14731 14732 // Assign base classes. 14733 bool Invalid = false; 14734 for (auto &Base : ClassDecl->bases()) { 14735 // C++11 [class.copy]p28: 14736 // It is unspecified whether subobjects representing virtual base classes 14737 // are assigned more than once by the implicitly-defined copy assignment 14738 // operator. 14739 // FIXME: Do not assign to a vbase that will be assigned by some other base 14740 // class. For a move-assignment, this can result in the vbase being moved 14741 // multiple times. 14742 14743 // Form the assignment: 14744 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 14745 QualType BaseType = Base.getType().getUnqualifiedType(); 14746 if (!BaseType->isRecordType()) { 14747 Invalid = true; 14748 continue; 14749 } 14750 14751 CXXCastPath BasePath; 14752 BasePath.push_back(&Base); 14753 14754 // Construct the "from" expression, which is an implicit cast to the 14755 // appropriately-qualified base type. 14756 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 14757 14758 // Dereference "this". 14759 DerefBuilder DerefThis(This); 14760 14761 // Implicitly cast "this" to the appropriately-qualified base type. 14762 CastBuilder To(DerefThis, 14763 Context.getQualifiedType( 14764 BaseType, MoveAssignOperator->getMethodQualifiers()), 14765 VK_LValue, BasePath); 14766 14767 // Build the move. 14768 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 14769 To, From, 14770 /*CopyingBaseSubobject=*/true, 14771 /*Copying=*/false); 14772 if (Move.isInvalid()) { 14773 MoveAssignOperator->setInvalidDecl(); 14774 return; 14775 } 14776 14777 // Success! Record the move. 14778 Statements.push_back(Move.getAs<Expr>()); 14779 } 14780 14781 // Assign non-static members. 14782 for (auto *Field : ClassDecl->fields()) { 14783 // FIXME: We should form some kind of AST representation for the implied 14784 // memcpy in a union copy operation. 14785 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14786 continue; 14787 14788 if (Field->isInvalidDecl()) { 14789 Invalid = true; 14790 continue; 14791 } 14792 14793 // Check for members of reference type; we can't move those. 14794 if (Field->getType()->isReferenceType()) { 14795 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14796 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14797 Diag(Field->getLocation(), diag::note_declared_at); 14798 Invalid = true; 14799 continue; 14800 } 14801 14802 // Check for members of const-qualified, non-class type. 14803 QualType BaseType = Context.getBaseElementType(Field->getType()); 14804 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14805 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14806 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14807 Diag(Field->getLocation(), diag::note_declared_at); 14808 Invalid = true; 14809 continue; 14810 } 14811 14812 // Suppress assigning zero-width bitfields. 14813 if (Field->isZeroLengthBitField(Context)) 14814 continue; 14815 14816 QualType FieldType = Field->getType().getNonReferenceType(); 14817 if (FieldType->isIncompleteArrayType()) { 14818 assert(ClassDecl->hasFlexibleArrayMember() && 14819 "Incomplete array type is not valid"); 14820 continue; 14821 } 14822 14823 // Build references to the field in the object we're copying from and to. 14824 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14825 LookupMemberName); 14826 MemberLookup.addDecl(Field); 14827 MemberLookup.resolveKind(); 14828 MemberBuilder From(MoveOther, OtherRefType, 14829 /*IsArrow=*/false, MemberLookup); 14830 MemberBuilder To(This, getCurrentThisType(), 14831 /*IsArrow=*/true, MemberLookup); 14832 14833 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 14834 "Member reference with rvalue base must be rvalue except for reference " 14835 "members, which aren't allowed for move assignment."); 14836 14837 // Build the move of this field. 14838 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 14839 To, From, 14840 /*CopyingBaseSubobject=*/false, 14841 /*Copying=*/false); 14842 if (Move.isInvalid()) { 14843 MoveAssignOperator->setInvalidDecl(); 14844 return; 14845 } 14846 14847 // Success! Record the copy. 14848 Statements.push_back(Move.getAs<Stmt>()); 14849 } 14850 14851 if (!Invalid) { 14852 // Add a "return *this;" 14853 ExprResult ThisObj = 14854 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14855 14856 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14857 if (Return.isInvalid()) 14858 Invalid = true; 14859 else 14860 Statements.push_back(Return.getAs<Stmt>()); 14861 } 14862 14863 if (Invalid) { 14864 MoveAssignOperator->setInvalidDecl(); 14865 return; 14866 } 14867 14868 StmtResult Body; 14869 { 14870 CompoundScopeRAII CompoundScope(*this); 14871 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14872 /*isStmtExpr=*/false); 14873 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14874 } 14875 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 14876 MoveAssignOperator->markUsed(Context); 14877 14878 if (ASTMutationListener *L = getASTMutationListener()) { 14879 L->CompletedImplicitDefinition(MoveAssignOperator); 14880 } 14881 } 14882 14883 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 14884 CXXRecordDecl *ClassDecl) { 14885 // C++ [class.copy]p4: 14886 // If the class definition does not explicitly declare a copy 14887 // constructor, one is declared implicitly. 14888 assert(ClassDecl->needsImplicitCopyConstructor()); 14889 14890 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 14891 if (DSM.isAlreadyBeingDeclared()) 14892 return nullptr; 14893 14894 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14895 QualType ArgType = ClassType; 14896 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 14897 if (Const) 14898 ArgType = ArgType.withConst(); 14899 14900 LangAS AS = getDefaultCXXMethodAddrSpace(); 14901 if (AS != LangAS::Default) 14902 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14903 14904 ArgType = Context.getLValueReferenceType(ArgType); 14905 14906 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14907 CXXCopyConstructor, 14908 Const); 14909 14910 DeclarationName Name 14911 = Context.DeclarationNames.getCXXConstructorName( 14912 Context.getCanonicalType(ClassType)); 14913 SourceLocation ClassLoc = ClassDecl->getLocation(); 14914 DeclarationNameInfo NameInfo(Name, ClassLoc); 14915 14916 // An implicitly-declared copy constructor is an inline public 14917 // member of its class. 14918 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 14919 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14920 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 14921 /*isInline=*/true, 14922 /*isImplicitlyDeclared=*/true, 14923 Constexpr ? ConstexprSpecKind::Constexpr 14924 : ConstexprSpecKind::Unspecified); 14925 CopyConstructor->setAccess(AS_public); 14926 CopyConstructor->setDefaulted(); 14927 14928 if (getLangOpts().CUDA) { 14929 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 14930 CopyConstructor, 14931 /* ConstRHS */ Const, 14932 /* Diagnose */ false); 14933 } 14934 14935 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 14936 14937 // During template instantiation of special member functions we need a 14938 // reliable TypeSourceInfo for the parameter types in order to allow functions 14939 // to be substituted. 14940 TypeSourceInfo *TSI = nullptr; 14941 if (inTemplateInstantiation() && ClassDecl->isLambda()) 14942 TSI = Context.getTrivialTypeSourceInfo(ArgType); 14943 14944 // Add the parameter to the constructor. 14945 ParmVarDecl *FromParam = 14946 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc, 14947 /*IdentifierInfo=*/nullptr, ArgType, 14948 /*TInfo=*/TSI, SC_None, nullptr); 14949 CopyConstructor->setParams(FromParam); 14950 14951 CopyConstructor->setTrivial( 14952 ClassDecl->needsOverloadResolutionForCopyConstructor() 14953 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 14954 : ClassDecl->hasTrivialCopyConstructor()); 14955 14956 CopyConstructor->setTrivialForCall( 14957 ClassDecl->hasAttr<TrivialABIAttr>() || 14958 (ClassDecl->needsOverloadResolutionForCopyConstructor() 14959 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 14960 TAH_ConsiderTrivialABI) 14961 : ClassDecl->hasTrivialCopyConstructorForCall())); 14962 14963 // Note that we have declared this constructor. 14964 ++getASTContext().NumImplicitCopyConstructorsDeclared; 14965 14966 Scope *S = getScopeForContext(ClassDecl); 14967 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 14968 14969 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 14970 ClassDecl->setImplicitCopyConstructorIsDeleted(); 14971 SetDeclDeleted(CopyConstructor, ClassLoc); 14972 } 14973 14974 if (S) 14975 PushOnScopeChains(CopyConstructor, S, false); 14976 ClassDecl->addDecl(CopyConstructor); 14977 14978 return CopyConstructor; 14979 } 14980 14981 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 14982 CXXConstructorDecl *CopyConstructor) { 14983 assert((CopyConstructor->isDefaulted() && 14984 CopyConstructor->isCopyConstructor() && 14985 !CopyConstructor->doesThisDeclarationHaveABody() && 14986 !CopyConstructor->isDeleted()) && 14987 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 14988 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 14989 return; 14990 14991 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 14992 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 14993 14994 SynthesizedFunctionScope Scope(*this, CopyConstructor); 14995 14996 // The exception specification is needed because we are defining the 14997 // function. 14998 ResolveExceptionSpec(CurrentLocation, 14999 CopyConstructor->getType()->castAs<FunctionProtoType>()); 15000 MarkVTableUsed(CurrentLocation, ClassDecl); 15001 15002 // Add a context note for diagnostics produced after this point. 15003 Scope.addContextNote(CurrentLocation); 15004 15005 // C++11 [class.copy]p7: 15006 // The [definition of an implicitly declared copy constructor] is 15007 // deprecated if the class has a user-declared copy assignment operator 15008 // or a user-declared destructor. 15009 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 15010 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 15011 15012 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 15013 CopyConstructor->setInvalidDecl(); 15014 } else { 15015 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 15016 ? CopyConstructor->getEndLoc() 15017 : CopyConstructor->getLocation(); 15018 Sema::CompoundScopeRAII CompoundScope(*this); 15019 CopyConstructor->setBody( 15020 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 15021 CopyConstructor->markUsed(Context); 15022 } 15023 15024 if (ASTMutationListener *L = getASTMutationListener()) { 15025 L->CompletedImplicitDefinition(CopyConstructor); 15026 } 15027 } 15028 15029 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 15030 CXXRecordDecl *ClassDecl) { 15031 assert(ClassDecl->needsImplicitMoveConstructor()); 15032 15033 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 15034 if (DSM.isAlreadyBeingDeclared()) 15035 return nullptr; 15036 15037 QualType ClassType = Context.getTypeDeclType(ClassDecl); 15038 15039 QualType ArgType = ClassType; 15040 LangAS AS = getDefaultCXXMethodAddrSpace(); 15041 if (AS != LangAS::Default) 15042 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 15043 ArgType = Context.getRValueReferenceType(ArgType); 15044 15045 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 15046 CXXMoveConstructor, 15047 false); 15048 15049 DeclarationName Name 15050 = Context.DeclarationNames.getCXXConstructorName( 15051 Context.getCanonicalType(ClassType)); 15052 SourceLocation ClassLoc = ClassDecl->getLocation(); 15053 DeclarationNameInfo NameInfo(Name, ClassLoc); 15054 15055 // C++11 [class.copy]p11: 15056 // An implicitly-declared copy/move constructor is an inline public 15057 // member of its class. 15058 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 15059 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 15060 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 15061 /*isInline=*/true, 15062 /*isImplicitlyDeclared=*/true, 15063 Constexpr ? ConstexprSpecKind::Constexpr 15064 : ConstexprSpecKind::Unspecified); 15065 MoveConstructor->setAccess(AS_public); 15066 MoveConstructor->setDefaulted(); 15067 15068 if (getLangOpts().CUDA) { 15069 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 15070 MoveConstructor, 15071 /* ConstRHS */ false, 15072 /* Diagnose */ false); 15073 } 15074 15075 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 15076 15077 // Add the parameter to the constructor. 15078 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 15079 ClassLoc, ClassLoc, 15080 /*IdentifierInfo=*/nullptr, 15081 ArgType, /*TInfo=*/nullptr, 15082 SC_None, nullptr); 15083 MoveConstructor->setParams(FromParam); 15084 15085 MoveConstructor->setTrivial( 15086 ClassDecl->needsOverloadResolutionForMoveConstructor() 15087 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 15088 : ClassDecl->hasTrivialMoveConstructor()); 15089 15090 MoveConstructor->setTrivialForCall( 15091 ClassDecl->hasAttr<TrivialABIAttr>() || 15092 (ClassDecl->needsOverloadResolutionForMoveConstructor() 15093 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 15094 TAH_ConsiderTrivialABI) 15095 : ClassDecl->hasTrivialMoveConstructorForCall())); 15096 15097 // Note that we have declared this constructor. 15098 ++getASTContext().NumImplicitMoveConstructorsDeclared; 15099 15100 Scope *S = getScopeForContext(ClassDecl); 15101 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 15102 15103 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 15104 ClassDecl->setImplicitMoveConstructorIsDeleted(); 15105 SetDeclDeleted(MoveConstructor, ClassLoc); 15106 } 15107 15108 if (S) 15109 PushOnScopeChains(MoveConstructor, S, false); 15110 ClassDecl->addDecl(MoveConstructor); 15111 15112 return MoveConstructor; 15113 } 15114 15115 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 15116 CXXConstructorDecl *MoveConstructor) { 15117 assert((MoveConstructor->isDefaulted() && 15118 MoveConstructor->isMoveConstructor() && 15119 !MoveConstructor->doesThisDeclarationHaveABody() && 15120 !MoveConstructor->isDeleted()) && 15121 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 15122 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 15123 return; 15124 15125 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 15126 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 15127 15128 SynthesizedFunctionScope Scope(*this, MoveConstructor); 15129 15130 // The exception specification is needed because we are defining the 15131 // function. 15132 ResolveExceptionSpec(CurrentLocation, 15133 MoveConstructor->getType()->castAs<FunctionProtoType>()); 15134 MarkVTableUsed(CurrentLocation, ClassDecl); 15135 15136 // Add a context note for diagnostics produced after this point. 15137 Scope.addContextNote(CurrentLocation); 15138 15139 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 15140 MoveConstructor->setInvalidDecl(); 15141 } else { 15142 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 15143 ? MoveConstructor->getEndLoc() 15144 : MoveConstructor->getLocation(); 15145 Sema::CompoundScopeRAII CompoundScope(*this); 15146 MoveConstructor->setBody(ActOnCompoundStmt( 15147 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 15148 MoveConstructor->markUsed(Context); 15149 } 15150 15151 if (ASTMutationListener *L = getASTMutationListener()) { 15152 L->CompletedImplicitDefinition(MoveConstructor); 15153 } 15154 } 15155 15156 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 15157 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 15158 } 15159 15160 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 15161 SourceLocation CurrentLocation, 15162 CXXConversionDecl *Conv) { 15163 SynthesizedFunctionScope Scope(*this, Conv); 15164 assert(!Conv->getReturnType()->isUndeducedType()); 15165 15166 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType(); 15167 CallingConv CC = 15168 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv(); 15169 15170 CXXRecordDecl *Lambda = Conv->getParent(); 15171 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 15172 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC); 15173 15174 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 15175 CallOp = InstantiateFunctionDeclaration( 15176 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 15177 if (!CallOp) 15178 return; 15179 15180 Invoker = InstantiateFunctionDeclaration( 15181 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 15182 if (!Invoker) 15183 return; 15184 } 15185 15186 if (CallOp->isInvalidDecl()) 15187 return; 15188 15189 // Mark the call operator referenced (and add to pending instantiations 15190 // if necessary). 15191 // For both the conversion and static-invoker template specializations 15192 // we construct their body's in this function, so no need to add them 15193 // to the PendingInstantiations. 15194 MarkFunctionReferenced(CurrentLocation, CallOp); 15195 15196 // Fill in the __invoke function with a dummy implementation. IR generation 15197 // will fill in the actual details. Update its type in case it contained 15198 // an 'auto'. 15199 Invoker->markUsed(Context); 15200 Invoker->setReferenced(); 15201 Invoker->setType(Conv->getReturnType()->getPointeeType()); 15202 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 15203 15204 // Construct the body of the conversion function { return __invoke; }. 15205 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 15206 VK_LValue, Conv->getLocation()); 15207 assert(FunctionRef && "Can't refer to __invoke function?"); 15208 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 15209 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 15210 Conv->getLocation())); 15211 Conv->markUsed(Context); 15212 Conv->setReferenced(); 15213 15214 if (ASTMutationListener *L = getASTMutationListener()) { 15215 L->CompletedImplicitDefinition(Conv); 15216 L->CompletedImplicitDefinition(Invoker); 15217 } 15218 } 15219 15220 15221 15222 void Sema::DefineImplicitLambdaToBlockPointerConversion( 15223 SourceLocation CurrentLocation, 15224 CXXConversionDecl *Conv) 15225 { 15226 assert(!Conv->getParent()->isGenericLambda()); 15227 15228 SynthesizedFunctionScope Scope(*this, Conv); 15229 15230 // Copy-initialize the lambda object as needed to capture it. 15231 Expr *This = ActOnCXXThis(CurrentLocation).get(); 15232 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 15233 15234 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 15235 Conv->getLocation(), 15236 Conv, DerefThis); 15237 15238 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 15239 // behavior. Note that only the general conversion function does this 15240 // (since it's unusable otherwise); in the case where we inline the 15241 // block literal, it has block literal lifetime semantics. 15242 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 15243 BuildBlock = ImplicitCastExpr::Create( 15244 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject, 15245 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride()); 15246 15247 if (BuildBlock.isInvalid()) { 15248 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15249 Conv->setInvalidDecl(); 15250 return; 15251 } 15252 15253 // Create the return statement that returns the block from the conversion 15254 // function. 15255 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 15256 if (Return.isInvalid()) { 15257 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15258 Conv->setInvalidDecl(); 15259 return; 15260 } 15261 15262 // Set the body of the conversion function. 15263 Stmt *ReturnS = Return.get(); 15264 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 15265 Conv->getLocation())); 15266 Conv->markUsed(Context); 15267 15268 // We're done; notify the mutation listener, if any. 15269 if (ASTMutationListener *L = getASTMutationListener()) { 15270 L->CompletedImplicitDefinition(Conv); 15271 } 15272 } 15273 15274 /// Determine whether the given list arguments contains exactly one 15275 /// "real" (non-default) argument. 15276 static bool hasOneRealArgument(MultiExprArg Args) { 15277 switch (Args.size()) { 15278 case 0: 15279 return false; 15280 15281 default: 15282 if (!Args[1]->isDefaultArgument()) 15283 return false; 15284 15285 LLVM_FALLTHROUGH; 15286 case 1: 15287 return !Args[0]->isDefaultArgument(); 15288 } 15289 15290 return false; 15291 } 15292 15293 ExprResult 15294 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15295 NamedDecl *FoundDecl, 15296 CXXConstructorDecl *Constructor, 15297 MultiExprArg ExprArgs, 15298 bool HadMultipleCandidates, 15299 bool IsListInitialization, 15300 bool IsStdInitListInitialization, 15301 bool RequiresZeroInit, 15302 unsigned ConstructKind, 15303 SourceRange ParenRange) { 15304 bool Elidable = false; 15305 15306 // C++0x [class.copy]p34: 15307 // When certain criteria are met, an implementation is allowed to 15308 // omit the copy/move construction of a class object, even if the 15309 // copy/move constructor and/or destructor for the object have 15310 // side effects. [...] 15311 // - when a temporary class object that has not been bound to a 15312 // reference (12.2) would be copied/moved to a class object 15313 // with the same cv-unqualified type, the copy/move operation 15314 // can be omitted by constructing the temporary object 15315 // directly into the target of the omitted copy/move 15316 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 15317 // FIXME: Converting constructors should also be accepted. 15318 // But to fix this, the logic that digs down into a CXXConstructExpr 15319 // to find the source object needs to handle it. 15320 // Right now it assumes the source object is passed directly as the 15321 // first argument. 15322 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 15323 Expr *SubExpr = ExprArgs[0]; 15324 // FIXME: Per above, this is also incorrect if we want to accept 15325 // converting constructors, as isTemporaryObject will 15326 // reject temporaries with different type from the 15327 // CXXRecord itself. 15328 Elidable = SubExpr->isTemporaryObject( 15329 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 15330 } 15331 15332 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 15333 FoundDecl, Constructor, 15334 Elidable, ExprArgs, HadMultipleCandidates, 15335 IsListInitialization, 15336 IsStdInitListInitialization, RequiresZeroInit, 15337 ConstructKind, ParenRange); 15338 } 15339 15340 ExprResult 15341 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15342 NamedDecl *FoundDecl, 15343 CXXConstructorDecl *Constructor, 15344 bool Elidable, 15345 MultiExprArg ExprArgs, 15346 bool HadMultipleCandidates, 15347 bool IsListInitialization, 15348 bool IsStdInitListInitialization, 15349 bool RequiresZeroInit, 15350 unsigned ConstructKind, 15351 SourceRange ParenRange) { 15352 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 15353 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 15354 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 15355 return ExprError(); 15356 } 15357 15358 return BuildCXXConstructExpr( 15359 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 15360 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 15361 RequiresZeroInit, ConstructKind, ParenRange); 15362 } 15363 15364 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 15365 /// including handling of its default argument expressions. 15366 ExprResult 15367 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15368 CXXConstructorDecl *Constructor, 15369 bool Elidable, 15370 MultiExprArg ExprArgs, 15371 bool HadMultipleCandidates, 15372 bool IsListInitialization, 15373 bool IsStdInitListInitialization, 15374 bool RequiresZeroInit, 15375 unsigned ConstructKind, 15376 SourceRange ParenRange) { 15377 assert(declaresSameEntity( 15378 Constructor->getParent(), 15379 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 15380 "given constructor for wrong type"); 15381 MarkFunctionReferenced(ConstructLoc, Constructor); 15382 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 15383 return ExprError(); 15384 if (getLangOpts().SYCLIsDevice && 15385 !checkSYCLDeviceFunction(ConstructLoc, Constructor)) 15386 return ExprError(); 15387 15388 return CheckForImmediateInvocation( 15389 CXXConstructExpr::Create( 15390 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 15391 HadMultipleCandidates, IsListInitialization, 15392 IsStdInitListInitialization, RequiresZeroInit, 15393 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 15394 ParenRange), 15395 Constructor); 15396 } 15397 15398 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 15399 assert(Field->hasInClassInitializer()); 15400 15401 // If we already have the in-class initializer nothing needs to be done. 15402 if (Field->getInClassInitializer()) 15403 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15404 15405 // If we might have already tried and failed to instantiate, don't try again. 15406 if (Field->isInvalidDecl()) 15407 return ExprError(); 15408 15409 // Maybe we haven't instantiated the in-class initializer. Go check the 15410 // pattern FieldDecl to see if it has one. 15411 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 15412 15413 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 15414 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 15415 DeclContext::lookup_result Lookup = 15416 ClassPattern->lookup(Field->getDeclName()); 15417 15418 FieldDecl *Pattern = nullptr; 15419 for (auto L : Lookup) { 15420 if (isa<FieldDecl>(L)) { 15421 Pattern = cast<FieldDecl>(L); 15422 break; 15423 } 15424 } 15425 assert(Pattern && "We must have set the Pattern!"); 15426 15427 if (!Pattern->hasInClassInitializer() || 15428 InstantiateInClassInitializer(Loc, Field, Pattern, 15429 getTemplateInstantiationArgs(Field))) { 15430 // Don't diagnose this again. 15431 Field->setInvalidDecl(); 15432 return ExprError(); 15433 } 15434 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15435 } 15436 15437 // DR1351: 15438 // If the brace-or-equal-initializer of a non-static data member 15439 // invokes a defaulted default constructor of its class or of an 15440 // enclosing class in a potentially evaluated subexpression, the 15441 // program is ill-formed. 15442 // 15443 // This resolution is unworkable: the exception specification of the 15444 // default constructor can be needed in an unevaluated context, in 15445 // particular, in the operand of a noexcept-expression, and we can be 15446 // unable to compute an exception specification for an enclosed class. 15447 // 15448 // Any attempt to resolve the exception specification of a defaulted default 15449 // constructor before the initializer is lexically complete will ultimately 15450 // come here at which point we can diagnose it. 15451 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 15452 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed) 15453 << OutermostClass << Field; 15454 Diag(Field->getEndLoc(), 15455 diag::note_default_member_initializer_not_yet_parsed); 15456 // Recover by marking the field invalid, unless we're in a SFINAE context. 15457 if (!isSFINAEContext()) 15458 Field->setInvalidDecl(); 15459 return ExprError(); 15460 } 15461 15462 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 15463 if (VD->isInvalidDecl()) return; 15464 // If initializing the variable failed, don't also diagnose problems with 15465 // the destructor, they're likely related. 15466 if (VD->getInit() && VD->getInit()->containsErrors()) 15467 return; 15468 15469 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 15470 if (ClassDecl->isInvalidDecl()) return; 15471 if (ClassDecl->hasIrrelevantDestructor()) return; 15472 if (ClassDecl->isDependentContext()) return; 15473 15474 if (VD->isNoDestroy(getASTContext())) 15475 return; 15476 15477 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15478 15479 // If this is an array, we'll require the destructor during initialization, so 15480 // we can skip over this. We still want to emit exit-time destructor warnings 15481 // though. 15482 if (!VD->getType()->isArrayType()) { 15483 MarkFunctionReferenced(VD->getLocation(), Destructor); 15484 CheckDestructorAccess(VD->getLocation(), Destructor, 15485 PDiag(diag::err_access_dtor_var) 15486 << VD->getDeclName() << VD->getType()); 15487 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 15488 } 15489 15490 if (Destructor->isTrivial()) return; 15491 15492 // If the destructor is constexpr, check whether the variable has constant 15493 // destruction now. 15494 if (Destructor->isConstexpr()) { 15495 bool HasConstantInit = false; 15496 if (VD->getInit() && !VD->getInit()->isValueDependent()) 15497 HasConstantInit = VD->evaluateValue(); 15498 SmallVector<PartialDiagnosticAt, 8> Notes; 15499 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && 15500 HasConstantInit) { 15501 Diag(VD->getLocation(), 15502 diag::err_constexpr_var_requires_const_destruction) << VD; 15503 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 15504 Diag(Notes[I].first, Notes[I].second); 15505 } 15506 } 15507 15508 if (!VD->hasGlobalStorage()) return; 15509 15510 // Emit warning for non-trivial dtor in global scope (a real global, 15511 // class-static, function-static). 15512 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 15513 15514 // TODO: this should be re-enabled for static locals by !CXAAtExit 15515 if (!VD->isStaticLocal()) 15516 Diag(VD->getLocation(), diag::warn_global_destructor); 15517 } 15518 15519 /// Given a constructor and the set of arguments provided for the 15520 /// constructor, convert the arguments and add any required default arguments 15521 /// to form a proper call to this constructor. 15522 /// 15523 /// \returns true if an error occurred, false otherwise. 15524 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 15525 QualType DeclInitType, MultiExprArg ArgsPtr, 15526 SourceLocation Loc, 15527 SmallVectorImpl<Expr *> &ConvertedArgs, 15528 bool AllowExplicit, 15529 bool IsListInitialization) { 15530 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 15531 unsigned NumArgs = ArgsPtr.size(); 15532 Expr **Args = ArgsPtr.data(); 15533 15534 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); 15535 unsigned NumParams = Proto->getNumParams(); 15536 15537 // If too few arguments are available, we'll fill in the rest with defaults. 15538 if (NumArgs < NumParams) 15539 ConvertedArgs.reserve(NumParams); 15540 else 15541 ConvertedArgs.reserve(NumArgs); 15542 15543 VariadicCallType CallType = 15544 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 15545 SmallVector<Expr *, 8> AllArgs; 15546 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 15547 Proto, 0, 15548 llvm::makeArrayRef(Args, NumArgs), 15549 AllArgs, 15550 CallType, AllowExplicit, 15551 IsListInitialization); 15552 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 15553 15554 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 15555 15556 CheckConstructorCall(Constructor, DeclInitType, 15557 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 15558 Proto, Loc); 15559 15560 return Invalid; 15561 } 15562 15563 static inline bool 15564 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 15565 const FunctionDecl *FnDecl) { 15566 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 15567 if (isa<NamespaceDecl>(DC)) { 15568 return SemaRef.Diag(FnDecl->getLocation(), 15569 diag::err_operator_new_delete_declared_in_namespace) 15570 << FnDecl->getDeclName(); 15571 } 15572 15573 if (isa<TranslationUnitDecl>(DC) && 15574 FnDecl->getStorageClass() == SC_Static) { 15575 return SemaRef.Diag(FnDecl->getLocation(), 15576 diag::err_operator_new_delete_declared_static) 15577 << FnDecl->getDeclName(); 15578 } 15579 15580 return false; 15581 } 15582 15583 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, 15584 const PointerType *PtrTy) { 15585 auto &Ctx = SemaRef.Context; 15586 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers(); 15587 PtrQuals.removeAddressSpace(); 15588 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType( 15589 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals))); 15590 } 15591 15592 static inline bool 15593 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 15594 CanQualType ExpectedResultType, 15595 CanQualType ExpectedFirstParamType, 15596 unsigned DependentParamTypeDiag, 15597 unsigned InvalidParamTypeDiag) { 15598 QualType ResultType = 15599 FnDecl->getType()->castAs<FunctionType>()->getReturnType(); 15600 15601 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15602 // The operator is valid on any address space for OpenCL. 15603 // Drop address space from actual and expected result types. 15604 if (const auto *PtrTy = ResultType->getAs<PointerType>()) 15605 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15606 15607 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>()) 15608 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15609 } 15610 15611 // Check that the result type is what we expect. 15612 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) { 15613 // Reject even if the type is dependent; an operator delete function is 15614 // required to have a non-dependent result type. 15615 return SemaRef.Diag( 15616 FnDecl->getLocation(), 15617 ResultType->isDependentType() 15618 ? diag::err_operator_new_delete_dependent_result_type 15619 : diag::err_operator_new_delete_invalid_result_type) 15620 << FnDecl->getDeclName() << ExpectedResultType; 15621 } 15622 15623 // A function template must have at least 2 parameters. 15624 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 15625 return SemaRef.Diag(FnDecl->getLocation(), 15626 diag::err_operator_new_delete_template_too_few_parameters) 15627 << FnDecl->getDeclName(); 15628 15629 // The function decl must have at least 1 parameter. 15630 if (FnDecl->getNumParams() == 0) 15631 return SemaRef.Diag(FnDecl->getLocation(), 15632 diag::err_operator_new_delete_too_few_parameters) 15633 << FnDecl->getDeclName(); 15634 15635 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 15636 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15637 // The operator is valid on any address space for OpenCL. 15638 // Drop address space from actual and expected first parameter types. 15639 if (const auto *PtrTy = 15640 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) 15641 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15642 15643 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>()) 15644 ExpectedFirstParamType = 15645 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15646 } 15647 15648 // Check that the first parameter type is what we expect. 15649 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 15650 ExpectedFirstParamType) { 15651 // The first parameter type is not allowed to be dependent. As a tentative 15652 // DR resolution, we allow a dependent parameter type if it is the right 15653 // type anyway, to allow destroying operator delete in class templates. 15654 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType() 15655 ? DependentParamTypeDiag 15656 : InvalidParamTypeDiag) 15657 << FnDecl->getDeclName() << ExpectedFirstParamType; 15658 } 15659 15660 return false; 15661 } 15662 15663 static bool 15664 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 15665 // C++ [basic.stc.dynamic.allocation]p1: 15666 // A program is ill-formed if an allocation function is declared in a 15667 // namespace scope other than global scope or declared static in global 15668 // scope. 15669 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15670 return true; 15671 15672 CanQualType SizeTy = 15673 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 15674 15675 // C++ [basic.stc.dynamic.allocation]p1: 15676 // The return type shall be void*. The first parameter shall have type 15677 // std::size_t. 15678 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 15679 SizeTy, 15680 diag::err_operator_new_dependent_param_type, 15681 diag::err_operator_new_param_type)) 15682 return true; 15683 15684 // C++ [basic.stc.dynamic.allocation]p1: 15685 // The first parameter shall not have an associated default argument. 15686 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 15687 return SemaRef.Diag(FnDecl->getLocation(), 15688 diag::err_operator_new_default_arg) 15689 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 15690 15691 return false; 15692 } 15693 15694 static bool 15695 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 15696 // C++ [basic.stc.dynamic.deallocation]p1: 15697 // A program is ill-formed if deallocation functions are declared in a 15698 // namespace scope other than global scope or declared static in global 15699 // scope. 15700 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15701 return true; 15702 15703 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 15704 15705 // C++ P0722: 15706 // Within a class C, the first parameter of a destroying operator delete 15707 // shall be of type C *. The first parameter of any other deallocation 15708 // function shall be of type void *. 15709 CanQualType ExpectedFirstParamType = 15710 MD && MD->isDestroyingOperatorDelete() 15711 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 15712 SemaRef.Context.getRecordType(MD->getParent()))) 15713 : SemaRef.Context.VoidPtrTy; 15714 15715 // C++ [basic.stc.dynamic.deallocation]p2: 15716 // Each deallocation function shall return void 15717 if (CheckOperatorNewDeleteTypes( 15718 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 15719 diag::err_operator_delete_dependent_param_type, 15720 diag::err_operator_delete_param_type)) 15721 return true; 15722 15723 // C++ P0722: 15724 // A destroying operator delete shall be a usual deallocation function. 15725 if (MD && !MD->getParent()->isDependentContext() && 15726 MD->isDestroyingOperatorDelete() && 15727 !SemaRef.isUsualDeallocationFunction(MD)) { 15728 SemaRef.Diag(MD->getLocation(), 15729 diag::err_destroying_operator_delete_not_usual); 15730 return true; 15731 } 15732 15733 return false; 15734 } 15735 15736 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 15737 /// of this overloaded operator is well-formed. If so, returns false; 15738 /// otherwise, emits appropriate diagnostics and returns true. 15739 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 15740 assert(FnDecl && FnDecl->isOverloadedOperator() && 15741 "Expected an overloaded operator declaration"); 15742 15743 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 15744 15745 // C++ [over.oper]p5: 15746 // The allocation and deallocation functions, operator new, 15747 // operator new[], operator delete and operator delete[], are 15748 // described completely in 3.7.3. The attributes and restrictions 15749 // found in the rest of this subclause do not apply to them unless 15750 // explicitly stated in 3.7.3. 15751 if (Op == OO_Delete || Op == OO_Array_Delete) 15752 return CheckOperatorDeleteDeclaration(*this, FnDecl); 15753 15754 if (Op == OO_New || Op == OO_Array_New) 15755 return CheckOperatorNewDeclaration(*this, FnDecl); 15756 15757 // C++ [over.oper]p6: 15758 // An operator function shall either be a non-static member 15759 // function or be a non-member function and have at least one 15760 // parameter whose type is a class, a reference to a class, an 15761 // enumeration, or a reference to an enumeration. 15762 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 15763 if (MethodDecl->isStatic()) 15764 return Diag(FnDecl->getLocation(), 15765 diag::err_operator_overload_static) << FnDecl->getDeclName(); 15766 } else { 15767 bool ClassOrEnumParam = false; 15768 for (auto Param : FnDecl->parameters()) { 15769 QualType ParamType = Param->getType().getNonReferenceType(); 15770 if (ParamType->isDependentType() || ParamType->isRecordType() || 15771 ParamType->isEnumeralType()) { 15772 ClassOrEnumParam = true; 15773 break; 15774 } 15775 } 15776 15777 if (!ClassOrEnumParam) 15778 return Diag(FnDecl->getLocation(), 15779 diag::err_operator_overload_needs_class_or_enum) 15780 << FnDecl->getDeclName(); 15781 } 15782 15783 // C++ [over.oper]p8: 15784 // An operator function cannot have default arguments (8.3.6), 15785 // except where explicitly stated below. 15786 // 15787 // Only the function-call operator allows default arguments 15788 // (C++ [over.call]p1). 15789 if (Op != OO_Call) { 15790 for (auto Param : FnDecl->parameters()) { 15791 if (Param->hasDefaultArg()) 15792 return Diag(Param->getLocation(), 15793 diag::err_operator_overload_default_arg) 15794 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 15795 } 15796 } 15797 15798 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 15799 { false, false, false } 15800 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 15801 , { Unary, Binary, MemberOnly } 15802 #include "clang/Basic/OperatorKinds.def" 15803 }; 15804 15805 bool CanBeUnaryOperator = OperatorUses[Op][0]; 15806 bool CanBeBinaryOperator = OperatorUses[Op][1]; 15807 bool MustBeMemberOperator = OperatorUses[Op][2]; 15808 15809 // C++ [over.oper]p8: 15810 // [...] Operator functions cannot have more or fewer parameters 15811 // than the number required for the corresponding operator, as 15812 // described in the rest of this subclause. 15813 unsigned NumParams = FnDecl->getNumParams() 15814 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 15815 if (Op != OO_Call && 15816 ((NumParams == 1 && !CanBeUnaryOperator) || 15817 (NumParams == 2 && !CanBeBinaryOperator) || 15818 (NumParams < 1) || (NumParams > 2))) { 15819 // We have the wrong number of parameters. 15820 unsigned ErrorKind; 15821 if (CanBeUnaryOperator && CanBeBinaryOperator) { 15822 ErrorKind = 2; // 2 -> unary or binary. 15823 } else if (CanBeUnaryOperator) { 15824 ErrorKind = 0; // 0 -> unary 15825 } else { 15826 assert(CanBeBinaryOperator && 15827 "All non-call overloaded operators are unary or binary!"); 15828 ErrorKind = 1; // 1 -> binary 15829 } 15830 15831 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 15832 << FnDecl->getDeclName() << NumParams << ErrorKind; 15833 } 15834 15835 // Overloaded operators other than operator() cannot be variadic. 15836 if (Op != OO_Call && 15837 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { 15838 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 15839 << FnDecl->getDeclName(); 15840 } 15841 15842 // Some operators must be non-static member functions. 15843 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 15844 return Diag(FnDecl->getLocation(), 15845 diag::err_operator_overload_must_be_member) 15846 << FnDecl->getDeclName(); 15847 } 15848 15849 // C++ [over.inc]p1: 15850 // The user-defined function called operator++ implements the 15851 // prefix and postfix ++ operator. If this function is a member 15852 // function with no parameters, or a non-member function with one 15853 // parameter of class or enumeration type, it defines the prefix 15854 // increment operator ++ for objects of that type. If the function 15855 // is a member function with one parameter (which shall be of type 15856 // int) or a non-member function with two parameters (the second 15857 // of which shall be of type int), it defines the postfix 15858 // increment operator ++ for objects of that type. 15859 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 15860 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 15861 QualType ParamType = LastParam->getType(); 15862 15863 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 15864 !ParamType->isDependentType()) 15865 return Diag(LastParam->getLocation(), 15866 diag::err_operator_overload_post_incdec_must_be_int) 15867 << LastParam->getType() << (Op == OO_MinusMinus); 15868 } 15869 15870 return false; 15871 } 15872 15873 static bool 15874 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 15875 FunctionTemplateDecl *TpDecl) { 15876 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 15877 15878 // Must have one or two template parameters. 15879 if (TemplateParams->size() == 1) { 15880 NonTypeTemplateParmDecl *PmDecl = 15881 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 15882 15883 // The template parameter must be a char parameter pack. 15884 if (PmDecl && PmDecl->isTemplateParameterPack() && 15885 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 15886 return false; 15887 15888 // C++20 [over.literal]p5: 15889 // A string literal operator template is a literal operator template 15890 // whose template-parameter-list comprises a single non-type 15891 // template-parameter of class type. 15892 // 15893 // As a DR resolution, we also allow placeholders for deduced class 15894 // template specializations. 15895 if (SemaRef.getLangOpts().CPlusPlus20 && 15896 !PmDecl->isTemplateParameterPack() && 15897 (PmDecl->getType()->isRecordType() || 15898 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>())) 15899 return false; 15900 } else if (TemplateParams->size() == 2) { 15901 TemplateTypeParmDecl *PmType = 15902 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 15903 NonTypeTemplateParmDecl *PmArgs = 15904 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 15905 15906 // The second template parameter must be a parameter pack with the 15907 // first template parameter as its type. 15908 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 15909 PmArgs->isTemplateParameterPack()) { 15910 const TemplateTypeParmType *TArgs = 15911 PmArgs->getType()->getAs<TemplateTypeParmType>(); 15912 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 15913 TArgs->getIndex() == PmType->getIndex()) { 15914 if (!SemaRef.inTemplateInstantiation()) 15915 SemaRef.Diag(TpDecl->getLocation(), 15916 diag::ext_string_literal_operator_template); 15917 return false; 15918 } 15919 } 15920 } 15921 15922 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 15923 diag::err_literal_operator_template) 15924 << TpDecl->getTemplateParameters()->getSourceRange(); 15925 return true; 15926 } 15927 15928 /// CheckLiteralOperatorDeclaration - Check whether the declaration 15929 /// of this literal operator function is well-formed. If so, returns 15930 /// false; otherwise, emits appropriate diagnostics and returns true. 15931 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 15932 if (isa<CXXMethodDecl>(FnDecl)) { 15933 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 15934 << FnDecl->getDeclName(); 15935 return true; 15936 } 15937 15938 if (FnDecl->isExternC()) { 15939 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 15940 if (const LinkageSpecDecl *LSD = 15941 FnDecl->getDeclContext()->getExternCContext()) 15942 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 15943 return true; 15944 } 15945 15946 // This might be the definition of a literal operator template. 15947 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 15948 15949 // This might be a specialization of a literal operator template. 15950 if (!TpDecl) 15951 TpDecl = FnDecl->getPrimaryTemplate(); 15952 15953 // template <char...> type operator "" name() and 15954 // template <class T, T...> type operator "" name() are the only valid 15955 // template signatures, and the only valid signatures with no parameters. 15956 // 15957 // C++20 also allows template <SomeClass T> type operator "" name(). 15958 if (TpDecl) { 15959 if (FnDecl->param_size() != 0) { 15960 Diag(FnDecl->getLocation(), 15961 diag::err_literal_operator_template_with_params); 15962 return true; 15963 } 15964 15965 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 15966 return true; 15967 15968 } else if (FnDecl->param_size() == 1) { 15969 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 15970 15971 QualType ParamType = Param->getType().getUnqualifiedType(); 15972 15973 // Only unsigned long long int, long double, any character type, and const 15974 // char * are allowed as the only parameters. 15975 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 15976 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 15977 Context.hasSameType(ParamType, Context.CharTy) || 15978 Context.hasSameType(ParamType, Context.WideCharTy) || 15979 Context.hasSameType(ParamType, Context.Char8Ty) || 15980 Context.hasSameType(ParamType, Context.Char16Ty) || 15981 Context.hasSameType(ParamType, Context.Char32Ty)) { 15982 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 15983 QualType InnerType = Ptr->getPointeeType(); 15984 15985 // Pointer parameter must be a const char *. 15986 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 15987 Context.CharTy) && 15988 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 15989 Diag(Param->getSourceRange().getBegin(), 15990 diag::err_literal_operator_param) 15991 << ParamType << "'const char *'" << Param->getSourceRange(); 15992 return true; 15993 } 15994 15995 } else if (ParamType->isRealFloatingType()) { 15996 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15997 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 15998 return true; 15999 16000 } else if (ParamType->isIntegerType()) { 16001 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 16002 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 16003 return true; 16004 16005 } else { 16006 Diag(Param->getSourceRange().getBegin(), 16007 diag::err_literal_operator_invalid_param) 16008 << ParamType << Param->getSourceRange(); 16009 return true; 16010 } 16011 16012 } else if (FnDecl->param_size() == 2) { 16013 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 16014 16015 // First, verify that the first parameter is correct. 16016 16017 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 16018 16019 // Two parameter function must have a pointer to const as a 16020 // first parameter; let's strip those qualifiers. 16021 const PointerType *PT = FirstParamType->getAs<PointerType>(); 16022 16023 if (!PT) { 16024 Diag((*Param)->getSourceRange().getBegin(), 16025 diag::err_literal_operator_param) 16026 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16027 return true; 16028 } 16029 16030 QualType PointeeType = PT->getPointeeType(); 16031 // First parameter must be const 16032 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 16033 Diag((*Param)->getSourceRange().getBegin(), 16034 diag::err_literal_operator_param) 16035 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16036 return true; 16037 } 16038 16039 QualType InnerType = PointeeType.getUnqualifiedType(); 16040 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 16041 // const char32_t* are allowed as the first parameter to a two-parameter 16042 // function 16043 if (!(Context.hasSameType(InnerType, Context.CharTy) || 16044 Context.hasSameType(InnerType, Context.WideCharTy) || 16045 Context.hasSameType(InnerType, Context.Char8Ty) || 16046 Context.hasSameType(InnerType, Context.Char16Ty) || 16047 Context.hasSameType(InnerType, Context.Char32Ty))) { 16048 Diag((*Param)->getSourceRange().getBegin(), 16049 diag::err_literal_operator_param) 16050 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16051 return true; 16052 } 16053 16054 // Move on to the second and final parameter. 16055 ++Param; 16056 16057 // The second parameter must be a std::size_t. 16058 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 16059 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 16060 Diag((*Param)->getSourceRange().getBegin(), 16061 diag::err_literal_operator_param) 16062 << SecondParamType << Context.getSizeType() 16063 << (*Param)->getSourceRange(); 16064 return true; 16065 } 16066 } else { 16067 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 16068 return true; 16069 } 16070 16071 // Parameters are good. 16072 16073 // A parameter-declaration-clause containing a default argument is not 16074 // equivalent to any of the permitted forms. 16075 for (auto Param : FnDecl->parameters()) { 16076 if (Param->hasDefaultArg()) { 16077 Diag(Param->getDefaultArgRange().getBegin(), 16078 diag::err_literal_operator_default_argument) 16079 << Param->getDefaultArgRange(); 16080 break; 16081 } 16082 } 16083 16084 StringRef LiteralName 16085 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 16086 if (LiteralName[0] != '_' && 16087 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 16088 // C++11 [usrlit.suffix]p1: 16089 // Literal suffix identifiers that do not start with an underscore 16090 // are reserved for future standardization. 16091 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 16092 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 16093 } 16094 16095 return false; 16096 } 16097 16098 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 16099 /// linkage specification, including the language and (if present) 16100 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 16101 /// language string literal. LBraceLoc, if valid, provides the location of 16102 /// the '{' brace. Otherwise, this linkage specification does not 16103 /// have any braces. 16104 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 16105 Expr *LangStr, 16106 SourceLocation LBraceLoc) { 16107 StringLiteral *Lit = cast<StringLiteral>(LangStr); 16108 if (!Lit->isAscii()) { 16109 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 16110 << LangStr->getSourceRange(); 16111 return nullptr; 16112 } 16113 16114 StringRef Lang = Lit->getString(); 16115 LinkageSpecDecl::LanguageIDs Language; 16116 if (Lang == "C") 16117 Language = LinkageSpecDecl::lang_c; 16118 else if (Lang == "C++") 16119 Language = LinkageSpecDecl::lang_cxx; 16120 else { 16121 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 16122 << LangStr->getSourceRange(); 16123 return nullptr; 16124 } 16125 16126 // FIXME: Add all the various semantics of linkage specifications 16127 16128 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 16129 LangStr->getExprLoc(), Language, 16130 LBraceLoc.isValid()); 16131 CurContext->addDecl(D); 16132 PushDeclContext(S, D); 16133 return D; 16134 } 16135 16136 /// ActOnFinishLinkageSpecification - Complete the definition of 16137 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 16138 /// valid, it's the position of the closing '}' brace in a linkage 16139 /// specification that uses braces. 16140 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 16141 Decl *LinkageSpec, 16142 SourceLocation RBraceLoc) { 16143 if (RBraceLoc.isValid()) { 16144 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 16145 LSDecl->setRBraceLoc(RBraceLoc); 16146 } 16147 PopDeclContext(); 16148 return LinkageSpec; 16149 } 16150 16151 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 16152 const ParsedAttributesView &AttrList, 16153 SourceLocation SemiLoc) { 16154 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 16155 // Attribute declarations appertain to empty declaration so we handle 16156 // them here. 16157 ProcessDeclAttributeList(S, ED, AttrList); 16158 16159 CurContext->addDecl(ED); 16160 return ED; 16161 } 16162 16163 /// Perform semantic analysis for the variable declaration that 16164 /// occurs within a C++ catch clause, returning the newly-created 16165 /// variable. 16166 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 16167 TypeSourceInfo *TInfo, 16168 SourceLocation StartLoc, 16169 SourceLocation Loc, 16170 IdentifierInfo *Name) { 16171 bool Invalid = false; 16172 QualType ExDeclType = TInfo->getType(); 16173 16174 // Arrays and functions decay. 16175 if (ExDeclType->isArrayType()) 16176 ExDeclType = Context.getArrayDecayedType(ExDeclType); 16177 else if (ExDeclType->isFunctionType()) 16178 ExDeclType = Context.getPointerType(ExDeclType); 16179 16180 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 16181 // The exception-declaration shall not denote a pointer or reference to an 16182 // incomplete type, other than [cv] void*. 16183 // N2844 forbids rvalue references. 16184 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 16185 Diag(Loc, diag::err_catch_rvalue_ref); 16186 Invalid = true; 16187 } 16188 16189 if (ExDeclType->isVariablyModifiedType()) { 16190 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 16191 Invalid = true; 16192 } 16193 16194 QualType BaseType = ExDeclType; 16195 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 16196 unsigned DK = diag::err_catch_incomplete; 16197 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 16198 BaseType = Ptr->getPointeeType(); 16199 Mode = 1; 16200 DK = diag::err_catch_incomplete_ptr; 16201 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 16202 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 16203 BaseType = Ref->getPointeeType(); 16204 Mode = 2; 16205 DK = diag::err_catch_incomplete_ref; 16206 } 16207 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 16208 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 16209 Invalid = true; 16210 16211 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) { 16212 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType; 16213 Invalid = true; 16214 } 16215 16216 if (!Invalid && !ExDeclType->isDependentType() && 16217 RequireNonAbstractType(Loc, ExDeclType, 16218 diag::err_abstract_type_in_decl, 16219 AbstractVariableType)) 16220 Invalid = true; 16221 16222 // Only the non-fragile NeXT runtime currently supports C++ catches 16223 // of ObjC types, and no runtime supports catching ObjC types by value. 16224 if (!Invalid && getLangOpts().ObjC) { 16225 QualType T = ExDeclType; 16226 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 16227 T = RT->getPointeeType(); 16228 16229 if (T->isObjCObjectType()) { 16230 Diag(Loc, diag::err_objc_object_catch); 16231 Invalid = true; 16232 } else if (T->isObjCObjectPointerType()) { 16233 // FIXME: should this be a test for macosx-fragile specifically? 16234 if (getLangOpts().ObjCRuntime.isFragile()) 16235 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 16236 } 16237 } 16238 16239 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 16240 ExDeclType, TInfo, SC_None); 16241 ExDecl->setExceptionVariable(true); 16242 16243 // In ARC, infer 'retaining' for variables of retainable type. 16244 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 16245 Invalid = true; 16246 16247 if (!Invalid && !ExDeclType->isDependentType()) { 16248 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 16249 // Insulate this from anything else we might currently be parsing. 16250 EnterExpressionEvaluationContext scope( 16251 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 16252 16253 // C++ [except.handle]p16: 16254 // The object declared in an exception-declaration or, if the 16255 // exception-declaration does not specify a name, a temporary (12.2) is 16256 // copy-initialized (8.5) from the exception object. [...] 16257 // The object is destroyed when the handler exits, after the destruction 16258 // of any automatic objects initialized within the handler. 16259 // 16260 // We just pretend to initialize the object with itself, then make sure 16261 // it can be destroyed later. 16262 QualType initType = Context.getExceptionObjectType(ExDeclType); 16263 16264 InitializedEntity entity = 16265 InitializedEntity::InitializeVariable(ExDecl); 16266 InitializationKind initKind = 16267 InitializationKind::CreateCopy(Loc, SourceLocation()); 16268 16269 Expr *opaqueValue = 16270 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 16271 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 16272 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 16273 if (result.isInvalid()) 16274 Invalid = true; 16275 else { 16276 // If the constructor used was non-trivial, set this as the 16277 // "initializer". 16278 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 16279 if (!construct->getConstructor()->isTrivial()) { 16280 Expr *init = MaybeCreateExprWithCleanups(construct); 16281 ExDecl->setInit(init); 16282 } 16283 16284 // And make sure it's destructable. 16285 FinalizeVarWithDestructor(ExDecl, recordType); 16286 } 16287 } 16288 } 16289 16290 if (Invalid) 16291 ExDecl->setInvalidDecl(); 16292 16293 return ExDecl; 16294 } 16295 16296 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 16297 /// handler. 16298 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 16299 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16300 bool Invalid = D.isInvalidType(); 16301 16302 // Check for unexpanded parameter packs. 16303 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16304 UPPC_ExceptionType)) { 16305 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 16306 D.getIdentifierLoc()); 16307 Invalid = true; 16308 } 16309 16310 IdentifierInfo *II = D.getIdentifier(); 16311 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 16312 LookupOrdinaryName, 16313 ForVisibleRedeclaration)) { 16314 // The scope should be freshly made just for us. There is just no way 16315 // it contains any previous declaration, except for function parameters in 16316 // a function-try-block's catch statement. 16317 assert(!S->isDeclScope(PrevDecl)); 16318 if (isDeclInScope(PrevDecl, CurContext, S)) { 16319 Diag(D.getIdentifierLoc(), diag::err_redefinition) 16320 << D.getIdentifier(); 16321 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 16322 Invalid = true; 16323 } else if (PrevDecl->isTemplateParameter()) 16324 // Maybe we will complain about the shadowed template parameter. 16325 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16326 } 16327 16328 if (D.getCXXScopeSpec().isSet() && !Invalid) { 16329 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 16330 << D.getCXXScopeSpec().getRange(); 16331 Invalid = true; 16332 } 16333 16334 VarDecl *ExDecl = BuildExceptionDeclaration( 16335 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 16336 if (Invalid) 16337 ExDecl->setInvalidDecl(); 16338 16339 // Add the exception declaration into this scope. 16340 if (II) 16341 PushOnScopeChains(ExDecl, S); 16342 else 16343 CurContext->addDecl(ExDecl); 16344 16345 ProcessDeclAttributes(S, ExDecl, D); 16346 return ExDecl; 16347 } 16348 16349 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16350 Expr *AssertExpr, 16351 Expr *AssertMessageExpr, 16352 SourceLocation RParenLoc) { 16353 StringLiteral *AssertMessage = 16354 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 16355 16356 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 16357 return nullptr; 16358 16359 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 16360 AssertMessage, RParenLoc, false); 16361 } 16362 16363 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16364 Expr *AssertExpr, 16365 StringLiteral *AssertMessage, 16366 SourceLocation RParenLoc, 16367 bool Failed) { 16368 assert(AssertExpr != nullptr && "Expected non-null condition"); 16369 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 16370 !Failed) { 16371 // In a static_assert-declaration, the constant-expression shall be a 16372 // constant expression that can be contextually converted to bool. 16373 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 16374 if (Converted.isInvalid()) 16375 Failed = true; 16376 16377 ExprResult FullAssertExpr = 16378 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 16379 /*DiscardedValue*/ false, 16380 /*IsConstexpr*/ true); 16381 if (FullAssertExpr.isInvalid()) 16382 Failed = true; 16383 else 16384 AssertExpr = FullAssertExpr.get(); 16385 16386 llvm::APSInt Cond; 16387 if (!Failed && VerifyIntegerConstantExpression( 16388 AssertExpr, &Cond, 16389 diag::err_static_assert_expression_is_not_constant) 16390 .isInvalid()) 16391 Failed = true; 16392 16393 if (!Failed && !Cond) { 16394 SmallString<256> MsgBuffer; 16395 llvm::raw_svector_ostream Msg(MsgBuffer); 16396 if (AssertMessage) 16397 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 16398 16399 Expr *InnerCond = nullptr; 16400 std::string InnerCondDescription; 16401 std::tie(InnerCond, InnerCondDescription) = 16402 findFailedBooleanCondition(Converted.get()); 16403 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 16404 // Drill down into concept specialization expressions to see why they 16405 // weren't satisfied. 16406 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16407 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16408 ConstraintSatisfaction Satisfaction; 16409 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 16410 DiagnoseUnsatisfiedConstraint(Satisfaction); 16411 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 16412 && !isa<IntegerLiteral>(InnerCond)) { 16413 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 16414 << InnerCondDescription << !AssertMessage 16415 << Msg.str() << InnerCond->getSourceRange(); 16416 } else { 16417 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16418 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16419 } 16420 Failed = true; 16421 } 16422 } else { 16423 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 16424 /*DiscardedValue*/false, 16425 /*IsConstexpr*/true); 16426 if (FullAssertExpr.isInvalid()) 16427 Failed = true; 16428 else 16429 AssertExpr = FullAssertExpr.get(); 16430 } 16431 16432 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 16433 AssertExpr, AssertMessage, RParenLoc, 16434 Failed); 16435 16436 CurContext->addDecl(Decl); 16437 return Decl; 16438 } 16439 16440 /// Perform semantic analysis of the given friend type declaration. 16441 /// 16442 /// \returns A friend declaration that. 16443 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 16444 SourceLocation FriendLoc, 16445 TypeSourceInfo *TSInfo) { 16446 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 16447 16448 QualType T = TSInfo->getType(); 16449 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 16450 16451 // C++03 [class.friend]p2: 16452 // An elaborated-type-specifier shall be used in a friend declaration 16453 // for a class.* 16454 // 16455 // * The class-key of the elaborated-type-specifier is required. 16456 if (!CodeSynthesisContexts.empty()) { 16457 // Do not complain about the form of friend template types during any kind 16458 // of code synthesis. For template instantiation, we will have complained 16459 // when the template was defined. 16460 } else { 16461 if (!T->isElaboratedTypeSpecifier()) { 16462 // If we evaluated the type to a record type, suggest putting 16463 // a tag in front. 16464 if (const RecordType *RT = T->getAs<RecordType>()) { 16465 RecordDecl *RD = RT->getDecl(); 16466 16467 SmallString<16> InsertionText(" "); 16468 InsertionText += RD->getKindName(); 16469 16470 Diag(TypeRange.getBegin(), 16471 getLangOpts().CPlusPlus11 ? 16472 diag::warn_cxx98_compat_unelaborated_friend_type : 16473 diag::ext_unelaborated_friend_type) 16474 << (unsigned) RD->getTagKind() 16475 << T 16476 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 16477 InsertionText); 16478 } else { 16479 Diag(FriendLoc, 16480 getLangOpts().CPlusPlus11 ? 16481 diag::warn_cxx98_compat_nonclass_type_friend : 16482 diag::ext_nonclass_type_friend) 16483 << T 16484 << TypeRange; 16485 } 16486 } else if (T->getAs<EnumType>()) { 16487 Diag(FriendLoc, 16488 getLangOpts().CPlusPlus11 ? 16489 diag::warn_cxx98_compat_enum_friend : 16490 diag::ext_enum_friend) 16491 << T 16492 << TypeRange; 16493 } 16494 16495 // C++11 [class.friend]p3: 16496 // A friend declaration that does not declare a function shall have one 16497 // of the following forms: 16498 // friend elaborated-type-specifier ; 16499 // friend simple-type-specifier ; 16500 // friend typename-specifier ; 16501 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 16502 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 16503 } 16504 16505 // If the type specifier in a friend declaration designates a (possibly 16506 // cv-qualified) class type, that class is declared as a friend; otherwise, 16507 // the friend declaration is ignored. 16508 return FriendDecl::Create(Context, CurContext, 16509 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 16510 FriendLoc); 16511 } 16512 16513 /// Handle a friend tag declaration where the scope specifier was 16514 /// templated. 16515 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 16516 unsigned TagSpec, SourceLocation TagLoc, 16517 CXXScopeSpec &SS, IdentifierInfo *Name, 16518 SourceLocation NameLoc, 16519 const ParsedAttributesView &Attr, 16520 MultiTemplateParamsArg TempParamLists) { 16521 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16522 16523 bool IsMemberSpecialization = false; 16524 bool Invalid = false; 16525 16526 if (TemplateParameterList *TemplateParams = 16527 MatchTemplateParametersToScopeSpecifier( 16528 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 16529 IsMemberSpecialization, Invalid)) { 16530 if (TemplateParams->size() > 0) { 16531 // This is a declaration of a class template. 16532 if (Invalid) 16533 return nullptr; 16534 16535 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 16536 NameLoc, Attr, TemplateParams, AS_public, 16537 /*ModulePrivateLoc=*/SourceLocation(), 16538 FriendLoc, TempParamLists.size() - 1, 16539 TempParamLists.data()).get(); 16540 } else { 16541 // The "template<>" header is extraneous. 16542 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16543 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16544 IsMemberSpecialization = true; 16545 } 16546 } 16547 16548 if (Invalid) return nullptr; 16549 16550 bool isAllExplicitSpecializations = true; 16551 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 16552 if (TempParamLists[I]->size()) { 16553 isAllExplicitSpecializations = false; 16554 break; 16555 } 16556 } 16557 16558 // FIXME: don't ignore attributes. 16559 16560 // If it's explicit specializations all the way down, just forget 16561 // about the template header and build an appropriate non-templated 16562 // friend. TODO: for source fidelity, remember the headers. 16563 if (isAllExplicitSpecializations) { 16564 if (SS.isEmpty()) { 16565 bool Owned = false; 16566 bool IsDependent = false; 16567 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 16568 Attr, AS_public, 16569 /*ModulePrivateLoc=*/SourceLocation(), 16570 MultiTemplateParamsArg(), Owned, IsDependent, 16571 /*ScopedEnumKWLoc=*/SourceLocation(), 16572 /*ScopedEnumUsesClassTag=*/false, 16573 /*UnderlyingType=*/TypeResult(), 16574 /*IsTypeSpecifier=*/false, 16575 /*IsTemplateParamOrArg=*/false); 16576 } 16577 16578 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 16579 ElaboratedTypeKeyword Keyword 16580 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16581 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 16582 *Name, NameLoc); 16583 if (T.isNull()) 16584 return nullptr; 16585 16586 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16587 if (isa<DependentNameType>(T)) { 16588 DependentNameTypeLoc TL = 16589 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16590 TL.setElaboratedKeywordLoc(TagLoc); 16591 TL.setQualifierLoc(QualifierLoc); 16592 TL.setNameLoc(NameLoc); 16593 } else { 16594 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 16595 TL.setElaboratedKeywordLoc(TagLoc); 16596 TL.setQualifierLoc(QualifierLoc); 16597 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 16598 } 16599 16600 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16601 TSI, FriendLoc, TempParamLists); 16602 Friend->setAccess(AS_public); 16603 CurContext->addDecl(Friend); 16604 return Friend; 16605 } 16606 16607 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 16608 16609 16610 16611 // Handle the case of a templated-scope friend class. e.g. 16612 // template <class T> class A<T>::B; 16613 // FIXME: we don't support these right now. 16614 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 16615 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 16616 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16617 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 16618 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16619 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16620 TL.setElaboratedKeywordLoc(TagLoc); 16621 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 16622 TL.setNameLoc(NameLoc); 16623 16624 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16625 TSI, FriendLoc, TempParamLists); 16626 Friend->setAccess(AS_public); 16627 Friend->setUnsupportedFriend(true); 16628 CurContext->addDecl(Friend); 16629 return Friend; 16630 } 16631 16632 /// Handle a friend type declaration. This works in tandem with 16633 /// ActOnTag. 16634 /// 16635 /// Notes on friend class templates: 16636 /// 16637 /// We generally treat friend class declarations as if they were 16638 /// declaring a class. So, for example, the elaborated type specifier 16639 /// in a friend declaration is required to obey the restrictions of a 16640 /// class-head (i.e. no typedefs in the scope chain), template 16641 /// parameters are required to match up with simple template-ids, &c. 16642 /// However, unlike when declaring a template specialization, it's 16643 /// okay to refer to a template specialization without an empty 16644 /// template parameter declaration, e.g. 16645 /// friend class A<T>::B<unsigned>; 16646 /// We permit this as a special case; if there are any template 16647 /// parameters present at all, require proper matching, i.e. 16648 /// template <> template \<class T> friend class A<int>::B; 16649 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 16650 MultiTemplateParamsArg TempParams) { 16651 SourceLocation Loc = DS.getBeginLoc(); 16652 16653 assert(DS.isFriendSpecified()); 16654 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16655 16656 // C++ [class.friend]p3: 16657 // A friend declaration that does not declare a function shall have one of 16658 // the following forms: 16659 // friend elaborated-type-specifier ; 16660 // friend simple-type-specifier ; 16661 // friend typename-specifier ; 16662 // 16663 // Any declaration with a type qualifier does not have that form. (It's 16664 // legal to specify a qualified type as a friend, you just can't write the 16665 // keywords.) 16666 if (DS.getTypeQualifiers()) { 16667 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 16668 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 16669 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 16670 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 16671 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 16672 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 16673 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 16674 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 16675 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 16676 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 16677 } 16678 16679 // Try to convert the decl specifier to a type. This works for 16680 // friend templates because ActOnTag never produces a ClassTemplateDecl 16681 // for a TUK_Friend. 16682 Declarator TheDeclarator(DS, DeclaratorContext::Member); 16683 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 16684 QualType T = TSI->getType(); 16685 if (TheDeclarator.isInvalidType()) 16686 return nullptr; 16687 16688 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 16689 return nullptr; 16690 16691 // This is definitely an error in C++98. It's probably meant to 16692 // be forbidden in C++0x, too, but the specification is just 16693 // poorly written. 16694 // 16695 // The problem is with declarations like the following: 16696 // template <T> friend A<T>::foo; 16697 // where deciding whether a class C is a friend or not now hinges 16698 // on whether there exists an instantiation of A that causes 16699 // 'foo' to equal C. There are restrictions on class-heads 16700 // (which we declare (by fiat) elaborated friend declarations to 16701 // be) that makes this tractable. 16702 // 16703 // FIXME: handle "template <> friend class A<T>;", which 16704 // is possibly well-formed? Who even knows? 16705 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 16706 Diag(Loc, diag::err_tagless_friend_type_template) 16707 << DS.getSourceRange(); 16708 return nullptr; 16709 } 16710 16711 // C++98 [class.friend]p1: A friend of a class is a function 16712 // or class that is not a member of the class . . . 16713 // This is fixed in DR77, which just barely didn't make the C++03 16714 // deadline. It's also a very silly restriction that seriously 16715 // affects inner classes and which nobody else seems to implement; 16716 // thus we never diagnose it, not even in -pedantic. 16717 // 16718 // But note that we could warn about it: it's always useless to 16719 // friend one of your own members (it's not, however, worthless to 16720 // friend a member of an arbitrary specialization of your template). 16721 16722 Decl *D; 16723 if (!TempParams.empty()) 16724 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 16725 TempParams, 16726 TSI, 16727 DS.getFriendSpecLoc()); 16728 else 16729 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 16730 16731 if (!D) 16732 return nullptr; 16733 16734 D->setAccess(AS_public); 16735 CurContext->addDecl(D); 16736 16737 return D; 16738 } 16739 16740 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 16741 MultiTemplateParamsArg TemplateParams) { 16742 const DeclSpec &DS = D.getDeclSpec(); 16743 16744 assert(DS.isFriendSpecified()); 16745 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16746 16747 SourceLocation Loc = D.getIdentifierLoc(); 16748 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16749 16750 // C++ [class.friend]p1 16751 // A friend of a class is a function or class.... 16752 // Note that this sees through typedefs, which is intended. 16753 // It *doesn't* see through dependent types, which is correct 16754 // according to [temp.arg.type]p3: 16755 // If a declaration acquires a function type through a 16756 // type dependent on a template-parameter and this causes 16757 // a declaration that does not use the syntactic form of a 16758 // function declarator to have a function type, the program 16759 // is ill-formed. 16760 if (!TInfo->getType()->isFunctionType()) { 16761 Diag(Loc, diag::err_unexpected_friend); 16762 16763 // It might be worthwhile to try to recover by creating an 16764 // appropriate declaration. 16765 return nullptr; 16766 } 16767 16768 // C++ [namespace.memdef]p3 16769 // - If a friend declaration in a non-local class first declares a 16770 // class or function, the friend class or function is a member 16771 // of the innermost enclosing namespace. 16772 // - The name of the friend is not found by simple name lookup 16773 // until a matching declaration is provided in that namespace 16774 // scope (either before or after the class declaration granting 16775 // friendship). 16776 // - If a friend function is called, its name may be found by the 16777 // name lookup that considers functions from namespaces and 16778 // classes associated with the types of the function arguments. 16779 // - When looking for a prior declaration of a class or a function 16780 // declared as a friend, scopes outside the innermost enclosing 16781 // namespace scope are not considered. 16782 16783 CXXScopeSpec &SS = D.getCXXScopeSpec(); 16784 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 16785 assert(NameInfo.getName()); 16786 16787 // Check for unexpanded parameter packs. 16788 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 16789 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 16790 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 16791 return nullptr; 16792 16793 // The context we found the declaration in, or in which we should 16794 // create the declaration. 16795 DeclContext *DC; 16796 Scope *DCScope = S; 16797 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 16798 ForExternalRedeclaration); 16799 16800 // There are five cases here. 16801 // - There's no scope specifier and we're in a local class. Only look 16802 // for functions declared in the immediately-enclosing block scope. 16803 // We recover from invalid scope qualifiers as if they just weren't there. 16804 FunctionDecl *FunctionContainingLocalClass = nullptr; 16805 if ((SS.isInvalid() || !SS.isSet()) && 16806 (FunctionContainingLocalClass = 16807 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 16808 // C++11 [class.friend]p11: 16809 // If a friend declaration appears in a local class and the name 16810 // specified is an unqualified name, a prior declaration is 16811 // looked up without considering scopes that are outside the 16812 // innermost enclosing non-class scope. For a friend function 16813 // declaration, if there is no prior declaration, the program is 16814 // ill-formed. 16815 16816 // Find the innermost enclosing non-class scope. This is the block 16817 // scope containing the local class definition (or for a nested class, 16818 // the outer local class). 16819 DCScope = S->getFnParent(); 16820 16821 // Look up the function name in the scope. 16822 Previous.clear(LookupLocalFriendName); 16823 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 16824 16825 if (!Previous.empty()) { 16826 // All possible previous declarations must have the same context: 16827 // either they were declared at block scope or they are members of 16828 // one of the enclosing local classes. 16829 DC = Previous.getRepresentativeDecl()->getDeclContext(); 16830 } else { 16831 // This is ill-formed, but provide the context that we would have 16832 // declared the function in, if we were permitted to, for error recovery. 16833 DC = FunctionContainingLocalClass; 16834 } 16835 adjustContextForLocalExternDecl(DC); 16836 16837 // C++ [class.friend]p6: 16838 // A function can be defined in a friend declaration of a class if and 16839 // only if the class is a non-local class (9.8), the function name is 16840 // unqualified, and the function has namespace scope. 16841 if (D.isFunctionDefinition()) { 16842 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 16843 } 16844 16845 // - There's no scope specifier, in which case we just go to the 16846 // appropriate scope and look for a function or function template 16847 // there as appropriate. 16848 } else if (SS.isInvalid() || !SS.isSet()) { 16849 // C++11 [namespace.memdef]p3: 16850 // If the name in a friend declaration is neither qualified nor 16851 // a template-id and the declaration is a function or an 16852 // elaborated-type-specifier, the lookup to determine whether 16853 // the entity has been previously declared shall not consider 16854 // any scopes outside the innermost enclosing namespace. 16855 bool isTemplateId = 16856 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 16857 16858 // Find the appropriate context according to the above. 16859 DC = CurContext; 16860 16861 // Skip class contexts. If someone can cite chapter and verse 16862 // for this behavior, that would be nice --- it's what GCC and 16863 // EDG do, and it seems like a reasonable intent, but the spec 16864 // really only says that checks for unqualified existing 16865 // declarations should stop at the nearest enclosing namespace, 16866 // not that they should only consider the nearest enclosing 16867 // namespace. 16868 while (DC->isRecord()) 16869 DC = DC->getParent(); 16870 16871 DeclContext *LookupDC = DC->getNonTransparentContext(); 16872 while (true) { 16873 LookupQualifiedName(Previous, LookupDC); 16874 16875 if (!Previous.empty()) { 16876 DC = LookupDC; 16877 break; 16878 } 16879 16880 if (isTemplateId) { 16881 if (isa<TranslationUnitDecl>(LookupDC)) break; 16882 } else { 16883 if (LookupDC->isFileContext()) break; 16884 } 16885 LookupDC = LookupDC->getParent(); 16886 } 16887 16888 DCScope = getScopeForDeclContext(S, DC); 16889 16890 // - There's a non-dependent scope specifier, in which case we 16891 // compute it and do a previous lookup there for a function 16892 // or function template. 16893 } else if (!SS.getScopeRep()->isDependent()) { 16894 DC = computeDeclContext(SS); 16895 if (!DC) return nullptr; 16896 16897 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 16898 16899 LookupQualifiedName(Previous, DC); 16900 16901 // C++ [class.friend]p1: A friend of a class is a function or 16902 // class that is not a member of the class . . . 16903 if (DC->Equals(CurContext)) 16904 Diag(DS.getFriendSpecLoc(), 16905 getLangOpts().CPlusPlus11 ? 16906 diag::warn_cxx98_compat_friend_is_member : 16907 diag::err_friend_is_member); 16908 16909 if (D.isFunctionDefinition()) { 16910 // C++ [class.friend]p6: 16911 // A function can be defined in a friend declaration of a class if and 16912 // only if the class is a non-local class (9.8), the function name is 16913 // unqualified, and the function has namespace scope. 16914 // 16915 // FIXME: We should only do this if the scope specifier names the 16916 // innermost enclosing namespace; otherwise the fixit changes the 16917 // meaning of the code. 16918 SemaDiagnosticBuilder DB 16919 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 16920 16921 DB << SS.getScopeRep(); 16922 if (DC->isFileContext()) 16923 DB << FixItHint::CreateRemoval(SS.getRange()); 16924 SS.clear(); 16925 } 16926 16927 // - There's a scope specifier that does not match any template 16928 // parameter lists, in which case we use some arbitrary context, 16929 // create a method or method template, and wait for instantiation. 16930 // - There's a scope specifier that does match some template 16931 // parameter lists, which we don't handle right now. 16932 } else { 16933 if (D.isFunctionDefinition()) { 16934 // C++ [class.friend]p6: 16935 // A function can be defined in a friend declaration of a class if and 16936 // only if the class is a non-local class (9.8), the function name is 16937 // unqualified, and the function has namespace scope. 16938 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 16939 << SS.getScopeRep(); 16940 } 16941 16942 DC = CurContext; 16943 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 16944 } 16945 16946 if (!DC->isRecord()) { 16947 int DiagArg = -1; 16948 switch (D.getName().getKind()) { 16949 case UnqualifiedIdKind::IK_ConstructorTemplateId: 16950 case UnqualifiedIdKind::IK_ConstructorName: 16951 DiagArg = 0; 16952 break; 16953 case UnqualifiedIdKind::IK_DestructorName: 16954 DiagArg = 1; 16955 break; 16956 case UnqualifiedIdKind::IK_ConversionFunctionId: 16957 DiagArg = 2; 16958 break; 16959 case UnqualifiedIdKind::IK_DeductionGuideName: 16960 DiagArg = 3; 16961 break; 16962 case UnqualifiedIdKind::IK_Identifier: 16963 case UnqualifiedIdKind::IK_ImplicitSelfParam: 16964 case UnqualifiedIdKind::IK_LiteralOperatorId: 16965 case UnqualifiedIdKind::IK_OperatorFunctionId: 16966 case UnqualifiedIdKind::IK_TemplateId: 16967 break; 16968 } 16969 // This implies that it has to be an operator or function. 16970 if (DiagArg >= 0) { 16971 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 16972 return nullptr; 16973 } 16974 } 16975 16976 // FIXME: This is an egregious hack to cope with cases where the scope stack 16977 // does not contain the declaration context, i.e., in an out-of-line 16978 // definition of a class. 16979 Scope FakeDCScope(S, Scope::DeclScope, Diags); 16980 if (!DCScope) { 16981 FakeDCScope.setEntity(DC); 16982 DCScope = &FakeDCScope; 16983 } 16984 16985 bool AddToScope = true; 16986 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 16987 TemplateParams, AddToScope); 16988 if (!ND) return nullptr; 16989 16990 assert(ND->getLexicalDeclContext() == CurContext); 16991 16992 // If we performed typo correction, we might have added a scope specifier 16993 // and changed the decl context. 16994 DC = ND->getDeclContext(); 16995 16996 // Add the function declaration to the appropriate lookup tables, 16997 // adjusting the redeclarations list as necessary. We don't 16998 // want to do this yet if the friending class is dependent. 16999 // 17000 // Also update the scope-based lookup if the target context's 17001 // lookup context is in lexical scope. 17002 if (!CurContext->isDependentContext()) { 17003 DC = DC->getRedeclContext(); 17004 DC->makeDeclVisibleInContext(ND); 17005 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 17006 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 17007 } 17008 17009 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 17010 D.getIdentifierLoc(), ND, 17011 DS.getFriendSpecLoc()); 17012 FrD->setAccess(AS_public); 17013 CurContext->addDecl(FrD); 17014 17015 if (ND->isInvalidDecl()) { 17016 FrD->setInvalidDecl(); 17017 } else { 17018 if (DC->isRecord()) CheckFriendAccess(ND); 17019 17020 FunctionDecl *FD; 17021 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 17022 FD = FTD->getTemplatedDecl(); 17023 else 17024 FD = cast<FunctionDecl>(ND); 17025 17026 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 17027 // default argument expression, that declaration shall be a definition 17028 // and shall be the only declaration of the function or function 17029 // template in the translation unit. 17030 if (functionDeclHasDefaultArgument(FD)) { 17031 // We can't look at FD->getPreviousDecl() because it may not have been set 17032 // if we're in a dependent context. If the function is known to be a 17033 // redeclaration, we will have narrowed Previous down to the right decl. 17034 if (D.isRedeclaration()) { 17035 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 17036 Diag(Previous.getRepresentativeDecl()->getLocation(), 17037 diag::note_previous_declaration); 17038 } else if (!D.isFunctionDefinition()) 17039 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 17040 } 17041 17042 // Mark templated-scope function declarations as unsupported. 17043 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 17044 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 17045 << SS.getScopeRep() << SS.getRange() 17046 << cast<CXXRecordDecl>(CurContext); 17047 FrD->setUnsupportedFriend(true); 17048 } 17049 } 17050 17051 warnOnReservedIdentifier(ND); 17052 17053 return ND; 17054 } 17055 17056 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 17057 AdjustDeclIfTemplate(Dcl); 17058 17059 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 17060 if (!Fn) { 17061 Diag(DelLoc, diag::err_deleted_non_function); 17062 return; 17063 } 17064 17065 // Deleted function does not have a body. 17066 Fn->setWillHaveBody(false); 17067 17068 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 17069 // Don't consider the implicit declaration we generate for explicit 17070 // specializations. FIXME: Do not generate these implicit declarations. 17071 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 17072 Prev->getPreviousDecl()) && 17073 !Prev->isDefined()) { 17074 Diag(DelLoc, diag::err_deleted_decl_not_first); 17075 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 17076 Prev->isImplicit() ? diag::note_previous_implicit_declaration 17077 : diag::note_previous_declaration); 17078 // We can't recover from this; the declaration might have already 17079 // been used. 17080 Fn->setInvalidDecl(); 17081 return; 17082 } 17083 17084 // To maintain the invariant that functions are only deleted on their first 17085 // declaration, mark the implicitly-instantiated declaration of the 17086 // explicitly-specialized function as deleted instead of marking the 17087 // instantiated redeclaration. 17088 Fn = Fn->getCanonicalDecl(); 17089 } 17090 17091 // dllimport/dllexport cannot be deleted. 17092 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 17093 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 17094 Fn->setInvalidDecl(); 17095 } 17096 17097 // C++11 [basic.start.main]p3: 17098 // A program that defines main as deleted [...] is ill-formed. 17099 if (Fn->isMain()) 17100 Diag(DelLoc, diag::err_deleted_main); 17101 17102 // C++11 [dcl.fct.def.delete]p4: 17103 // A deleted function is implicitly inline. 17104 Fn->setImplicitlyInline(); 17105 Fn->setDeletedAsWritten(); 17106 } 17107 17108 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 17109 if (!Dcl || Dcl->isInvalidDecl()) 17110 return; 17111 17112 auto *FD = dyn_cast<FunctionDecl>(Dcl); 17113 if (!FD) { 17114 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 17115 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 17116 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 17117 return; 17118 } 17119 } 17120 17121 Diag(DefaultLoc, diag::err_default_special_members) 17122 << getLangOpts().CPlusPlus20; 17123 return; 17124 } 17125 17126 // Reject if this can't possibly be a defaultable function. 17127 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 17128 if (!DefKind && 17129 // A dependent function that doesn't locally look defaultable can 17130 // still instantiate to a defaultable function if it's a constructor 17131 // or assignment operator. 17132 (!FD->isDependentContext() || 17133 (!isa<CXXConstructorDecl>(FD) && 17134 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 17135 Diag(DefaultLoc, diag::err_default_special_members) 17136 << getLangOpts().CPlusPlus20; 17137 return; 17138 } 17139 17140 if (DefKind.isComparison() && 17141 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 17142 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class) 17143 << (int)DefKind.asComparison(); 17144 return; 17145 } 17146 17147 // Issue compatibility warning. We already warned if the operator is 17148 // 'operator<=>' when parsing the '<=>' token. 17149 if (DefKind.isComparison() && 17150 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 17151 Diag(DefaultLoc, getLangOpts().CPlusPlus20 17152 ? diag::warn_cxx17_compat_defaulted_comparison 17153 : diag::ext_defaulted_comparison); 17154 } 17155 17156 FD->setDefaulted(); 17157 FD->setExplicitlyDefaulted(); 17158 17159 // Defer checking functions that are defaulted in a dependent context. 17160 if (FD->isDependentContext()) 17161 return; 17162 17163 // Unset that we will have a body for this function. We might not, 17164 // if it turns out to be trivial, and we don't need this marking now 17165 // that we've marked it as defaulted. 17166 FD->setWillHaveBody(false); 17167 17168 // If this definition appears within the record, do the checking when 17169 // the record is complete. This is always the case for a defaulted 17170 // comparison. 17171 if (DefKind.isComparison()) 17172 return; 17173 auto *MD = cast<CXXMethodDecl>(FD); 17174 17175 const FunctionDecl *Primary = FD; 17176 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 17177 // Ask the template instantiation pattern that actually had the 17178 // '= default' on it. 17179 Primary = Pattern; 17180 17181 // If the method was defaulted on its first declaration, we will have 17182 // already performed the checking in CheckCompletedCXXClass. Such a 17183 // declaration doesn't trigger an implicit definition. 17184 if (Primary->getCanonicalDecl()->isDefaulted()) 17185 return; 17186 17187 // FIXME: Once we support defining comparisons out of class, check for a 17188 // defaulted comparison here. 17189 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 17190 MD->setInvalidDecl(); 17191 else 17192 DefineDefaultedFunction(*this, MD, DefaultLoc); 17193 } 17194 17195 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 17196 for (Stmt *SubStmt : S->children()) { 17197 if (!SubStmt) 17198 continue; 17199 if (isa<ReturnStmt>(SubStmt)) 17200 Self.Diag(SubStmt->getBeginLoc(), 17201 diag::err_return_in_constructor_handler); 17202 if (!isa<Expr>(SubStmt)) 17203 SearchForReturnInStmt(Self, SubStmt); 17204 } 17205 } 17206 17207 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 17208 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 17209 CXXCatchStmt *Handler = TryBlock->getHandler(I); 17210 SearchForReturnInStmt(*this, Handler); 17211 } 17212 } 17213 17214 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 17215 const CXXMethodDecl *Old) { 17216 const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); 17217 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); 17218 17219 if (OldFT->hasExtParameterInfos()) { 17220 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 17221 // A parameter of the overriding method should be annotated with noescape 17222 // if the corresponding parameter of the overridden method is annotated. 17223 if (OldFT->getExtParameterInfo(I).isNoEscape() && 17224 !NewFT->getExtParameterInfo(I).isNoEscape()) { 17225 Diag(New->getParamDecl(I)->getLocation(), 17226 diag::warn_overriding_method_missing_noescape); 17227 Diag(Old->getParamDecl(I)->getLocation(), 17228 diag::note_overridden_marked_noescape); 17229 } 17230 } 17231 17232 // Virtual overrides must have the same code_seg. 17233 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 17234 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 17235 if ((NewCSA || OldCSA) && 17236 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 17237 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 17238 Diag(Old->getLocation(), diag::note_previous_declaration); 17239 return true; 17240 } 17241 17242 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 17243 17244 // If the calling conventions match, everything is fine 17245 if (NewCC == OldCC) 17246 return false; 17247 17248 // If the calling conventions mismatch because the new function is static, 17249 // suppress the calling convention mismatch error; the error about static 17250 // function override (err_static_overrides_virtual from 17251 // Sema::CheckFunctionDeclaration) is more clear. 17252 if (New->getStorageClass() == SC_Static) 17253 return false; 17254 17255 Diag(New->getLocation(), 17256 diag::err_conflicting_overriding_cc_attributes) 17257 << New->getDeclName() << New->getType() << Old->getType(); 17258 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 17259 return true; 17260 } 17261 17262 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 17263 const CXXMethodDecl *Old) { 17264 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); 17265 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); 17266 17267 if (Context.hasSameType(NewTy, OldTy) || 17268 NewTy->isDependentType() || OldTy->isDependentType()) 17269 return false; 17270 17271 // Check if the return types are covariant 17272 QualType NewClassTy, OldClassTy; 17273 17274 /// Both types must be pointers or references to classes. 17275 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 17276 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 17277 NewClassTy = NewPT->getPointeeType(); 17278 OldClassTy = OldPT->getPointeeType(); 17279 } 17280 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 17281 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 17282 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 17283 NewClassTy = NewRT->getPointeeType(); 17284 OldClassTy = OldRT->getPointeeType(); 17285 } 17286 } 17287 } 17288 17289 // The return types aren't either both pointers or references to a class type. 17290 if (NewClassTy.isNull()) { 17291 Diag(New->getLocation(), 17292 diag::err_different_return_type_for_overriding_virtual_function) 17293 << New->getDeclName() << NewTy << OldTy 17294 << New->getReturnTypeSourceRange(); 17295 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17296 << Old->getReturnTypeSourceRange(); 17297 17298 return true; 17299 } 17300 17301 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 17302 // C++14 [class.virtual]p8: 17303 // If the class type in the covariant return type of D::f differs from 17304 // that of B::f, the class type in the return type of D::f shall be 17305 // complete at the point of declaration of D::f or shall be the class 17306 // type D. 17307 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 17308 if (!RT->isBeingDefined() && 17309 RequireCompleteType(New->getLocation(), NewClassTy, 17310 diag::err_covariant_return_incomplete, 17311 New->getDeclName())) 17312 return true; 17313 } 17314 17315 // Check if the new class derives from the old class. 17316 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 17317 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 17318 << New->getDeclName() << NewTy << OldTy 17319 << New->getReturnTypeSourceRange(); 17320 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17321 << Old->getReturnTypeSourceRange(); 17322 return true; 17323 } 17324 17325 // Check if we the conversion from derived to base is valid. 17326 if (CheckDerivedToBaseConversion( 17327 NewClassTy, OldClassTy, 17328 diag::err_covariant_return_inaccessible_base, 17329 diag::err_covariant_return_ambiguous_derived_to_base_conv, 17330 New->getLocation(), New->getReturnTypeSourceRange(), 17331 New->getDeclName(), nullptr)) { 17332 // FIXME: this note won't trigger for delayed access control 17333 // diagnostics, and it's impossible to get an undelayed error 17334 // here from access control during the original parse because 17335 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 17336 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17337 << Old->getReturnTypeSourceRange(); 17338 return true; 17339 } 17340 } 17341 17342 // The qualifiers of the return types must be the same. 17343 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 17344 Diag(New->getLocation(), 17345 diag::err_covariant_return_type_different_qualifications) 17346 << New->getDeclName() << NewTy << OldTy 17347 << New->getReturnTypeSourceRange(); 17348 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17349 << Old->getReturnTypeSourceRange(); 17350 return true; 17351 } 17352 17353 17354 // The new class type must have the same or less qualifiers as the old type. 17355 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 17356 Diag(New->getLocation(), 17357 diag::err_covariant_return_type_class_type_more_qualified) 17358 << New->getDeclName() << NewTy << OldTy 17359 << New->getReturnTypeSourceRange(); 17360 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17361 << Old->getReturnTypeSourceRange(); 17362 return true; 17363 } 17364 17365 return false; 17366 } 17367 17368 /// Mark the given method pure. 17369 /// 17370 /// \param Method the method to be marked pure. 17371 /// 17372 /// \param InitRange the source range that covers the "0" initializer. 17373 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 17374 SourceLocation EndLoc = InitRange.getEnd(); 17375 if (EndLoc.isValid()) 17376 Method->setRangeEnd(EndLoc); 17377 17378 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 17379 Method->setPure(); 17380 return false; 17381 } 17382 17383 if (!Method->isInvalidDecl()) 17384 Diag(Method->getLocation(), diag::err_non_virtual_pure) 17385 << Method->getDeclName() << InitRange; 17386 return true; 17387 } 17388 17389 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 17390 if (D->getFriendObjectKind()) 17391 Diag(D->getLocation(), diag::err_pure_friend); 17392 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 17393 CheckPureMethod(M, ZeroLoc); 17394 else 17395 Diag(D->getLocation(), diag::err_illegal_initializer); 17396 } 17397 17398 /// Determine whether the given declaration is a global variable or 17399 /// static data member. 17400 static bool isNonlocalVariable(const Decl *D) { 17401 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 17402 return Var->hasGlobalStorage(); 17403 17404 return false; 17405 } 17406 17407 /// Invoked when we are about to parse an initializer for the declaration 17408 /// 'Dcl'. 17409 /// 17410 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 17411 /// static data member of class X, names should be looked up in the scope of 17412 /// class X. If the declaration had a scope specifier, a scope will have 17413 /// been created and passed in for this purpose. Otherwise, S will be null. 17414 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 17415 // If there is no declaration, there was an error parsing it. 17416 if (!D || D->isInvalidDecl()) 17417 return; 17418 17419 // We will always have a nested name specifier here, but this declaration 17420 // might not be out of line if the specifier names the current namespace: 17421 // extern int n; 17422 // int ::n = 0; 17423 if (S && D->isOutOfLine()) 17424 EnterDeclaratorContext(S, D->getDeclContext()); 17425 17426 // If we are parsing the initializer for a static data member, push a 17427 // new expression evaluation context that is associated with this static 17428 // data member. 17429 if (isNonlocalVariable(D)) 17430 PushExpressionEvaluationContext( 17431 ExpressionEvaluationContext::PotentiallyEvaluated, D); 17432 } 17433 17434 /// Invoked after we are finished parsing an initializer for the declaration D. 17435 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 17436 // If there is no declaration, there was an error parsing it. 17437 if (!D || D->isInvalidDecl()) 17438 return; 17439 17440 if (isNonlocalVariable(D)) 17441 PopExpressionEvaluationContext(); 17442 17443 if (S && D->isOutOfLine()) 17444 ExitDeclaratorContext(S); 17445 } 17446 17447 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 17448 /// C++ if/switch/while/for statement. 17449 /// e.g: "if (int x = f()) {...}" 17450 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 17451 // C++ 6.4p2: 17452 // The declarator shall not specify a function or an array. 17453 // The type-specifier-seq shall not contain typedef and shall not declare a 17454 // new class or enumeration. 17455 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 17456 "Parser allowed 'typedef' as storage class of condition decl."); 17457 17458 Decl *Dcl = ActOnDeclarator(S, D); 17459 if (!Dcl) 17460 return true; 17461 17462 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 17463 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 17464 << D.getSourceRange(); 17465 return true; 17466 } 17467 17468 return Dcl; 17469 } 17470 17471 void Sema::LoadExternalVTableUses() { 17472 if (!ExternalSource) 17473 return; 17474 17475 SmallVector<ExternalVTableUse, 4> VTables; 17476 ExternalSource->ReadUsedVTables(VTables); 17477 SmallVector<VTableUse, 4> NewUses; 17478 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 17479 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 17480 = VTablesUsed.find(VTables[I].Record); 17481 // Even if a definition wasn't required before, it may be required now. 17482 if (Pos != VTablesUsed.end()) { 17483 if (!Pos->second && VTables[I].DefinitionRequired) 17484 Pos->second = true; 17485 continue; 17486 } 17487 17488 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 17489 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 17490 } 17491 17492 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 17493 } 17494 17495 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 17496 bool DefinitionRequired) { 17497 // Ignore any vtable uses in unevaluated operands or for classes that do 17498 // not have a vtable. 17499 if (!Class->isDynamicClass() || Class->isDependentContext() || 17500 CurContext->isDependentContext() || isUnevaluatedContext()) 17501 return; 17502 // Do not mark as used if compiling for the device outside of the target 17503 // region. 17504 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 17505 !isInOpenMPDeclareTargetContext() && 17506 !isInOpenMPTargetExecutionDirective()) { 17507 if (!DefinitionRequired) 17508 MarkVirtualMembersReferenced(Loc, Class); 17509 return; 17510 } 17511 17512 // Try to insert this class into the map. 17513 LoadExternalVTableUses(); 17514 Class = Class->getCanonicalDecl(); 17515 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 17516 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 17517 if (!Pos.second) { 17518 // If we already had an entry, check to see if we are promoting this vtable 17519 // to require a definition. If so, we need to reappend to the VTableUses 17520 // list, since we may have already processed the first entry. 17521 if (DefinitionRequired && !Pos.first->second) { 17522 Pos.first->second = true; 17523 } else { 17524 // Otherwise, we can early exit. 17525 return; 17526 } 17527 } else { 17528 // The Microsoft ABI requires that we perform the destructor body 17529 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 17530 // the deleting destructor is emitted with the vtable, not with the 17531 // destructor definition as in the Itanium ABI. 17532 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17533 CXXDestructorDecl *DD = Class->getDestructor(); 17534 if (DD && DD->isVirtual() && !DD->isDeleted()) { 17535 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 17536 // If this is an out-of-line declaration, marking it referenced will 17537 // not do anything. Manually call CheckDestructor to look up operator 17538 // delete(). 17539 ContextRAII SavedContext(*this, DD); 17540 CheckDestructor(DD); 17541 } else { 17542 MarkFunctionReferenced(Loc, Class->getDestructor()); 17543 } 17544 } 17545 } 17546 } 17547 17548 // Local classes need to have their virtual members marked 17549 // immediately. For all other classes, we mark their virtual members 17550 // at the end of the translation unit. 17551 if (Class->isLocalClass()) 17552 MarkVirtualMembersReferenced(Loc, Class); 17553 else 17554 VTableUses.push_back(std::make_pair(Class, Loc)); 17555 } 17556 17557 bool Sema::DefineUsedVTables() { 17558 LoadExternalVTableUses(); 17559 if (VTableUses.empty()) 17560 return false; 17561 17562 // Note: The VTableUses vector could grow as a result of marking 17563 // the members of a class as "used", so we check the size each 17564 // time through the loop and prefer indices (which are stable) to 17565 // iterators (which are not). 17566 bool DefinedAnything = false; 17567 for (unsigned I = 0; I != VTableUses.size(); ++I) { 17568 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 17569 if (!Class) 17570 continue; 17571 TemplateSpecializationKind ClassTSK = 17572 Class->getTemplateSpecializationKind(); 17573 17574 SourceLocation Loc = VTableUses[I].second; 17575 17576 bool DefineVTable = true; 17577 17578 // If this class has a key function, but that key function is 17579 // defined in another translation unit, we don't need to emit the 17580 // vtable even though we're using it. 17581 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 17582 if (KeyFunction && !KeyFunction->hasBody()) { 17583 // The key function is in another translation unit. 17584 DefineVTable = false; 17585 TemplateSpecializationKind TSK = 17586 KeyFunction->getTemplateSpecializationKind(); 17587 assert(TSK != TSK_ExplicitInstantiationDefinition && 17588 TSK != TSK_ImplicitInstantiation && 17589 "Instantiations don't have key functions"); 17590 (void)TSK; 17591 } else if (!KeyFunction) { 17592 // If we have a class with no key function that is the subject 17593 // of an explicit instantiation declaration, suppress the 17594 // vtable; it will live with the explicit instantiation 17595 // definition. 17596 bool IsExplicitInstantiationDeclaration = 17597 ClassTSK == TSK_ExplicitInstantiationDeclaration; 17598 for (auto R : Class->redecls()) { 17599 TemplateSpecializationKind TSK 17600 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 17601 if (TSK == TSK_ExplicitInstantiationDeclaration) 17602 IsExplicitInstantiationDeclaration = true; 17603 else if (TSK == TSK_ExplicitInstantiationDefinition) { 17604 IsExplicitInstantiationDeclaration = false; 17605 break; 17606 } 17607 } 17608 17609 if (IsExplicitInstantiationDeclaration) 17610 DefineVTable = false; 17611 } 17612 17613 // The exception specifications for all virtual members may be needed even 17614 // if we are not providing an authoritative form of the vtable in this TU. 17615 // We may choose to emit it available_externally anyway. 17616 if (!DefineVTable) { 17617 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 17618 continue; 17619 } 17620 17621 // Mark all of the virtual members of this class as referenced, so 17622 // that we can build a vtable. Then, tell the AST consumer that a 17623 // vtable for this class is required. 17624 DefinedAnything = true; 17625 MarkVirtualMembersReferenced(Loc, Class); 17626 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 17627 if (VTablesUsed[Canonical]) 17628 Consumer.HandleVTable(Class); 17629 17630 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 17631 // no key function or the key function is inlined. Don't warn in C++ ABIs 17632 // that lack key functions, since the user won't be able to make one. 17633 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 17634 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 17635 const FunctionDecl *KeyFunctionDef = nullptr; 17636 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 17637 KeyFunctionDef->isInlined())) { 17638 Diag(Class->getLocation(), 17639 ClassTSK == TSK_ExplicitInstantiationDefinition 17640 ? diag::warn_weak_template_vtable 17641 : diag::warn_weak_vtable) 17642 << Class; 17643 } 17644 } 17645 } 17646 VTableUses.clear(); 17647 17648 return DefinedAnything; 17649 } 17650 17651 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 17652 const CXXRecordDecl *RD) { 17653 for (const auto *I : RD->methods()) 17654 if (I->isVirtual() && !I->isPure()) 17655 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 17656 } 17657 17658 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 17659 const CXXRecordDecl *RD, 17660 bool ConstexprOnly) { 17661 // Mark all functions which will appear in RD's vtable as used. 17662 CXXFinalOverriderMap FinalOverriders; 17663 RD->getFinalOverriders(FinalOverriders); 17664 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 17665 E = FinalOverriders.end(); 17666 I != E; ++I) { 17667 for (OverridingMethods::const_iterator OI = I->second.begin(), 17668 OE = I->second.end(); 17669 OI != OE; ++OI) { 17670 assert(OI->second.size() > 0 && "no final overrider"); 17671 CXXMethodDecl *Overrider = OI->second.front().Method; 17672 17673 // C++ [basic.def.odr]p2: 17674 // [...] A virtual member function is used if it is not pure. [...] 17675 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 17676 MarkFunctionReferenced(Loc, Overrider); 17677 } 17678 } 17679 17680 // Only classes that have virtual bases need a VTT. 17681 if (RD->getNumVBases() == 0) 17682 return; 17683 17684 for (const auto &I : RD->bases()) { 17685 const auto *Base = 17686 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 17687 if (Base->getNumVBases() == 0) 17688 continue; 17689 MarkVirtualMembersReferenced(Loc, Base); 17690 } 17691 } 17692 17693 /// SetIvarInitializers - This routine builds initialization ASTs for the 17694 /// Objective-C implementation whose ivars need be initialized. 17695 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 17696 if (!getLangOpts().CPlusPlus) 17697 return; 17698 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 17699 SmallVector<ObjCIvarDecl*, 8> ivars; 17700 CollectIvarsToConstructOrDestruct(OID, ivars); 17701 if (ivars.empty()) 17702 return; 17703 SmallVector<CXXCtorInitializer*, 32> AllToInit; 17704 for (unsigned i = 0; i < ivars.size(); i++) { 17705 FieldDecl *Field = ivars[i]; 17706 if (Field->isInvalidDecl()) 17707 continue; 17708 17709 CXXCtorInitializer *Member; 17710 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 17711 InitializationKind InitKind = 17712 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 17713 17714 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 17715 ExprResult MemberInit = 17716 InitSeq.Perform(*this, InitEntity, InitKind, None); 17717 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 17718 // Note, MemberInit could actually come back empty if no initialization 17719 // is required (e.g., because it would call a trivial default constructor) 17720 if (!MemberInit.get() || MemberInit.isInvalid()) 17721 continue; 17722 17723 Member = 17724 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 17725 SourceLocation(), 17726 MemberInit.getAs<Expr>(), 17727 SourceLocation()); 17728 AllToInit.push_back(Member); 17729 17730 // Be sure that the destructor is accessible and is marked as referenced. 17731 if (const RecordType *RecordTy = 17732 Context.getBaseElementType(Field->getType()) 17733 ->getAs<RecordType>()) { 17734 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 17735 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 17736 MarkFunctionReferenced(Field->getLocation(), Destructor); 17737 CheckDestructorAccess(Field->getLocation(), Destructor, 17738 PDiag(diag::err_access_dtor_ivar) 17739 << Context.getBaseElementType(Field->getType())); 17740 } 17741 } 17742 } 17743 ObjCImplementation->setIvarInitializers(Context, 17744 AllToInit.data(), AllToInit.size()); 17745 } 17746 } 17747 17748 static 17749 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 17750 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 17751 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 17752 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 17753 Sema &S) { 17754 if (Ctor->isInvalidDecl()) 17755 return; 17756 17757 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 17758 17759 // Target may not be determinable yet, for instance if this is a dependent 17760 // call in an uninstantiated template. 17761 if (Target) { 17762 const FunctionDecl *FNTarget = nullptr; 17763 (void)Target->hasBody(FNTarget); 17764 Target = const_cast<CXXConstructorDecl*>( 17765 cast_or_null<CXXConstructorDecl>(FNTarget)); 17766 } 17767 17768 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 17769 // Avoid dereferencing a null pointer here. 17770 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 17771 17772 if (!Current.insert(Canonical).second) 17773 return; 17774 17775 // We know that beyond here, we aren't chaining into a cycle. 17776 if (!Target || !Target->isDelegatingConstructor() || 17777 Target->isInvalidDecl() || Valid.count(TCanonical)) { 17778 Valid.insert(Current.begin(), Current.end()); 17779 Current.clear(); 17780 // We've hit a cycle. 17781 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 17782 Current.count(TCanonical)) { 17783 // If we haven't diagnosed this cycle yet, do so now. 17784 if (!Invalid.count(TCanonical)) { 17785 S.Diag((*Ctor->init_begin())->getSourceLocation(), 17786 diag::warn_delegating_ctor_cycle) 17787 << Ctor; 17788 17789 // Don't add a note for a function delegating directly to itself. 17790 if (TCanonical != Canonical) 17791 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 17792 17793 CXXConstructorDecl *C = Target; 17794 while (C->getCanonicalDecl() != Canonical) { 17795 const FunctionDecl *FNTarget = nullptr; 17796 (void)C->getTargetConstructor()->hasBody(FNTarget); 17797 assert(FNTarget && "Ctor cycle through bodiless function"); 17798 17799 C = const_cast<CXXConstructorDecl*>( 17800 cast<CXXConstructorDecl>(FNTarget)); 17801 S.Diag(C->getLocation(), diag::note_which_delegates_to); 17802 } 17803 } 17804 17805 Invalid.insert(Current.begin(), Current.end()); 17806 Current.clear(); 17807 } else { 17808 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 17809 } 17810 } 17811 17812 17813 void Sema::CheckDelegatingCtorCycles() { 17814 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 17815 17816 for (DelegatingCtorDeclsType::iterator 17817 I = DelegatingCtorDecls.begin(ExternalSource), 17818 E = DelegatingCtorDecls.end(); 17819 I != E; ++I) 17820 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 17821 17822 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 17823 (*CI)->setInvalidDecl(); 17824 } 17825 17826 namespace { 17827 /// AST visitor that finds references to the 'this' expression. 17828 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 17829 Sema &S; 17830 17831 public: 17832 explicit FindCXXThisExpr(Sema &S) : S(S) { } 17833 17834 bool VisitCXXThisExpr(CXXThisExpr *E) { 17835 S.Diag(E->getLocation(), diag::err_this_static_member_func) 17836 << E->isImplicit(); 17837 return false; 17838 } 17839 }; 17840 } 17841 17842 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 17843 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17844 if (!TSInfo) 17845 return false; 17846 17847 TypeLoc TL = TSInfo->getTypeLoc(); 17848 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17849 if (!ProtoTL) 17850 return false; 17851 17852 // C++11 [expr.prim.general]p3: 17853 // [The expression this] shall not appear before the optional 17854 // cv-qualifier-seq and it shall not appear within the declaration of a 17855 // static member function (although its type and value category are defined 17856 // within a static member function as they are within a non-static member 17857 // function). [ Note: this is because declaration matching does not occur 17858 // until the complete declarator is known. - end note ] 17859 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17860 FindCXXThisExpr Finder(*this); 17861 17862 // If the return type came after the cv-qualifier-seq, check it now. 17863 if (Proto->hasTrailingReturn() && 17864 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 17865 return true; 17866 17867 // Check the exception specification. 17868 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 17869 return true; 17870 17871 // Check the trailing requires clause 17872 if (Expr *E = Method->getTrailingRequiresClause()) 17873 if (!Finder.TraverseStmt(E)) 17874 return true; 17875 17876 return checkThisInStaticMemberFunctionAttributes(Method); 17877 } 17878 17879 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 17880 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17881 if (!TSInfo) 17882 return false; 17883 17884 TypeLoc TL = TSInfo->getTypeLoc(); 17885 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17886 if (!ProtoTL) 17887 return false; 17888 17889 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17890 FindCXXThisExpr Finder(*this); 17891 17892 switch (Proto->getExceptionSpecType()) { 17893 case EST_Unparsed: 17894 case EST_Uninstantiated: 17895 case EST_Unevaluated: 17896 case EST_BasicNoexcept: 17897 case EST_NoThrow: 17898 case EST_DynamicNone: 17899 case EST_MSAny: 17900 case EST_None: 17901 break; 17902 17903 case EST_DependentNoexcept: 17904 case EST_NoexceptFalse: 17905 case EST_NoexceptTrue: 17906 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 17907 return true; 17908 LLVM_FALLTHROUGH; 17909 17910 case EST_Dynamic: 17911 for (const auto &E : Proto->exceptions()) { 17912 if (!Finder.TraverseType(E)) 17913 return true; 17914 } 17915 break; 17916 } 17917 17918 return false; 17919 } 17920 17921 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 17922 FindCXXThisExpr Finder(*this); 17923 17924 // Check attributes. 17925 for (const auto *A : Method->attrs()) { 17926 // FIXME: This should be emitted by tblgen. 17927 Expr *Arg = nullptr; 17928 ArrayRef<Expr *> Args; 17929 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 17930 Arg = G->getArg(); 17931 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 17932 Arg = G->getArg(); 17933 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 17934 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 17935 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 17936 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 17937 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 17938 Arg = ETLF->getSuccessValue(); 17939 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 17940 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 17941 Arg = STLF->getSuccessValue(); 17942 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 17943 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 17944 Arg = LR->getArg(); 17945 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 17946 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 17947 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 17948 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17949 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 17950 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17951 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 17952 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17953 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 17954 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17955 17956 if (Arg && !Finder.TraverseStmt(Arg)) 17957 return true; 17958 17959 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 17960 if (!Finder.TraverseStmt(Args[I])) 17961 return true; 17962 } 17963 } 17964 17965 return false; 17966 } 17967 17968 void Sema::checkExceptionSpecification( 17969 bool IsTopLevel, ExceptionSpecificationType EST, 17970 ArrayRef<ParsedType> DynamicExceptions, 17971 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 17972 SmallVectorImpl<QualType> &Exceptions, 17973 FunctionProtoType::ExceptionSpecInfo &ESI) { 17974 Exceptions.clear(); 17975 ESI.Type = EST; 17976 if (EST == EST_Dynamic) { 17977 Exceptions.reserve(DynamicExceptions.size()); 17978 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 17979 // FIXME: Preserve type source info. 17980 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 17981 17982 if (IsTopLevel) { 17983 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 17984 collectUnexpandedParameterPacks(ET, Unexpanded); 17985 if (!Unexpanded.empty()) { 17986 DiagnoseUnexpandedParameterPacks( 17987 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 17988 Unexpanded); 17989 continue; 17990 } 17991 } 17992 17993 // Check that the type is valid for an exception spec, and 17994 // drop it if not. 17995 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 17996 Exceptions.push_back(ET); 17997 } 17998 ESI.Exceptions = Exceptions; 17999 return; 18000 } 18001 18002 if (isComputedNoexcept(EST)) { 18003 assert((NoexceptExpr->isTypeDependent() || 18004 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 18005 Context.BoolTy) && 18006 "Parser should have made sure that the expression is boolean"); 18007 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 18008 ESI.Type = EST_BasicNoexcept; 18009 return; 18010 } 18011 18012 ESI.NoexceptExpr = NoexceptExpr; 18013 return; 18014 } 18015 } 18016 18017 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 18018 ExceptionSpecificationType EST, 18019 SourceRange SpecificationRange, 18020 ArrayRef<ParsedType> DynamicExceptions, 18021 ArrayRef<SourceRange> DynamicExceptionRanges, 18022 Expr *NoexceptExpr) { 18023 if (!MethodD) 18024 return; 18025 18026 // Dig out the method we're referring to. 18027 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 18028 MethodD = FunTmpl->getTemplatedDecl(); 18029 18030 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 18031 if (!Method) 18032 return; 18033 18034 // Check the exception specification. 18035 llvm::SmallVector<QualType, 4> Exceptions; 18036 FunctionProtoType::ExceptionSpecInfo ESI; 18037 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 18038 DynamicExceptionRanges, NoexceptExpr, Exceptions, 18039 ESI); 18040 18041 // Update the exception specification on the function type. 18042 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 18043 18044 if (Method->isStatic()) 18045 checkThisInStaticMemberFunctionExceptionSpec(Method); 18046 18047 if (Method->isVirtual()) { 18048 // Check overrides, which we previously had to delay. 18049 for (const CXXMethodDecl *O : Method->overridden_methods()) 18050 CheckOverridingFunctionExceptionSpec(Method, O); 18051 } 18052 } 18053 18054 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 18055 /// 18056 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 18057 SourceLocation DeclStart, Declarator &D, 18058 Expr *BitWidth, 18059 InClassInitStyle InitStyle, 18060 AccessSpecifier AS, 18061 const ParsedAttr &MSPropertyAttr) { 18062 IdentifierInfo *II = D.getIdentifier(); 18063 if (!II) { 18064 Diag(DeclStart, diag::err_anonymous_property); 18065 return nullptr; 18066 } 18067 SourceLocation Loc = D.getIdentifierLoc(); 18068 18069 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 18070 QualType T = TInfo->getType(); 18071 if (getLangOpts().CPlusPlus) { 18072 CheckExtraCXXDefaultArguments(D); 18073 18074 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 18075 UPPC_DataMemberType)) { 18076 D.setInvalidType(); 18077 T = Context.IntTy; 18078 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 18079 } 18080 } 18081 18082 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 18083 18084 if (D.getDeclSpec().isInlineSpecified()) 18085 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 18086 << getLangOpts().CPlusPlus17; 18087 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 18088 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 18089 diag::err_invalid_thread) 18090 << DeclSpec::getSpecifierName(TSCS); 18091 18092 // Check to see if this name was declared as a member previously 18093 NamedDecl *PrevDecl = nullptr; 18094 LookupResult Previous(*this, II, Loc, LookupMemberName, 18095 ForVisibleRedeclaration); 18096 LookupName(Previous, S); 18097 switch (Previous.getResultKind()) { 18098 case LookupResult::Found: 18099 case LookupResult::FoundUnresolvedValue: 18100 PrevDecl = Previous.getAsSingle<NamedDecl>(); 18101 break; 18102 18103 case LookupResult::FoundOverloaded: 18104 PrevDecl = Previous.getRepresentativeDecl(); 18105 break; 18106 18107 case LookupResult::NotFound: 18108 case LookupResult::NotFoundInCurrentInstantiation: 18109 case LookupResult::Ambiguous: 18110 break; 18111 } 18112 18113 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18114 // Maybe we will complain about the shadowed template parameter. 18115 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 18116 // Just pretend that we didn't see the previous declaration. 18117 PrevDecl = nullptr; 18118 } 18119 18120 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 18121 PrevDecl = nullptr; 18122 18123 SourceLocation TSSL = D.getBeginLoc(); 18124 MSPropertyDecl *NewPD = 18125 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 18126 MSPropertyAttr.getPropertyDataGetter(), 18127 MSPropertyAttr.getPropertyDataSetter()); 18128 ProcessDeclAttributes(TUScope, NewPD, D); 18129 NewPD->setAccess(AS); 18130 18131 if (NewPD->isInvalidDecl()) 18132 Record->setInvalidDecl(); 18133 18134 if (D.getDeclSpec().isModulePrivateSpecified()) 18135 NewPD->setModulePrivate(); 18136 18137 if (NewPD->isInvalidDecl() && PrevDecl) { 18138 // Don't introduce NewFD into scope; there's already something 18139 // with the same name in the same scope. 18140 } else if (II) { 18141 PushOnScopeChains(NewPD, S); 18142 } else 18143 Record->addDecl(NewPD); 18144 18145 return NewPD; 18146 } 18147 18148 void Sema::ActOnStartFunctionDeclarationDeclarator( 18149 Declarator &Declarator, unsigned TemplateParameterDepth) { 18150 auto &Info = InventedParameterInfos.emplace_back(); 18151 TemplateParameterList *ExplicitParams = nullptr; 18152 ArrayRef<TemplateParameterList *> ExplicitLists = 18153 Declarator.getTemplateParameterLists(); 18154 if (!ExplicitLists.empty()) { 18155 bool IsMemberSpecialization, IsInvalid; 18156 ExplicitParams = MatchTemplateParametersToScopeSpecifier( 18157 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), 18158 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, 18159 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, 18160 /*SuppressDiagnostic=*/true); 18161 } 18162 if (ExplicitParams) { 18163 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); 18164 for (NamedDecl *Param : *ExplicitParams) 18165 Info.TemplateParams.push_back(Param); 18166 Info.NumExplicitTemplateParams = ExplicitParams->size(); 18167 } else { 18168 Info.AutoTemplateParameterDepth = TemplateParameterDepth; 18169 Info.NumExplicitTemplateParams = 0; 18170 } 18171 } 18172 18173 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { 18174 auto &FSI = InventedParameterInfos.back(); 18175 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { 18176 if (FSI.NumExplicitTemplateParams != 0) { 18177 TemplateParameterList *ExplicitParams = 18178 Declarator.getTemplateParameterLists().back(); 18179 Declarator.setInventedTemplateParameterList( 18180 TemplateParameterList::Create( 18181 Context, ExplicitParams->getTemplateLoc(), 18182 ExplicitParams->getLAngleLoc(), FSI.TemplateParams, 18183 ExplicitParams->getRAngleLoc(), 18184 ExplicitParams->getRequiresClause())); 18185 } else { 18186 Declarator.setInventedTemplateParameterList( 18187 TemplateParameterList::Create( 18188 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, 18189 SourceLocation(), /*RequiresClause=*/nullptr)); 18190 } 18191 } 18192 InventedParameterInfos.pop_back(); 18193 } 18194