1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for C++ declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTConsumer.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/ASTLambda.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/ComparisonCategories.h" 20 #include "clang/AST/EvaluatedExprVisitor.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/RecordLayout.h" 23 #include "clang/AST/RecursiveASTVisitor.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/AST/TypeLoc.h" 26 #include "clang/AST/TypeOrdering.h" 27 #include "clang/Basic/AttributeCommonInfo.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/LiteralSupport.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Sema/CXXFieldCollector.h" 33 #include "clang/Sema/DeclSpec.h" 34 #include "clang/Sema/Initialization.h" 35 #include "clang/Sema/Lookup.h" 36 #include "clang/Sema/ParsedTemplate.h" 37 #include "clang/Sema/Scope.h" 38 #include "clang/Sema/ScopeInfo.h" 39 #include "clang/Sema/SemaInternal.h" 40 #include "clang/Sema/Template.h" 41 #include "llvm/ADT/ScopeExit.h" 42 #include "llvm/ADT/SmallString.h" 43 #include "llvm/ADT/STLExtras.h" 44 #include "llvm/ADT/StringExtras.h" 45 #include <map> 46 #include <set> 47 48 using namespace clang; 49 50 //===----------------------------------------------------------------------===// 51 // CheckDefaultArgumentVisitor 52 //===----------------------------------------------------------------------===// 53 54 namespace { 55 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 56 /// the default argument of a parameter to determine whether it 57 /// contains any ill-formed subexpressions. For example, this will 58 /// diagnose the use of local variables or parameters within the 59 /// default argument expression. 60 class CheckDefaultArgumentVisitor 61 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> { 62 Sema &S; 63 const Expr *DefaultArg; 64 65 public: 66 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg) 67 : S(S), DefaultArg(DefaultArg) {} 68 69 bool VisitExpr(const Expr *Node); 70 bool VisitDeclRefExpr(const DeclRefExpr *DRE); 71 bool VisitCXXThisExpr(const CXXThisExpr *ThisE); 72 bool VisitLambdaExpr(const LambdaExpr *Lambda); 73 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE); 74 }; 75 76 /// VisitExpr - Visit all of the children of this expression. 77 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) { 78 bool IsInvalid = false; 79 for (const Stmt *SubStmt : Node->children()) 80 IsInvalid |= Visit(SubStmt); 81 return IsInvalid; 82 } 83 84 /// VisitDeclRefExpr - Visit a reference to a declaration, to 85 /// determine whether this declaration can be used in the default 86 /// argument expression. 87 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) { 88 const NamedDecl *Decl = DRE->getDecl(); 89 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) { 90 // C++ [dcl.fct.default]p9: 91 // [...] parameters of a function shall not be used in default 92 // argument expressions, even if they are not evaluated. [...] 93 // 94 // C++17 [dcl.fct.default]p9 (by CWG 2082): 95 // [...] A parameter shall not appear as a potentially-evaluated 96 // expression in a default argument. [...] 97 // 98 if (DRE->isNonOdrUse() != NOUR_Unevaluated) 99 return S.Diag(DRE->getBeginLoc(), 100 diag::err_param_default_argument_references_param) 101 << Param->getDeclName() << DefaultArg->getSourceRange(); 102 } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) { 103 // C++ [dcl.fct.default]p7: 104 // Local variables shall not be used in default argument 105 // expressions. 106 // 107 // C++17 [dcl.fct.default]p7 (by CWG 2082): 108 // A local variable shall not appear as a potentially-evaluated 109 // expression in a default argument. 110 // 111 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346): 112 // Note: A local variable cannot be odr-used (6.3) in a default argument. 113 // 114 if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse()) 115 return S.Diag(DRE->getBeginLoc(), 116 diag::err_param_default_argument_references_local) 117 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 118 } 119 120 return false; 121 } 122 123 /// VisitCXXThisExpr - Visit a C++ "this" expression. 124 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) { 125 // C++ [dcl.fct.default]p8: 126 // The keyword this shall not be used in a default argument of a 127 // member function. 128 return S.Diag(ThisE->getBeginLoc(), 129 diag::err_param_default_argument_references_this) 130 << ThisE->getSourceRange(); 131 } 132 133 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr( 134 const PseudoObjectExpr *POE) { 135 bool Invalid = false; 136 for (const Expr *E : POE->semantics()) { 137 // Look through bindings. 138 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) { 139 E = OVE->getSourceExpr(); 140 assert(E && "pseudo-object binding without source expression?"); 141 } 142 143 Invalid |= Visit(E); 144 } 145 return Invalid; 146 } 147 148 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) { 149 // C++11 [expr.lambda.prim]p13: 150 // A lambda-expression appearing in a default argument shall not 151 // implicitly or explicitly capture any entity. 152 if (Lambda->capture_begin() == Lambda->capture_end()) 153 return false; 154 155 return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); 156 } 157 } // namespace 158 159 void 160 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 161 const CXXMethodDecl *Method) { 162 // If we have an MSAny spec already, don't bother. 163 if (!Method || ComputedEST == EST_MSAny) 164 return; 165 166 const FunctionProtoType *Proto 167 = Method->getType()->getAs<FunctionProtoType>(); 168 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 169 if (!Proto) 170 return; 171 172 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 173 174 // If we have a throw-all spec at this point, ignore the function. 175 if (ComputedEST == EST_None) 176 return; 177 178 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 179 EST = EST_BasicNoexcept; 180 181 switch (EST) { 182 case EST_Unparsed: 183 case EST_Uninstantiated: 184 case EST_Unevaluated: 185 llvm_unreachable("should not see unresolved exception specs here"); 186 187 // If this function can throw any exceptions, make a note of that. 188 case EST_MSAny: 189 case EST_None: 190 // FIXME: Whichever we see last of MSAny and None determines our result. 191 // We should make a consistent, order-independent choice here. 192 ClearExceptions(); 193 ComputedEST = EST; 194 return; 195 case EST_NoexceptFalse: 196 ClearExceptions(); 197 ComputedEST = EST_None; 198 return; 199 // FIXME: If the call to this decl is using any of its default arguments, we 200 // need to search them for potentially-throwing calls. 201 // If this function has a basic noexcept, it doesn't affect the outcome. 202 case EST_BasicNoexcept: 203 case EST_NoexceptTrue: 204 case EST_NoThrow: 205 return; 206 // If we're still at noexcept(true) and there's a throw() callee, 207 // change to that specification. 208 case EST_DynamicNone: 209 if (ComputedEST == EST_BasicNoexcept) 210 ComputedEST = EST_DynamicNone; 211 return; 212 case EST_DependentNoexcept: 213 llvm_unreachable( 214 "should not generate implicit declarations for dependent cases"); 215 case EST_Dynamic: 216 break; 217 } 218 assert(EST == EST_Dynamic && "EST case not considered earlier."); 219 assert(ComputedEST != EST_None && 220 "Shouldn't collect exceptions when throw-all is guaranteed."); 221 ComputedEST = EST_Dynamic; 222 // Record the exceptions in this function's exception specification. 223 for (const auto &E : Proto->exceptions()) 224 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 225 Exceptions.push_back(E); 226 } 227 228 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) { 229 if (!S || ComputedEST == EST_MSAny) 230 return; 231 232 // FIXME: 233 // 234 // C++0x [except.spec]p14: 235 // [An] implicit exception-specification specifies the type-id T if and 236 // only if T is allowed by the exception-specification of a function directly 237 // invoked by f's implicit definition; f shall allow all exceptions if any 238 // function it directly invokes allows all exceptions, and f shall allow no 239 // exceptions if every function it directly invokes allows no exceptions. 240 // 241 // Note in particular that if an implicit exception-specification is generated 242 // for a function containing a throw-expression, that specification can still 243 // be noexcept(true). 244 // 245 // Note also that 'directly invoked' is not defined in the standard, and there 246 // is no indication that we should only consider potentially-evaluated calls. 247 // 248 // Ultimately we should implement the intent of the standard: the exception 249 // specification should be the set of exceptions which can be thrown by the 250 // implicit definition. For now, we assume that any non-nothrow expression can 251 // throw any exception. 252 253 if (Self->canThrow(S)) 254 ComputedEST = EST_None; 255 } 256 257 ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 258 SourceLocation EqualLoc) { 259 if (RequireCompleteType(Param->getLocation(), Param->getType(), 260 diag::err_typecheck_decl_incomplete_type)) 261 return true; 262 263 // C++ [dcl.fct.default]p5 264 // A default argument expression is implicitly converted (clause 265 // 4) to the parameter type. The default argument expression has 266 // the same semantic constraints as the initializer expression in 267 // a declaration of a variable of the parameter type, using the 268 // copy-initialization semantics (8.5). 269 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 270 Param); 271 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 272 EqualLoc); 273 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 274 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 275 if (Result.isInvalid()) 276 return true; 277 Arg = Result.getAs<Expr>(); 278 279 CheckCompletedExpr(Arg, EqualLoc); 280 Arg = MaybeCreateExprWithCleanups(Arg); 281 282 return Arg; 283 } 284 285 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 286 SourceLocation EqualLoc) { 287 // Add the default argument to the parameter 288 Param->setDefaultArg(Arg); 289 290 // We have already instantiated this parameter; provide each of the 291 // instantiations with the uninstantiated default argument. 292 UnparsedDefaultArgInstantiationsMap::iterator InstPos 293 = UnparsedDefaultArgInstantiations.find(Param); 294 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 295 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 296 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 297 298 // We're done tracking this parameter's instantiations. 299 UnparsedDefaultArgInstantiations.erase(InstPos); 300 } 301 } 302 303 /// ActOnParamDefaultArgument - Check whether the default argument 304 /// provided for a function parameter is well-formed. If so, attach it 305 /// to the parameter declaration. 306 void 307 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 308 Expr *DefaultArg) { 309 if (!param || !DefaultArg) 310 return; 311 312 ParmVarDecl *Param = cast<ParmVarDecl>(param); 313 UnparsedDefaultArgLocs.erase(Param); 314 315 auto Fail = [&] { 316 Param->setInvalidDecl(); 317 Param->setDefaultArg(new (Context) OpaqueValueExpr( 318 EqualLoc, Param->getType().getNonReferenceType(), VK_RValue)); 319 }; 320 321 // Default arguments are only permitted in C++ 322 if (!getLangOpts().CPlusPlus) { 323 Diag(EqualLoc, diag::err_param_default_argument) 324 << DefaultArg->getSourceRange(); 325 return Fail(); 326 } 327 328 // Check for unexpanded parameter packs. 329 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 330 return Fail(); 331 } 332 333 // C++11 [dcl.fct.default]p3 334 // A default argument expression [...] shall not be specified for a 335 // parameter pack. 336 if (Param->isParameterPack()) { 337 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 338 << DefaultArg->getSourceRange(); 339 // Recover by discarding the default argument. 340 Param->setDefaultArg(nullptr); 341 return; 342 } 343 344 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc); 345 if (Result.isInvalid()) 346 return Fail(); 347 348 DefaultArg = Result.getAs<Expr>(); 349 350 // Check that the default argument is well-formed 351 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg); 352 if (DefaultArgChecker.Visit(DefaultArg)) 353 return Fail(); 354 355 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 356 } 357 358 /// ActOnParamUnparsedDefaultArgument - We've seen a default 359 /// argument for a function parameter, but we can't parse it yet 360 /// because we're inside a class definition. Note that this default 361 /// argument will be parsed later. 362 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 363 SourceLocation EqualLoc, 364 SourceLocation ArgLoc) { 365 if (!param) 366 return; 367 368 ParmVarDecl *Param = cast<ParmVarDecl>(param); 369 Param->setUnparsedDefaultArg(); 370 UnparsedDefaultArgLocs[Param] = ArgLoc; 371 } 372 373 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 374 /// the default argument for the parameter param failed. 375 void Sema::ActOnParamDefaultArgumentError(Decl *param, 376 SourceLocation EqualLoc) { 377 if (!param) 378 return; 379 380 ParmVarDecl *Param = cast<ParmVarDecl>(param); 381 Param->setInvalidDecl(); 382 UnparsedDefaultArgLocs.erase(Param); 383 Param->setDefaultArg(new(Context) 384 OpaqueValueExpr(EqualLoc, 385 Param->getType().getNonReferenceType(), 386 VK_RValue)); 387 } 388 389 /// CheckExtraCXXDefaultArguments - Check for any extra default 390 /// arguments in the declarator, which is not a function declaration 391 /// or definition and therefore is not permitted to have default 392 /// arguments. This routine should be invoked for every declarator 393 /// that is not a function declaration or definition. 394 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 395 // C++ [dcl.fct.default]p3 396 // A default argument expression shall be specified only in the 397 // parameter-declaration-clause of a function declaration or in a 398 // template-parameter (14.1). It shall not be specified for a 399 // parameter pack. If it is specified in a 400 // parameter-declaration-clause, it shall not occur within a 401 // declarator or abstract-declarator of a parameter-declaration. 402 bool MightBeFunction = D.isFunctionDeclarationContext(); 403 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 404 DeclaratorChunk &chunk = D.getTypeObject(i); 405 if (chunk.Kind == DeclaratorChunk::Function) { 406 if (MightBeFunction) { 407 // This is a function declaration. It can have default arguments, but 408 // keep looking in case its return type is a function type with default 409 // arguments. 410 MightBeFunction = false; 411 continue; 412 } 413 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 414 ++argIdx) { 415 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 416 if (Param->hasUnparsedDefaultArg()) { 417 std::unique_ptr<CachedTokens> Toks = 418 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 419 SourceRange SR; 420 if (Toks->size() > 1) 421 SR = SourceRange((*Toks)[1].getLocation(), 422 Toks->back().getLocation()); 423 else 424 SR = UnparsedDefaultArgLocs[Param]; 425 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 426 << SR; 427 } else if (Param->getDefaultArg()) { 428 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 429 << Param->getDefaultArg()->getSourceRange(); 430 Param->setDefaultArg(nullptr); 431 } 432 } 433 } else if (chunk.Kind != DeclaratorChunk::Paren) { 434 MightBeFunction = false; 435 } 436 } 437 } 438 439 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 440 return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) { 441 return P->hasDefaultArg() && !P->hasInheritedDefaultArg(); 442 }); 443 } 444 445 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 446 /// function, once we already know that they have the same 447 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 448 /// error, false otherwise. 449 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 450 Scope *S) { 451 bool Invalid = false; 452 453 // The declaration context corresponding to the scope is the semantic 454 // parent, unless this is a local function declaration, in which case 455 // it is that surrounding function. 456 DeclContext *ScopeDC = New->isLocalExternDecl() 457 ? New->getLexicalDeclContext() 458 : New->getDeclContext(); 459 460 // Find the previous declaration for the purpose of default arguments. 461 FunctionDecl *PrevForDefaultArgs = Old; 462 for (/**/; PrevForDefaultArgs; 463 // Don't bother looking back past the latest decl if this is a local 464 // extern declaration; nothing else could work. 465 PrevForDefaultArgs = New->isLocalExternDecl() 466 ? nullptr 467 : PrevForDefaultArgs->getPreviousDecl()) { 468 // Ignore hidden declarations. 469 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 470 continue; 471 472 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 473 !New->isCXXClassMember()) { 474 // Ignore default arguments of old decl if they are not in 475 // the same scope and this is not an out-of-line definition of 476 // a member function. 477 continue; 478 } 479 480 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 481 // If only one of these is a local function declaration, then they are 482 // declared in different scopes, even though isDeclInScope may think 483 // they're in the same scope. (If both are local, the scope check is 484 // sufficient, and if neither is local, then they are in the same scope.) 485 continue; 486 } 487 488 // We found the right previous declaration. 489 break; 490 } 491 492 // C++ [dcl.fct.default]p4: 493 // For non-template functions, default arguments can be added in 494 // later declarations of a function in the same 495 // scope. Declarations in different scopes have completely 496 // distinct sets of default arguments. That is, declarations in 497 // inner scopes do not acquire default arguments from 498 // declarations in outer scopes, and vice versa. In a given 499 // function declaration, all parameters subsequent to a 500 // parameter with a default argument shall have default 501 // arguments supplied in this or previous declarations. A 502 // default argument shall not be redefined by a later 503 // declaration (not even to the same value). 504 // 505 // C++ [dcl.fct.default]p6: 506 // Except for member functions of class templates, the default arguments 507 // in a member function definition that appears outside of the class 508 // definition are added to the set of default arguments provided by the 509 // member function declaration in the class definition. 510 for (unsigned p = 0, NumParams = PrevForDefaultArgs 511 ? PrevForDefaultArgs->getNumParams() 512 : 0; 513 p < NumParams; ++p) { 514 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 515 ParmVarDecl *NewParam = New->getParamDecl(p); 516 517 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 518 bool NewParamHasDfl = NewParam->hasDefaultArg(); 519 520 if (OldParamHasDfl && NewParamHasDfl) { 521 unsigned DiagDefaultParamID = 522 diag::err_param_default_argument_redefinition; 523 524 // MSVC accepts that default parameters be redefined for member functions 525 // of template class. The new default parameter's value is ignored. 526 Invalid = true; 527 if (getLangOpts().MicrosoftExt) { 528 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 529 if (MD && MD->getParent()->getDescribedClassTemplate()) { 530 // Merge the old default argument into the new parameter. 531 NewParam->setHasInheritedDefaultArg(); 532 if (OldParam->hasUninstantiatedDefaultArg()) 533 NewParam->setUninstantiatedDefaultArg( 534 OldParam->getUninstantiatedDefaultArg()); 535 else 536 NewParam->setDefaultArg(OldParam->getInit()); 537 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 538 Invalid = false; 539 } 540 } 541 542 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 543 // hint here. Alternatively, we could walk the type-source information 544 // for NewParam to find the last source location in the type... but it 545 // isn't worth the effort right now. This is the kind of test case that 546 // is hard to get right: 547 // int f(int); 548 // void g(int (*fp)(int) = f); 549 // void g(int (*fp)(int) = &f); 550 Diag(NewParam->getLocation(), DiagDefaultParamID) 551 << NewParam->getDefaultArgRange(); 552 553 // Look for the function declaration where the default argument was 554 // actually written, which may be a declaration prior to Old. 555 for (auto Older = PrevForDefaultArgs; 556 OldParam->hasInheritedDefaultArg(); /**/) { 557 Older = Older->getPreviousDecl(); 558 OldParam = Older->getParamDecl(p); 559 } 560 561 Diag(OldParam->getLocation(), diag::note_previous_definition) 562 << OldParam->getDefaultArgRange(); 563 } else if (OldParamHasDfl) { 564 // Merge the old default argument into the new parameter unless the new 565 // function is a friend declaration in a template class. In the latter 566 // case the default arguments will be inherited when the friend 567 // declaration will be instantiated. 568 if (New->getFriendObjectKind() == Decl::FOK_None || 569 !New->getLexicalDeclContext()->isDependentContext()) { 570 // It's important to use getInit() here; getDefaultArg() 571 // strips off any top-level ExprWithCleanups. 572 NewParam->setHasInheritedDefaultArg(); 573 if (OldParam->hasUnparsedDefaultArg()) 574 NewParam->setUnparsedDefaultArg(); 575 else if (OldParam->hasUninstantiatedDefaultArg()) 576 NewParam->setUninstantiatedDefaultArg( 577 OldParam->getUninstantiatedDefaultArg()); 578 else 579 NewParam->setDefaultArg(OldParam->getInit()); 580 } 581 } else if (NewParamHasDfl) { 582 if (New->getDescribedFunctionTemplate()) { 583 // Paragraph 4, quoted above, only applies to non-template functions. 584 Diag(NewParam->getLocation(), 585 diag::err_param_default_argument_template_redecl) 586 << NewParam->getDefaultArgRange(); 587 Diag(PrevForDefaultArgs->getLocation(), 588 diag::note_template_prev_declaration) 589 << false; 590 } else if (New->getTemplateSpecializationKind() 591 != TSK_ImplicitInstantiation && 592 New->getTemplateSpecializationKind() != TSK_Undeclared) { 593 // C++ [temp.expr.spec]p21: 594 // Default function arguments shall not be specified in a declaration 595 // or a definition for one of the following explicit specializations: 596 // - the explicit specialization of a function template; 597 // - the explicit specialization of a member function template; 598 // - the explicit specialization of a member function of a class 599 // template where the class template specialization to which the 600 // member function specialization belongs is implicitly 601 // instantiated. 602 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 603 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 604 << New->getDeclName() 605 << NewParam->getDefaultArgRange(); 606 } else if (New->getDeclContext()->isDependentContext()) { 607 // C++ [dcl.fct.default]p6 (DR217): 608 // Default arguments for a member function of a class template shall 609 // be specified on the initial declaration of the member function 610 // within the class template. 611 // 612 // Reading the tea leaves a bit in DR217 and its reference to DR205 613 // leads me to the conclusion that one cannot add default function 614 // arguments for an out-of-line definition of a member function of a 615 // dependent type. 616 int WhichKind = 2; 617 if (CXXRecordDecl *Record 618 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 619 if (Record->getDescribedClassTemplate()) 620 WhichKind = 0; 621 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 622 WhichKind = 1; 623 else 624 WhichKind = 2; 625 } 626 627 Diag(NewParam->getLocation(), 628 diag::err_param_default_argument_member_template_redecl) 629 << WhichKind 630 << NewParam->getDefaultArgRange(); 631 } 632 } 633 } 634 635 // DR1344: If a default argument is added outside a class definition and that 636 // default argument makes the function a special member function, the program 637 // is ill-formed. This can only happen for constructors. 638 if (isa<CXXConstructorDecl>(New) && 639 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 640 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 641 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 642 if (NewSM != OldSM) { 643 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 644 assert(NewParam->hasDefaultArg()); 645 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 646 << NewParam->getDefaultArgRange() << NewSM; 647 Diag(Old->getLocation(), diag::note_previous_declaration); 648 } 649 } 650 651 const FunctionDecl *Def; 652 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 653 // template has a constexpr specifier then all its declarations shall 654 // contain the constexpr specifier. 655 if (New->getConstexprKind() != Old->getConstexprKind()) { 656 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 657 << New << static_cast<int>(New->getConstexprKind()) 658 << static_cast<int>(Old->getConstexprKind()); 659 Diag(Old->getLocation(), diag::note_previous_declaration); 660 Invalid = true; 661 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 662 Old->isDefined(Def) && 663 // If a friend function is inlined but does not have 'inline' 664 // specifier, it is a definition. Do not report attribute conflict 665 // in this case, redefinition will be diagnosed later. 666 (New->isInlineSpecified() || 667 New->getFriendObjectKind() == Decl::FOK_None)) { 668 // C++11 [dcl.fcn.spec]p4: 669 // If the definition of a function appears in a translation unit before its 670 // first declaration as inline, the program is ill-formed. 671 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 672 Diag(Def->getLocation(), diag::note_previous_definition); 673 Invalid = true; 674 } 675 676 // C++17 [temp.deduct.guide]p3: 677 // Two deduction guide declarations in the same translation unit 678 // for the same class template shall not have equivalent 679 // parameter-declaration-clauses. 680 if (isa<CXXDeductionGuideDecl>(New) && 681 !New->isFunctionTemplateSpecialization() && isVisible(Old)) { 682 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 683 Diag(Old->getLocation(), diag::note_previous_declaration); 684 } 685 686 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 687 // argument expression, that declaration shall be a definition and shall be 688 // the only declaration of the function or function template in the 689 // translation unit. 690 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 691 functionDeclHasDefaultArgument(Old)) { 692 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 693 Diag(Old->getLocation(), diag::note_previous_declaration); 694 Invalid = true; 695 } 696 697 // C++11 [temp.friend]p4 (DR329): 698 // When a function is defined in a friend function declaration in a class 699 // template, the function is instantiated when the function is odr-used. 700 // The same restrictions on multiple declarations and definitions that 701 // apply to non-template function declarations and definitions also apply 702 // to these implicit definitions. 703 const FunctionDecl *OldDefinition = nullptr; 704 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() && 705 Old->isDefined(OldDefinition, true)) 706 CheckForFunctionRedefinition(New, OldDefinition); 707 708 return Invalid; 709 } 710 711 NamedDecl * 712 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 713 MultiTemplateParamsArg TemplateParamLists) { 714 assert(D.isDecompositionDeclarator()); 715 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 716 717 // The syntax only allows a decomposition declarator as a simple-declaration, 718 // a for-range-declaration, or a condition in Clang, but we parse it in more 719 // cases than that. 720 if (!D.mayHaveDecompositionDeclarator()) { 721 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 722 << Decomp.getSourceRange(); 723 return nullptr; 724 } 725 726 if (!TemplateParamLists.empty()) { 727 // FIXME: There's no rule against this, but there are also no rules that 728 // would actually make it usable, so we reject it for now. 729 Diag(TemplateParamLists.front()->getTemplateLoc(), 730 diag::err_decomp_decl_template); 731 return nullptr; 732 } 733 734 Diag(Decomp.getLSquareLoc(), 735 !getLangOpts().CPlusPlus17 736 ? diag::ext_decomp_decl 737 : D.getContext() == DeclaratorContext::Condition 738 ? diag::ext_decomp_decl_cond 739 : diag::warn_cxx14_compat_decomp_decl) 740 << Decomp.getSourceRange(); 741 742 // The semantic context is always just the current context. 743 DeclContext *const DC = CurContext; 744 745 // C++17 [dcl.dcl]/8: 746 // The decl-specifier-seq shall contain only the type-specifier auto 747 // and cv-qualifiers. 748 // C++2a [dcl.dcl]/8: 749 // If decl-specifier-seq contains any decl-specifier other than static, 750 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 751 auto &DS = D.getDeclSpec(); 752 { 753 SmallVector<StringRef, 8> BadSpecifiers; 754 SmallVector<SourceLocation, 8> BadSpecifierLocs; 755 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 756 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 757 if (auto SCS = DS.getStorageClassSpec()) { 758 if (SCS == DeclSpec::SCS_static) { 759 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 760 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 761 } else { 762 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 763 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 764 } 765 } 766 if (auto TSCS = DS.getThreadStorageClassSpec()) { 767 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 768 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 769 } 770 if (DS.hasConstexprSpecifier()) { 771 BadSpecifiers.push_back( 772 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 773 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 774 } 775 if (DS.isInlineSpecified()) { 776 BadSpecifiers.push_back("inline"); 777 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 778 } 779 if (!BadSpecifiers.empty()) { 780 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 781 Err << (int)BadSpecifiers.size() 782 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 783 // Don't add FixItHints to remove the specifiers; we do still respect 784 // them when building the underlying variable. 785 for (auto Loc : BadSpecifierLocs) 786 Err << SourceRange(Loc, Loc); 787 } else if (!CPlusPlus20Specifiers.empty()) { 788 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 789 getLangOpts().CPlusPlus20 790 ? diag::warn_cxx17_compat_decomp_decl_spec 791 : diag::ext_decomp_decl_spec); 792 Warn << (int)CPlusPlus20Specifiers.size() 793 << llvm::join(CPlusPlus20Specifiers.begin(), 794 CPlusPlus20Specifiers.end(), " "); 795 for (auto Loc : CPlusPlus20SpecifierLocs) 796 Warn << SourceRange(Loc, Loc); 797 } 798 // We can't recover from it being declared as a typedef. 799 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 800 return nullptr; 801 } 802 803 // C++2a [dcl.struct.bind]p1: 804 // A cv that includes volatile is deprecated 805 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && 806 getLangOpts().CPlusPlus20) 807 Diag(DS.getVolatileSpecLoc(), 808 diag::warn_deprecated_volatile_structured_binding); 809 810 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 811 QualType R = TInfo->getType(); 812 813 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 814 UPPC_DeclarationType)) 815 D.setInvalidType(); 816 817 // The syntax only allows a single ref-qualifier prior to the decomposition 818 // declarator. No other declarator chunks are permitted. Also check the type 819 // specifier here. 820 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 821 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 822 (D.getNumTypeObjects() == 1 && 823 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 824 Diag(Decomp.getLSquareLoc(), 825 (D.hasGroupingParens() || 826 (D.getNumTypeObjects() && 827 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 828 ? diag::err_decomp_decl_parens 829 : diag::err_decomp_decl_type) 830 << R; 831 832 // In most cases, there's no actual problem with an explicitly-specified 833 // type, but a function type won't work here, and ActOnVariableDeclarator 834 // shouldn't be called for such a type. 835 if (R->isFunctionType()) 836 D.setInvalidType(); 837 } 838 839 // Build the BindingDecls. 840 SmallVector<BindingDecl*, 8> Bindings; 841 842 // Build the BindingDecls. 843 for (auto &B : D.getDecompositionDeclarator().bindings()) { 844 // Check for name conflicts. 845 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 846 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 847 ForVisibleRedeclaration); 848 LookupName(Previous, S, 849 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 850 851 // It's not permitted to shadow a template parameter name. 852 if (Previous.isSingleResult() && 853 Previous.getFoundDecl()->isTemplateParameter()) { 854 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 855 Previous.getFoundDecl()); 856 Previous.clear(); 857 } 858 859 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 860 861 // Find the shadowed declaration before filtering for scope. 862 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 863 ? getShadowedDeclaration(BD, Previous) 864 : nullptr; 865 866 bool ConsiderLinkage = DC->isFunctionOrMethod() && 867 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 868 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 869 /*AllowInlineNamespace*/false); 870 871 if (!Previous.empty()) { 872 auto *Old = Previous.getRepresentativeDecl(); 873 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 874 Diag(Old->getLocation(), diag::note_previous_definition); 875 } else if (ShadowedDecl && !D.isRedeclaration()) { 876 CheckShadow(BD, ShadowedDecl, Previous); 877 } 878 PushOnScopeChains(BD, S, true); 879 Bindings.push_back(BD); 880 ParsingInitForAutoVars.insert(BD); 881 } 882 883 // There are no prior lookup results for the variable itself, because it 884 // is unnamed. 885 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 886 Decomp.getLSquareLoc()); 887 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 888 ForVisibleRedeclaration); 889 890 // Build the variable that holds the non-decomposed object. 891 bool AddToScope = true; 892 NamedDecl *New = 893 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 894 MultiTemplateParamsArg(), AddToScope, Bindings); 895 if (AddToScope) { 896 S->AddDecl(New); 897 CurContext->addHiddenDecl(New); 898 } 899 900 if (isInOpenMPDeclareTargetContext()) 901 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 902 903 return New; 904 } 905 906 static bool checkSimpleDecomposition( 907 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 908 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 909 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 910 if ((int64_t)Bindings.size() != NumElems) { 911 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 912 << DecompType << (unsigned)Bindings.size() 913 << (unsigned)NumElems.getLimitedValue(UINT_MAX) << NumElems.toString(10) 914 << (NumElems < Bindings.size()); 915 return true; 916 } 917 918 unsigned I = 0; 919 for (auto *B : Bindings) { 920 SourceLocation Loc = B->getLocation(); 921 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 922 if (E.isInvalid()) 923 return true; 924 E = GetInit(Loc, E.get(), I++); 925 if (E.isInvalid()) 926 return true; 927 B->setBinding(ElemType, E.get()); 928 } 929 930 return false; 931 } 932 933 static bool checkArrayLikeDecomposition(Sema &S, 934 ArrayRef<BindingDecl *> Bindings, 935 ValueDecl *Src, QualType DecompType, 936 const llvm::APSInt &NumElems, 937 QualType ElemType) { 938 return checkSimpleDecomposition( 939 S, Bindings, Src, DecompType, NumElems, ElemType, 940 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 941 ExprResult E = S.ActOnIntegerConstant(Loc, I); 942 if (E.isInvalid()) 943 return ExprError(); 944 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 945 }); 946 } 947 948 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 949 ValueDecl *Src, QualType DecompType, 950 const ConstantArrayType *CAT) { 951 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 952 llvm::APSInt(CAT->getSize()), 953 CAT->getElementType()); 954 } 955 956 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 957 ValueDecl *Src, QualType DecompType, 958 const VectorType *VT) { 959 return checkArrayLikeDecomposition( 960 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 961 S.Context.getQualifiedType(VT->getElementType(), 962 DecompType.getQualifiers())); 963 } 964 965 static bool checkComplexDecomposition(Sema &S, 966 ArrayRef<BindingDecl *> Bindings, 967 ValueDecl *Src, QualType DecompType, 968 const ComplexType *CT) { 969 return checkSimpleDecomposition( 970 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 971 S.Context.getQualifiedType(CT->getElementType(), 972 DecompType.getQualifiers()), 973 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 974 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 975 }); 976 } 977 978 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 979 TemplateArgumentListInfo &Args) { 980 SmallString<128> SS; 981 llvm::raw_svector_ostream OS(SS); 982 bool First = true; 983 for (auto &Arg : Args.arguments()) { 984 if (!First) 985 OS << ", "; 986 Arg.getArgument().print(PrintingPolicy, OS); 987 First = false; 988 } 989 return std::string(OS.str()); 990 } 991 992 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 993 SourceLocation Loc, StringRef Trait, 994 TemplateArgumentListInfo &Args, 995 unsigned DiagID) { 996 auto DiagnoseMissing = [&] { 997 if (DiagID) 998 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 999 Args); 1000 return true; 1001 }; 1002 1003 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 1004 NamespaceDecl *Std = S.getStdNamespace(); 1005 if (!Std) 1006 return DiagnoseMissing(); 1007 1008 // Look up the trait itself, within namespace std. We can diagnose various 1009 // problems with this lookup even if we've been asked to not diagnose a 1010 // missing specialization, because this can only fail if the user has been 1011 // declaring their own names in namespace std or we don't support the 1012 // standard library implementation in use. 1013 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 1014 Loc, Sema::LookupOrdinaryName); 1015 if (!S.LookupQualifiedName(Result, Std)) 1016 return DiagnoseMissing(); 1017 if (Result.isAmbiguous()) 1018 return true; 1019 1020 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 1021 if (!TraitTD) { 1022 Result.suppressDiagnostics(); 1023 NamedDecl *Found = *Result.begin(); 1024 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 1025 S.Diag(Found->getLocation(), diag::note_declared_at); 1026 return true; 1027 } 1028 1029 // Build the template-id. 1030 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 1031 if (TraitTy.isNull()) 1032 return true; 1033 if (!S.isCompleteType(Loc, TraitTy)) { 1034 if (DiagID) 1035 S.RequireCompleteType( 1036 Loc, TraitTy, DiagID, 1037 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 1038 return true; 1039 } 1040 1041 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1042 assert(RD && "specialization of class template is not a class?"); 1043 1044 // Look up the member of the trait type. 1045 S.LookupQualifiedName(TraitMemberLookup, RD); 1046 return TraitMemberLookup.isAmbiguous(); 1047 } 1048 1049 static TemplateArgumentLoc 1050 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1051 uint64_t I) { 1052 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1053 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1054 } 1055 1056 static TemplateArgumentLoc 1057 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1058 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1059 } 1060 1061 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1062 1063 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1064 llvm::APSInt &Size) { 1065 EnterExpressionEvaluationContext ContextRAII( 1066 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1067 1068 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1069 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1070 1071 // Form template argument list for tuple_size<T>. 1072 TemplateArgumentListInfo Args(Loc, Loc); 1073 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1074 1075 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1076 // it's not tuple-like. 1077 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1078 R.empty()) 1079 return IsTupleLike::NotTupleLike; 1080 1081 // If we get this far, we've committed to the tuple interpretation, but 1082 // we can still fail if there actually isn't a usable ::value. 1083 1084 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1085 LookupResult &R; 1086 TemplateArgumentListInfo &Args; 1087 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1088 : R(R), Args(Args) {} 1089 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 1090 SourceLocation Loc) override { 1091 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1092 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1093 } 1094 } Diagnoser(R, Args); 1095 1096 ExprResult E = 1097 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1098 if (E.isInvalid()) 1099 return IsTupleLike::Error; 1100 1101 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser); 1102 if (E.isInvalid()) 1103 return IsTupleLike::Error; 1104 1105 return IsTupleLike::TupleLike; 1106 } 1107 1108 /// \return std::tuple_element<I, T>::type. 1109 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1110 unsigned I, QualType T) { 1111 // Form template argument list for tuple_element<I, T>. 1112 TemplateArgumentListInfo Args(Loc, Loc); 1113 Args.addArgument( 1114 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1115 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1116 1117 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1118 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1119 if (lookupStdTypeTraitMember( 1120 S, R, Loc, "tuple_element", Args, 1121 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1122 return QualType(); 1123 1124 auto *TD = R.getAsSingle<TypeDecl>(); 1125 if (!TD) { 1126 R.suppressDiagnostics(); 1127 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1128 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1129 if (!R.empty()) 1130 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1131 return QualType(); 1132 } 1133 1134 return S.Context.getTypeDeclType(TD); 1135 } 1136 1137 namespace { 1138 struct InitializingBinding { 1139 Sema &S; 1140 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) { 1141 Sema::CodeSynthesisContext Ctx; 1142 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding; 1143 Ctx.PointOfInstantiation = BD->getLocation(); 1144 Ctx.Entity = BD; 1145 S.pushCodeSynthesisContext(Ctx); 1146 } 1147 ~InitializingBinding() { 1148 S.popCodeSynthesisContext(); 1149 } 1150 }; 1151 } 1152 1153 static bool checkTupleLikeDecomposition(Sema &S, 1154 ArrayRef<BindingDecl *> Bindings, 1155 VarDecl *Src, QualType DecompType, 1156 const llvm::APSInt &TupleSize) { 1157 if ((int64_t)Bindings.size() != TupleSize) { 1158 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1159 << DecompType << (unsigned)Bindings.size() 1160 << (unsigned)TupleSize.getLimitedValue(UINT_MAX) 1161 << TupleSize.toString(10) << (TupleSize < Bindings.size()); 1162 return true; 1163 } 1164 1165 if (Bindings.empty()) 1166 return false; 1167 1168 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1169 1170 // [dcl.decomp]p3: 1171 // The unqualified-id get is looked up in the scope of E by class member 1172 // access lookup ... 1173 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1174 bool UseMemberGet = false; 1175 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1176 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1177 S.LookupQualifiedName(MemberGet, RD); 1178 if (MemberGet.isAmbiguous()) 1179 return true; 1180 // ... and if that finds at least one declaration that is a function 1181 // template whose first template parameter is a non-type parameter ... 1182 for (NamedDecl *D : MemberGet) { 1183 if (FunctionTemplateDecl *FTD = 1184 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1185 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1186 if (TPL->size() != 0 && 1187 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1188 // ... the initializer is e.get<i>(). 1189 UseMemberGet = true; 1190 break; 1191 } 1192 } 1193 } 1194 } 1195 1196 unsigned I = 0; 1197 for (auto *B : Bindings) { 1198 InitializingBinding InitContext(S, B); 1199 SourceLocation Loc = B->getLocation(); 1200 1201 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1202 if (E.isInvalid()) 1203 return true; 1204 1205 // e is an lvalue if the type of the entity is an lvalue reference and 1206 // an xvalue otherwise 1207 if (!Src->getType()->isLValueReferenceType()) 1208 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1209 E.get(), nullptr, VK_XValue, 1210 FPOptionsOverride()); 1211 1212 TemplateArgumentListInfo Args(Loc, Loc); 1213 Args.addArgument( 1214 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1215 1216 if (UseMemberGet) { 1217 // if [lookup of member get] finds at least one declaration, the 1218 // initializer is e.get<i-1>(). 1219 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1220 CXXScopeSpec(), SourceLocation(), nullptr, 1221 MemberGet, &Args, nullptr); 1222 if (E.isInvalid()) 1223 return true; 1224 1225 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1226 } else { 1227 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1228 // in the associated namespaces. 1229 Expr *Get = UnresolvedLookupExpr::Create( 1230 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1231 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1232 UnresolvedSetIterator(), UnresolvedSetIterator()); 1233 1234 Expr *Arg = E.get(); 1235 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1236 } 1237 if (E.isInvalid()) 1238 return true; 1239 Expr *Init = E.get(); 1240 1241 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1242 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1243 if (T.isNull()) 1244 return true; 1245 1246 // each vi is a variable of type "reference to T" initialized with the 1247 // initializer, where the reference is an lvalue reference if the 1248 // initializer is an lvalue and an rvalue reference otherwise 1249 QualType RefType = 1250 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1251 if (RefType.isNull()) 1252 return true; 1253 auto *RefVD = VarDecl::Create( 1254 S.Context, Src->getDeclContext(), Loc, Loc, 1255 B->getDeclName().getAsIdentifierInfo(), RefType, 1256 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1257 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1258 RefVD->setTSCSpec(Src->getTSCSpec()); 1259 RefVD->setImplicit(); 1260 if (Src->isInlineSpecified()) 1261 RefVD->setInlineSpecified(); 1262 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1263 1264 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1265 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1266 InitializationSequence Seq(S, Entity, Kind, Init); 1267 E = Seq.Perform(S, Entity, Kind, Init); 1268 if (E.isInvalid()) 1269 return true; 1270 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1271 if (E.isInvalid()) 1272 return true; 1273 RefVD->setInit(E.get()); 1274 S.CheckCompleteVariableDeclaration(RefVD); 1275 1276 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1277 DeclarationNameInfo(B->getDeclName(), Loc), 1278 RefVD); 1279 if (E.isInvalid()) 1280 return true; 1281 1282 B->setBinding(T, E.get()); 1283 I++; 1284 } 1285 1286 return false; 1287 } 1288 1289 /// Find the base class to decompose in a built-in decomposition of a class type. 1290 /// This base class search is, unfortunately, not quite like any other that we 1291 /// perform anywhere else in C++. 1292 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1293 const CXXRecordDecl *RD, 1294 CXXCastPath &BasePath) { 1295 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1296 CXXBasePath &Path) { 1297 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1298 }; 1299 1300 const CXXRecordDecl *ClassWithFields = nullptr; 1301 AccessSpecifier AS = AS_public; 1302 if (RD->hasDirectFields()) 1303 // [dcl.decomp]p4: 1304 // Otherwise, all of E's non-static data members shall be public direct 1305 // members of E ... 1306 ClassWithFields = RD; 1307 else { 1308 // ... or of ... 1309 CXXBasePaths Paths; 1310 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1311 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1312 // If no classes have fields, just decompose RD itself. (This will work 1313 // if and only if zero bindings were provided.) 1314 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1315 } 1316 1317 CXXBasePath *BestPath = nullptr; 1318 for (auto &P : Paths) { 1319 if (!BestPath) 1320 BestPath = &P; 1321 else if (!S.Context.hasSameType(P.back().Base->getType(), 1322 BestPath->back().Base->getType())) { 1323 // ... the same ... 1324 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1325 << false << RD << BestPath->back().Base->getType() 1326 << P.back().Base->getType(); 1327 return DeclAccessPair(); 1328 } else if (P.Access < BestPath->Access) { 1329 BestPath = &P; 1330 } 1331 } 1332 1333 // ... unambiguous ... 1334 QualType BaseType = BestPath->back().Base->getType(); 1335 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1336 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1337 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1338 return DeclAccessPair(); 1339 } 1340 1341 // ... [accessible, implied by other rules] base class of E. 1342 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1343 *BestPath, diag::err_decomp_decl_inaccessible_base); 1344 AS = BestPath->Access; 1345 1346 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1347 S.BuildBasePathArray(Paths, BasePath); 1348 } 1349 1350 // The above search did not check whether the selected class itself has base 1351 // classes with fields, so check that now. 1352 CXXBasePaths Paths; 1353 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1354 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1355 << (ClassWithFields == RD) << RD << ClassWithFields 1356 << Paths.front().back().Base->getType(); 1357 return DeclAccessPair(); 1358 } 1359 1360 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1361 } 1362 1363 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1364 ValueDecl *Src, QualType DecompType, 1365 const CXXRecordDecl *OrigRD) { 1366 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1367 diag::err_incomplete_type)) 1368 return true; 1369 1370 CXXCastPath BasePath; 1371 DeclAccessPair BasePair = 1372 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1373 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1374 if (!RD) 1375 return true; 1376 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1377 DecompType.getQualifiers()); 1378 1379 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1380 unsigned NumFields = 1381 std::count_if(RD->field_begin(), RD->field_end(), 1382 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1383 assert(Bindings.size() != NumFields); 1384 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1385 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields 1386 << (NumFields < Bindings.size()); 1387 return true; 1388 }; 1389 1390 // all of E's non-static data members shall be [...] well-formed 1391 // when named as e.name in the context of the structured binding, 1392 // E shall not have an anonymous union member, ... 1393 unsigned I = 0; 1394 for (auto *FD : RD->fields()) { 1395 if (FD->isUnnamedBitfield()) 1396 continue; 1397 1398 // All the non-static data members are required to be nameable, so they 1399 // must all have names. 1400 if (!FD->getDeclName()) { 1401 if (RD->isLambda()) { 1402 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda); 1403 S.Diag(RD->getLocation(), diag::note_lambda_decl); 1404 return true; 1405 } 1406 1407 if (FD->isAnonymousStructOrUnion()) { 1408 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1409 << DecompType << FD->getType()->isUnionType(); 1410 S.Diag(FD->getLocation(), diag::note_declared_at); 1411 return true; 1412 } 1413 1414 // FIXME: Are there any other ways we could have an anonymous member? 1415 } 1416 1417 // We have a real field to bind. 1418 if (I >= Bindings.size()) 1419 return DiagnoseBadNumberOfBindings(); 1420 auto *B = Bindings[I++]; 1421 SourceLocation Loc = B->getLocation(); 1422 1423 // The field must be accessible in the context of the structured binding. 1424 // We already checked that the base class is accessible. 1425 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1426 // const_cast here. 1427 S.CheckStructuredBindingMemberAccess( 1428 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1429 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1430 BasePair.getAccess(), FD->getAccess()))); 1431 1432 // Initialize the binding to Src.FD. 1433 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1434 if (E.isInvalid()) 1435 return true; 1436 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1437 VK_LValue, &BasePath); 1438 if (E.isInvalid()) 1439 return true; 1440 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1441 CXXScopeSpec(), FD, 1442 DeclAccessPair::make(FD, FD->getAccess()), 1443 DeclarationNameInfo(FD->getDeclName(), Loc)); 1444 if (E.isInvalid()) 1445 return true; 1446 1447 // If the type of the member is T, the referenced type is cv T, where cv is 1448 // the cv-qualification of the decomposition expression. 1449 // 1450 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1451 // 'const' to the type of the field. 1452 Qualifiers Q = DecompType.getQualifiers(); 1453 if (FD->isMutable()) 1454 Q.removeConst(); 1455 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1456 } 1457 1458 if (I != Bindings.size()) 1459 return DiagnoseBadNumberOfBindings(); 1460 1461 return false; 1462 } 1463 1464 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1465 QualType DecompType = DD->getType(); 1466 1467 // If the type of the decomposition is dependent, then so is the type of 1468 // each binding. 1469 if (DecompType->isDependentType()) { 1470 for (auto *B : DD->bindings()) 1471 B->setType(Context.DependentTy); 1472 return; 1473 } 1474 1475 DecompType = DecompType.getNonReferenceType(); 1476 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1477 1478 // C++1z [dcl.decomp]/2: 1479 // If E is an array type [...] 1480 // As an extension, we also support decomposition of built-in complex and 1481 // vector types. 1482 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1483 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1484 DD->setInvalidDecl(); 1485 return; 1486 } 1487 if (auto *VT = DecompType->getAs<VectorType>()) { 1488 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1489 DD->setInvalidDecl(); 1490 return; 1491 } 1492 if (auto *CT = DecompType->getAs<ComplexType>()) { 1493 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1494 DD->setInvalidDecl(); 1495 return; 1496 } 1497 1498 // C++1z [dcl.decomp]/3: 1499 // if the expression std::tuple_size<E>::value is a well-formed integral 1500 // constant expression, [...] 1501 llvm::APSInt TupleSize(32); 1502 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1503 case IsTupleLike::Error: 1504 DD->setInvalidDecl(); 1505 return; 1506 1507 case IsTupleLike::TupleLike: 1508 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1509 DD->setInvalidDecl(); 1510 return; 1511 1512 case IsTupleLike::NotTupleLike: 1513 break; 1514 } 1515 1516 // C++1z [dcl.dcl]/8: 1517 // [E shall be of array or non-union class type] 1518 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1519 if (!RD || RD->isUnion()) { 1520 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1521 << DD << !RD << DecompType; 1522 DD->setInvalidDecl(); 1523 return; 1524 } 1525 1526 // C++1z [dcl.decomp]/4: 1527 // all of E's non-static data members shall be [...] direct members of 1528 // E or of the same unambiguous public base class of E, ... 1529 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1530 DD->setInvalidDecl(); 1531 } 1532 1533 /// Merge the exception specifications of two variable declarations. 1534 /// 1535 /// This is called when there's a redeclaration of a VarDecl. The function 1536 /// checks if the redeclaration might have an exception specification and 1537 /// validates compatibility and merges the specs if necessary. 1538 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1539 // Shortcut if exceptions are disabled. 1540 if (!getLangOpts().CXXExceptions) 1541 return; 1542 1543 assert(Context.hasSameType(New->getType(), Old->getType()) && 1544 "Should only be called if types are otherwise the same."); 1545 1546 QualType NewType = New->getType(); 1547 QualType OldType = Old->getType(); 1548 1549 // We're only interested in pointers and references to functions, as well 1550 // as pointers to member functions. 1551 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1552 NewType = R->getPointeeType(); 1553 OldType = OldType->castAs<ReferenceType>()->getPointeeType(); 1554 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1555 NewType = P->getPointeeType(); 1556 OldType = OldType->castAs<PointerType>()->getPointeeType(); 1557 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1558 NewType = M->getPointeeType(); 1559 OldType = OldType->castAs<MemberPointerType>()->getPointeeType(); 1560 } 1561 1562 if (!NewType->isFunctionProtoType()) 1563 return; 1564 1565 // There's lots of special cases for functions. For function pointers, system 1566 // libraries are hopefully not as broken so that we don't need these 1567 // workarounds. 1568 if (CheckEquivalentExceptionSpec( 1569 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1570 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1571 New->setInvalidDecl(); 1572 } 1573 } 1574 1575 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1576 /// function declaration are well-formed according to C++ 1577 /// [dcl.fct.default]. 1578 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1579 unsigned NumParams = FD->getNumParams(); 1580 unsigned ParamIdx = 0; 1581 1582 // This checking doesn't make sense for explicit specializations; their 1583 // default arguments are determined by the declaration we're specializing, 1584 // not by FD. 1585 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1586 return; 1587 if (auto *FTD = FD->getDescribedFunctionTemplate()) 1588 if (FTD->isMemberSpecialization()) 1589 return; 1590 1591 // Find first parameter with a default argument 1592 for (; ParamIdx < NumParams; ++ParamIdx) { 1593 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1594 if (Param->hasDefaultArg()) 1595 break; 1596 } 1597 1598 // C++20 [dcl.fct.default]p4: 1599 // In a given function declaration, each parameter subsequent to a parameter 1600 // with a default argument shall have a default argument supplied in this or 1601 // a previous declaration, unless the parameter was expanded from a 1602 // parameter pack, or shall be a function parameter pack. 1603 for (; ParamIdx < NumParams; ++ParamIdx) { 1604 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1605 if (!Param->hasDefaultArg() && !Param->isParameterPack() && 1606 !(CurrentInstantiationScope && 1607 CurrentInstantiationScope->isLocalPackExpansion(Param))) { 1608 if (Param->isInvalidDecl()) 1609 /* We already complained about this parameter. */; 1610 else if (Param->getIdentifier()) 1611 Diag(Param->getLocation(), 1612 diag::err_param_default_argument_missing_name) 1613 << Param->getIdentifier(); 1614 else 1615 Diag(Param->getLocation(), 1616 diag::err_param_default_argument_missing); 1617 } 1618 } 1619 } 1620 1621 /// Check that the given type is a literal type. Issue a diagnostic if not, 1622 /// if Kind is Diagnose. 1623 /// \return \c true if a problem has been found (and optionally diagnosed). 1624 template <typename... Ts> 1625 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1626 SourceLocation Loc, QualType T, unsigned DiagID, 1627 Ts &&...DiagArgs) { 1628 if (T->isDependentType()) 1629 return false; 1630 1631 switch (Kind) { 1632 case Sema::CheckConstexprKind::Diagnose: 1633 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1634 std::forward<Ts>(DiagArgs)...); 1635 1636 case Sema::CheckConstexprKind::CheckValid: 1637 return !T->isLiteralType(SemaRef.Context); 1638 } 1639 1640 llvm_unreachable("unknown CheckConstexprKind"); 1641 } 1642 1643 /// Determine whether a destructor cannot be constexpr due to 1644 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, 1645 const CXXDestructorDecl *DD, 1646 Sema::CheckConstexprKind Kind) { 1647 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { 1648 const CXXRecordDecl *RD = 1649 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1650 if (!RD || RD->hasConstexprDestructor()) 1651 return true; 1652 1653 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1654 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) 1655 << static_cast<int>(DD->getConstexprKind()) << !FD 1656 << (FD ? FD->getDeclName() : DeclarationName()) << T; 1657 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) 1658 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; 1659 } 1660 return false; 1661 }; 1662 1663 const CXXRecordDecl *RD = DD->getParent(); 1664 for (const CXXBaseSpecifier &B : RD->bases()) 1665 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) 1666 return false; 1667 for (const FieldDecl *FD : RD->fields()) 1668 if (!Check(FD->getLocation(), FD->getType(), FD)) 1669 return false; 1670 return true; 1671 } 1672 1673 /// Check whether a function's parameter types are all literal types. If so, 1674 /// return true. If not, produce a suitable diagnostic and return false. 1675 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1676 const FunctionDecl *FD, 1677 Sema::CheckConstexprKind Kind) { 1678 unsigned ArgIndex = 0; 1679 const auto *FT = FD->getType()->castAs<FunctionProtoType>(); 1680 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1681 e = FT->param_type_end(); 1682 i != e; ++i, ++ArgIndex) { 1683 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1684 SourceLocation ParamLoc = PD->getLocation(); 1685 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1686 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1687 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1688 FD->isConsteval())) 1689 return false; 1690 } 1691 return true; 1692 } 1693 1694 /// Check whether a function's return type is a literal type. If so, return 1695 /// true. If not, produce a suitable diagnostic and return false. 1696 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, 1697 Sema::CheckConstexprKind Kind) { 1698 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), 1699 diag::err_constexpr_non_literal_return, 1700 FD->isConsteval())) 1701 return false; 1702 return true; 1703 } 1704 1705 /// Get diagnostic %select index for tag kind for 1706 /// record diagnostic message. 1707 /// WARNING: Indexes apply to particular diagnostics only! 1708 /// 1709 /// \returns diagnostic %select index. 1710 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1711 switch (Tag) { 1712 case TTK_Struct: return 0; 1713 case TTK_Interface: return 1; 1714 case TTK_Class: return 2; 1715 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1716 } 1717 } 1718 1719 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1720 Stmt *Body, 1721 Sema::CheckConstexprKind Kind); 1722 1723 // Check whether a function declaration satisfies the requirements of a 1724 // constexpr function definition or a constexpr constructor definition. If so, 1725 // return true. If not, produce appropriate diagnostics (unless asked not to by 1726 // Kind) and return false. 1727 // 1728 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1729 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1730 CheckConstexprKind Kind) { 1731 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1732 if (MD && MD->isInstance()) { 1733 // C++11 [dcl.constexpr]p4: 1734 // The definition of a constexpr constructor shall satisfy the following 1735 // constraints: 1736 // - the class shall not have any virtual base classes; 1737 // 1738 // FIXME: This only applies to constructors and destructors, not arbitrary 1739 // member functions. 1740 const CXXRecordDecl *RD = MD->getParent(); 1741 if (RD->getNumVBases()) { 1742 if (Kind == CheckConstexprKind::CheckValid) 1743 return false; 1744 1745 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1746 << isa<CXXConstructorDecl>(NewFD) 1747 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1748 for (const auto &I : RD->vbases()) 1749 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1750 << I.getSourceRange(); 1751 return false; 1752 } 1753 } 1754 1755 if (!isa<CXXConstructorDecl>(NewFD)) { 1756 // C++11 [dcl.constexpr]p3: 1757 // The definition of a constexpr function shall satisfy the following 1758 // constraints: 1759 // - it shall not be virtual; (removed in C++20) 1760 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1761 if (Method && Method->isVirtual()) { 1762 if (getLangOpts().CPlusPlus20) { 1763 if (Kind == CheckConstexprKind::Diagnose) 1764 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1765 } else { 1766 if (Kind == CheckConstexprKind::CheckValid) 1767 return false; 1768 1769 Method = Method->getCanonicalDecl(); 1770 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1771 1772 // If it's not obvious why this function is virtual, find an overridden 1773 // function which uses the 'virtual' keyword. 1774 const CXXMethodDecl *WrittenVirtual = Method; 1775 while (!WrittenVirtual->isVirtualAsWritten()) 1776 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1777 if (WrittenVirtual != Method) 1778 Diag(WrittenVirtual->getLocation(), 1779 diag::note_overridden_virtual_function); 1780 return false; 1781 } 1782 } 1783 1784 // - its return type shall be a literal type; 1785 if (!CheckConstexprReturnType(*this, NewFD, Kind)) 1786 return false; 1787 } 1788 1789 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { 1790 // A destructor can be constexpr only if the defaulted destructor could be; 1791 // we don't need to check the members and bases if we already know they all 1792 // have constexpr destructors. 1793 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { 1794 if (Kind == CheckConstexprKind::CheckValid) 1795 return false; 1796 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) 1797 return false; 1798 } 1799 } 1800 1801 // - each of its parameter types shall be a literal type; 1802 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1803 return false; 1804 1805 Stmt *Body = NewFD->getBody(); 1806 assert(Body && 1807 "CheckConstexprFunctionDefinition called on function with no body"); 1808 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1809 } 1810 1811 /// Check the given declaration statement is legal within a constexpr function 1812 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1813 /// 1814 /// \return true if the body is OK (maybe only as an extension), false if we 1815 /// have diagnosed a problem. 1816 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1817 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1818 Sema::CheckConstexprKind Kind) { 1819 // C++11 [dcl.constexpr]p3 and p4: 1820 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1821 // contain only 1822 for (const auto *DclIt : DS->decls()) { 1823 switch (DclIt->getKind()) { 1824 case Decl::StaticAssert: 1825 case Decl::Using: 1826 case Decl::UsingShadow: 1827 case Decl::UsingDirective: 1828 case Decl::UnresolvedUsingTypename: 1829 case Decl::UnresolvedUsingValue: 1830 // - static_assert-declarations 1831 // - using-declarations, 1832 // - using-directives, 1833 continue; 1834 1835 case Decl::Typedef: 1836 case Decl::TypeAlias: { 1837 // - typedef declarations and alias-declarations that do not define 1838 // classes or enumerations, 1839 const auto *TN = cast<TypedefNameDecl>(DclIt); 1840 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1841 // Don't allow variably-modified types in constexpr functions. 1842 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1843 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1844 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1845 << TL.getSourceRange() << TL.getType() 1846 << isa<CXXConstructorDecl>(Dcl); 1847 } 1848 return false; 1849 } 1850 continue; 1851 } 1852 1853 case Decl::Enum: 1854 case Decl::CXXRecord: 1855 // C++1y allows types to be defined, not just declared. 1856 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1857 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1858 SemaRef.Diag(DS->getBeginLoc(), 1859 SemaRef.getLangOpts().CPlusPlus14 1860 ? diag::warn_cxx11_compat_constexpr_type_definition 1861 : diag::ext_constexpr_type_definition) 1862 << isa<CXXConstructorDecl>(Dcl); 1863 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1864 return false; 1865 } 1866 } 1867 continue; 1868 1869 case Decl::EnumConstant: 1870 case Decl::IndirectField: 1871 case Decl::ParmVar: 1872 // These can only appear with other declarations which are banned in 1873 // C++11 and permitted in C++1y, so ignore them. 1874 continue; 1875 1876 case Decl::Var: 1877 case Decl::Decomposition: { 1878 // C++1y [dcl.constexpr]p3 allows anything except: 1879 // a definition of a variable of non-literal type or of static or 1880 // thread storage duration or [before C++2a] for which no 1881 // initialization is performed. 1882 const auto *VD = cast<VarDecl>(DclIt); 1883 if (VD->isThisDeclarationADefinition()) { 1884 if (VD->isStaticLocal()) { 1885 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1886 SemaRef.Diag(VD->getLocation(), 1887 diag::err_constexpr_local_var_static) 1888 << isa<CXXConstructorDecl>(Dcl) 1889 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1890 } 1891 return false; 1892 } 1893 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1894 diag::err_constexpr_local_var_non_literal_type, 1895 isa<CXXConstructorDecl>(Dcl))) 1896 return false; 1897 if (!VD->getType()->isDependentType() && 1898 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1899 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1900 SemaRef.Diag( 1901 VD->getLocation(), 1902 SemaRef.getLangOpts().CPlusPlus20 1903 ? diag::warn_cxx17_compat_constexpr_local_var_no_init 1904 : diag::ext_constexpr_local_var_no_init) 1905 << isa<CXXConstructorDecl>(Dcl); 1906 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1907 return false; 1908 } 1909 continue; 1910 } 1911 } 1912 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1913 SemaRef.Diag(VD->getLocation(), 1914 SemaRef.getLangOpts().CPlusPlus14 1915 ? diag::warn_cxx11_compat_constexpr_local_var 1916 : diag::ext_constexpr_local_var) 1917 << isa<CXXConstructorDecl>(Dcl); 1918 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1919 return false; 1920 } 1921 continue; 1922 } 1923 1924 case Decl::NamespaceAlias: 1925 case Decl::Function: 1926 // These are disallowed in C++11 and permitted in C++1y. Allow them 1927 // everywhere as an extension. 1928 if (!Cxx1yLoc.isValid()) 1929 Cxx1yLoc = DS->getBeginLoc(); 1930 continue; 1931 1932 default: 1933 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1934 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1935 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1936 } 1937 return false; 1938 } 1939 } 1940 1941 return true; 1942 } 1943 1944 /// Check that the given field is initialized within a constexpr constructor. 1945 /// 1946 /// \param Dcl The constexpr constructor being checked. 1947 /// \param Field The field being checked. This may be a member of an anonymous 1948 /// struct or union nested within the class being checked. 1949 /// \param Inits All declarations, including anonymous struct/union members and 1950 /// indirect members, for which any initialization was provided. 1951 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1952 /// multiple notes for different members to the same error. 1953 /// \param Kind Whether we're diagnosing a constructor as written or determining 1954 /// whether the formal requirements are satisfied. 1955 /// \return \c false if we're checking for validity and the constructor does 1956 /// not satisfy the requirements on a constexpr constructor. 1957 static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1958 const FunctionDecl *Dcl, 1959 FieldDecl *Field, 1960 llvm::SmallSet<Decl*, 16> &Inits, 1961 bool &Diagnosed, 1962 Sema::CheckConstexprKind Kind) { 1963 // In C++20 onwards, there's nothing to check for validity. 1964 if (Kind == Sema::CheckConstexprKind::CheckValid && 1965 SemaRef.getLangOpts().CPlusPlus20) 1966 return true; 1967 1968 if (Field->isInvalidDecl()) 1969 return true; 1970 1971 if (Field->isUnnamedBitfield()) 1972 return true; 1973 1974 // Anonymous unions with no variant members and empty anonymous structs do not 1975 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1976 // indirect fields don't need initializing. 1977 if (Field->isAnonymousStructOrUnion() && 1978 (Field->getType()->isUnionType() 1979 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1980 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1981 return true; 1982 1983 if (!Inits.count(Field)) { 1984 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1985 if (!Diagnosed) { 1986 SemaRef.Diag(Dcl->getLocation(), 1987 SemaRef.getLangOpts().CPlusPlus20 1988 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init 1989 : diag::ext_constexpr_ctor_missing_init); 1990 Diagnosed = true; 1991 } 1992 SemaRef.Diag(Field->getLocation(), 1993 diag::note_constexpr_ctor_missing_init); 1994 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1995 return false; 1996 } 1997 } else if (Field->isAnonymousStructOrUnion()) { 1998 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1999 for (auto *I : RD->fields()) 2000 // If an anonymous union contains an anonymous struct of which any member 2001 // is initialized, all members must be initialized. 2002 if (!RD->isUnion() || Inits.count(I)) 2003 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2004 Kind)) 2005 return false; 2006 } 2007 return true; 2008 } 2009 2010 /// Check the provided statement is allowed in a constexpr function 2011 /// definition. 2012 static bool 2013 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 2014 SmallVectorImpl<SourceLocation> &ReturnStmts, 2015 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 2016 Sema::CheckConstexprKind Kind) { 2017 // - its function-body shall be [...] a compound-statement that contains only 2018 switch (S->getStmtClass()) { 2019 case Stmt::NullStmtClass: 2020 // - null statements, 2021 return true; 2022 2023 case Stmt::DeclStmtClass: 2024 // - static_assert-declarations 2025 // - using-declarations, 2026 // - using-directives, 2027 // - typedef declarations and alias-declarations that do not define 2028 // classes or enumerations, 2029 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 2030 return false; 2031 return true; 2032 2033 case Stmt::ReturnStmtClass: 2034 // - and exactly one return statement; 2035 if (isa<CXXConstructorDecl>(Dcl)) { 2036 // C++1y allows return statements in constexpr constructors. 2037 if (!Cxx1yLoc.isValid()) 2038 Cxx1yLoc = S->getBeginLoc(); 2039 return true; 2040 } 2041 2042 ReturnStmts.push_back(S->getBeginLoc()); 2043 return true; 2044 2045 case Stmt::CompoundStmtClass: { 2046 // C++1y allows compound-statements. 2047 if (!Cxx1yLoc.isValid()) 2048 Cxx1yLoc = S->getBeginLoc(); 2049 2050 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2051 for (auto *BodyIt : CompStmt->body()) { 2052 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2053 Cxx1yLoc, Cxx2aLoc, Kind)) 2054 return false; 2055 } 2056 return true; 2057 } 2058 2059 case Stmt::AttributedStmtClass: 2060 if (!Cxx1yLoc.isValid()) 2061 Cxx1yLoc = S->getBeginLoc(); 2062 return true; 2063 2064 case Stmt::IfStmtClass: { 2065 // C++1y allows if-statements. 2066 if (!Cxx1yLoc.isValid()) 2067 Cxx1yLoc = S->getBeginLoc(); 2068 2069 IfStmt *If = cast<IfStmt>(S); 2070 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2071 Cxx1yLoc, Cxx2aLoc, Kind)) 2072 return false; 2073 if (If->getElse() && 2074 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2075 Cxx1yLoc, Cxx2aLoc, Kind)) 2076 return false; 2077 return true; 2078 } 2079 2080 case Stmt::WhileStmtClass: 2081 case Stmt::DoStmtClass: 2082 case Stmt::ForStmtClass: 2083 case Stmt::CXXForRangeStmtClass: 2084 case Stmt::ContinueStmtClass: 2085 // C++1y allows all of these. We don't allow them as extensions in C++11, 2086 // because they don't make sense without variable mutation. 2087 if (!SemaRef.getLangOpts().CPlusPlus14) 2088 break; 2089 if (!Cxx1yLoc.isValid()) 2090 Cxx1yLoc = S->getBeginLoc(); 2091 for (Stmt *SubStmt : S->children()) 2092 if (SubStmt && 2093 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2094 Cxx1yLoc, Cxx2aLoc, Kind)) 2095 return false; 2096 return true; 2097 2098 case Stmt::SwitchStmtClass: 2099 case Stmt::CaseStmtClass: 2100 case Stmt::DefaultStmtClass: 2101 case Stmt::BreakStmtClass: 2102 // C++1y allows switch-statements, and since they don't need variable 2103 // mutation, we can reasonably allow them in C++11 as an extension. 2104 if (!Cxx1yLoc.isValid()) 2105 Cxx1yLoc = S->getBeginLoc(); 2106 for (Stmt *SubStmt : S->children()) 2107 if (SubStmt && 2108 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2109 Cxx1yLoc, Cxx2aLoc, Kind)) 2110 return false; 2111 return true; 2112 2113 case Stmt::GCCAsmStmtClass: 2114 case Stmt::MSAsmStmtClass: 2115 // C++2a allows inline assembly statements. 2116 case Stmt::CXXTryStmtClass: 2117 if (Cxx2aLoc.isInvalid()) 2118 Cxx2aLoc = S->getBeginLoc(); 2119 for (Stmt *SubStmt : S->children()) { 2120 if (SubStmt && 2121 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2122 Cxx1yLoc, Cxx2aLoc, Kind)) 2123 return false; 2124 } 2125 return true; 2126 2127 case Stmt::CXXCatchStmtClass: 2128 // Do not bother checking the language mode (already covered by the 2129 // try block check). 2130 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2131 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2132 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2133 return false; 2134 return true; 2135 2136 default: 2137 if (!isa<Expr>(S)) 2138 break; 2139 2140 // C++1y allows expression-statements. 2141 if (!Cxx1yLoc.isValid()) 2142 Cxx1yLoc = S->getBeginLoc(); 2143 return true; 2144 } 2145 2146 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2147 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2148 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2149 } 2150 return false; 2151 } 2152 2153 /// Check the body for the given constexpr function declaration only contains 2154 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2155 /// 2156 /// \return true if the body is OK, false if we have found or diagnosed a 2157 /// problem. 2158 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2159 Stmt *Body, 2160 Sema::CheckConstexprKind Kind) { 2161 SmallVector<SourceLocation, 4> ReturnStmts; 2162 2163 if (isa<CXXTryStmt>(Body)) { 2164 // C++11 [dcl.constexpr]p3: 2165 // The definition of a constexpr function shall satisfy the following 2166 // constraints: [...] 2167 // - its function-body shall be = delete, = default, or a 2168 // compound-statement 2169 // 2170 // C++11 [dcl.constexpr]p4: 2171 // In the definition of a constexpr constructor, [...] 2172 // - its function-body shall not be a function-try-block; 2173 // 2174 // This restriction is lifted in C++2a, as long as inner statements also 2175 // apply the general constexpr rules. 2176 switch (Kind) { 2177 case Sema::CheckConstexprKind::CheckValid: 2178 if (!SemaRef.getLangOpts().CPlusPlus20) 2179 return false; 2180 break; 2181 2182 case Sema::CheckConstexprKind::Diagnose: 2183 SemaRef.Diag(Body->getBeginLoc(), 2184 !SemaRef.getLangOpts().CPlusPlus20 2185 ? diag::ext_constexpr_function_try_block_cxx20 2186 : diag::warn_cxx17_compat_constexpr_function_try_block) 2187 << isa<CXXConstructorDecl>(Dcl); 2188 break; 2189 } 2190 } 2191 2192 // - its function-body shall be [...] a compound-statement that contains only 2193 // [... list of cases ...] 2194 // 2195 // Note that walking the children here is enough to properly check for 2196 // CompoundStmt and CXXTryStmt body. 2197 SourceLocation Cxx1yLoc, Cxx2aLoc; 2198 for (Stmt *SubStmt : Body->children()) { 2199 if (SubStmt && 2200 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2201 Cxx1yLoc, Cxx2aLoc, Kind)) 2202 return false; 2203 } 2204 2205 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2206 // If this is only valid as an extension, report that we don't satisfy the 2207 // constraints of the current language. 2208 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) || 2209 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2210 return false; 2211 } else if (Cxx2aLoc.isValid()) { 2212 SemaRef.Diag(Cxx2aLoc, 2213 SemaRef.getLangOpts().CPlusPlus20 2214 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2215 : diag::ext_constexpr_body_invalid_stmt_cxx20) 2216 << isa<CXXConstructorDecl>(Dcl); 2217 } else if (Cxx1yLoc.isValid()) { 2218 SemaRef.Diag(Cxx1yLoc, 2219 SemaRef.getLangOpts().CPlusPlus14 2220 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2221 : diag::ext_constexpr_body_invalid_stmt) 2222 << isa<CXXConstructorDecl>(Dcl); 2223 } 2224 2225 if (const CXXConstructorDecl *Constructor 2226 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2227 const CXXRecordDecl *RD = Constructor->getParent(); 2228 // DR1359: 2229 // - every non-variant non-static data member and base class sub-object 2230 // shall be initialized; 2231 // DR1460: 2232 // - if the class is a union having variant members, exactly one of them 2233 // shall be initialized; 2234 if (RD->isUnion()) { 2235 if (Constructor->getNumCtorInitializers() == 0 && 2236 RD->hasVariantMembers()) { 2237 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2238 SemaRef.Diag( 2239 Dcl->getLocation(), 2240 SemaRef.getLangOpts().CPlusPlus20 2241 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2242 : diag::ext_constexpr_union_ctor_no_init); 2243 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2244 return false; 2245 } 2246 } 2247 } else if (!Constructor->isDependentContext() && 2248 !Constructor->isDelegatingConstructor()) { 2249 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2250 2251 // Skip detailed checking if we have enough initializers, and we would 2252 // allow at most one initializer per member. 2253 bool AnyAnonStructUnionMembers = false; 2254 unsigned Fields = 0; 2255 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2256 E = RD->field_end(); I != E; ++I, ++Fields) { 2257 if (I->isAnonymousStructOrUnion()) { 2258 AnyAnonStructUnionMembers = true; 2259 break; 2260 } 2261 } 2262 // DR1460: 2263 // - if the class is a union-like class, but is not a union, for each of 2264 // its anonymous union members having variant members, exactly one of 2265 // them shall be initialized; 2266 if (AnyAnonStructUnionMembers || 2267 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2268 // Check initialization of non-static data members. Base classes are 2269 // always initialized so do not need to be checked. Dependent bases 2270 // might not have initializers in the member initializer list. 2271 llvm::SmallSet<Decl*, 16> Inits; 2272 for (const auto *I: Constructor->inits()) { 2273 if (FieldDecl *FD = I->getMember()) 2274 Inits.insert(FD); 2275 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2276 Inits.insert(ID->chain_begin(), ID->chain_end()); 2277 } 2278 2279 bool Diagnosed = false; 2280 for (auto *I : RD->fields()) 2281 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2282 Kind)) 2283 return false; 2284 } 2285 } 2286 } else { 2287 if (ReturnStmts.empty()) { 2288 // C++1y doesn't require constexpr functions to contain a 'return' 2289 // statement. We still do, unless the return type might be void, because 2290 // otherwise if there's no return statement, the function cannot 2291 // be used in a core constant expression. 2292 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2293 (Dcl->getReturnType()->isVoidType() || 2294 Dcl->getReturnType()->isDependentType()); 2295 switch (Kind) { 2296 case Sema::CheckConstexprKind::Diagnose: 2297 SemaRef.Diag(Dcl->getLocation(), 2298 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2299 : diag::err_constexpr_body_no_return) 2300 << Dcl->isConsteval(); 2301 if (!OK) 2302 return false; 2303 break; 2304 2305 case Sema::CheckConstexprKind::CheckValid: 2306 // The formal requirements don't include this rule in C++14, even 2307 // though the "must be able to produce a constant expression" rules 2308 // still imply it in some cases. 2309 if (!SemaRef.getLangOpts().CPlusPlus14) 2310 return false; 2311 break; 2312 } 2313 } else if (ReturnStmts.size() > 1) { 2314 switch (Kind) { 2315 case Sema::CheckConstexprKind::Diagnose: 2316 SemaRef.Diag( 2317 ReturnStmts.back(), 2318 SemaRef.getLangOpts().CPlusPlus14 2319 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2320 : diag::ext_constexpr_body_multiple_return); 2321 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2322 SemaRef.Diag(ReturnStmts[I], 2323 diag::note_constexpr_body_previous_return); 2324 break; 2325 2326 case Sema::CheckConstexprKind::CheckValid: 2327 if (!SemaRef.getLangOpts().CPlusPlus14) 2328 return false; 2329 break; 2330 } 2331 } 2332 } 2333 2334 // C++11 [dcl.constexpr]p5: 2335 // if no function argument values exist such that the function invocation 2336 // substitution would produce a constant expression, the program is 2337 // ill-formed; no diagnostic required. 2338 // C++11 [dcl.constexpr]p3: 2339 // - every constructor call and implicit conversion used in initializing the 2340 // return value shall be one of those allowed in a constant expression. 2341 // C++11 [dcl.constexpr]p4: 2342 // - every constructor involved in initializing non-static data members and 2343 // base class sub-objects shall be a constexpr constructor. 2344 // 2345 // Note that this rule is distinct from the "requirements for a constexpr 2346 // function", so is not checked in CheckValid mode. 2347 SmallVector<PartialDiagnosticAt, 8> Diags; 2348 if (Kind == Sema::CheckConstexprKind::Diagnose && 2349 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2350 SemaRef.Diag(Dcl->getLocation(), 2351 diag::ext_constexpr_function_never_constant_expr) 2352 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2353 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2354 SemaRef.Diag(Diags[I].first, Diags[I].second); 2355 // Don't return false here: we allow this for compatibility in 2356 // system headers. 2357 } 2358 2359 return true; 2360 } 2361 2362 /// Get the class that is directly named by the current context. This is the 2363 /// class for which an unqualified-id in this scope could name a constructor 2364 /// or destructor. 2365 /// 2366 /// If the scope specifier denotes a class, this will be that class. 2367 /// If the scope specifier is empty, this will be the class whose 2368 /// member-specification we are currently within. Otherwise, there 2369 /// is no such class. 2370 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2371 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2372 2373 if (SS && SS->isInvalid()) 2374 return nullptr; 2375 2376 if (SS && SS->isNotEmpty()) { 2377 DeclContext *DC = computeDeclContext(*SS, true); 2378 return dyn_cast_or_null<CXXRecordDecl>(DC); 2379 } 2380 2381 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2382 } 2383 2384 /// isCurrentClassName - Determine whether the identifier II is the 2385 /// name of the class type currently being defined. In the case of 2386 /// nested classes, this will only return true if II is the name of 2387 /// the innermost class. 2388 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2389 const CXXScopeSpec *SS) { 2390 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2391 return CurDecl && &II == CurDecl->getIdentifier(); 2392 } 2393 2394 /// Determine whether the identifier II is a typo for the name of 2395 /// the class type currently being defined. If so, update it to the identifier 2396 /// that should have been used. 2397 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2398 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2399 2400 if (!getLangOpts().SpellChecking) 2401 return false; 2402 2403 CXXRecordDecl *CurDecl; 2404 if (SS && SS->isSet() && !SS->isInvalid()) { 2405 DeclContext *DC = computeDeclContext(*SS, true); 2406 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2407 } else 2408 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2409 2410 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2411 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2412 < II->getLength()) { 2413 II = CurDecl->getIdentifier(); 2414 return true; 2415 } 2416 2417 return false; 2418 } 2419 2420 /// Determine whether the given class is a base class of the given 2421 /// class, including looking at dependent bases. 2422 static bool findCircularInheritance(const CXXRecordDecl *Class, 2423 const CXXRecordDecl *Current) { 2424 SmallVector<const CXXRecordDecl*, 8> Queue; 2425 2426 Class = Class->getCanonicalDecl(); 2427 while (true) { 2428 for (const auto &I : Current->bases()) { 2429 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2430 if (!Base) 2431 continue; 2432 2433 Base = Base->getDefinition(); 2434 if (!Base) 2435 continue; 2436 2437 if (Base->getCanonicalDecl() == Class) 2438 return true; 2439 2440 Queue.push_back(Base); 2441 } 2442 2443 if (Queue.empty()) 2444 return false; 2445 2446 Current = Queue.pop_back_val(); 2447 } 2448 2449 return false; 2450 } 2451 2452 /// Check the validity of a C++ base class specifier. 2453 /// 2454 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2455 /// and returns NULL otherwise. 2456 CXXBaseSpecifier * 2457 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2458 SourceRange SpecifierRange, 2459 bool Virtual, AccessSpecifier Access, 2460 TypeSourceInfo *TInfo, 2461 SourceLocation EllipsisLoc) { 2462 QualType BaseType = TInfo->getType(); 2463 if (BaseType->containsErrors()) { 2464 // Already emitted a diagnostic when parsing the error type. 2465 return nullptr; 2466 } 2467 // C++ [class.union]p1: 2468 // A union shall not have base classes. 2469 if (Class->isUnion()) { 2470 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2471 << SpecifierRange; 2472 return nullptr; 2473 } 2474 2475 if (EllipsisLoc.isValid() && 2476 !TInfo->getType()->containsUnexpandedParameterPack()) { 2477 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2478 << TInfo->getTypeLoc().getSourceRange(); 2479 EllipsisLoc = SourceLocation(); 2480 } 2481 2482 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2483 2484 if (BaseType->isDependentType()) { 2485 // Make sure that we don't have circular inheritance among our dependent 2486 // bases. For non-dependent bases, the check for completeness below handles 2487 // this. 2488 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2489 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2490 ((BaseDecl = BaseDecl->getDefinition()) && 2491 findCircularInheritance(Class, BaseDecl))) { 2492 Diag(BaseLoc, diag::err_circular_inheritance) 2493 << BaseType << Context.getTypeDeclType(Class); 2494 2495 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2496 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2497 << BaseType; 2498 2499 return nullptr; 2500 } 2501 } 2502 2503 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2504 Class->getTagKind() == TTK_Class, 2505 Access, TInfo, EllipsisLoc); 2506 } 2507 2508 // Base specifiers must be record types. 2509 if (!BaseType->isRecordType()) { 2510 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2511 return nullptr; 2512 } 2513 2514 // C++ [class.union]p1: 2515 // A union shall not be used as a base class. 2516 if (BaseType->isUnionType()) { 2517 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2518 return nullptr; 2519 } 2520 2521 // For the MS ABI, propagate DLL attributes to base class templates. 2522 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2523 if (Attr *ClassAttr = getDLLAttr(Class)) { 2524 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2525 BaseType->getAsCXXRecordDecl())) { 2526 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2527 BaseLoc); 2528 } 2529 } 2530 } 2531 2532 // C++ [class.derived]p2: 2533 // The class-name in a base-specifier shall not be an incompletely 2534 // defined class. 2535 if (RequireCompleteType(BaseLoc, BaseType, 2536 diag::err_incomplete_base_class, SpecifierRange)) { 2537 Class->setInvalidDecl(); 2538 return nullptr; 2539 } 2540 2541 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2542 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2543 assert(BaseDecl && "Record type has no declaration"); 2544 BaseDecl = BaseDecl->getDefinition(); 2545 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2546 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2547 assert(CXXBaseDecl && "Base type is not a C++ type"); 2548 2549 // Microsoft docs say: 2550 // "If a base-class has a code_seg attribute, derived classes must have the 2551 // same attribute." 2552 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2553 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2554 if ((DerivedCSA || BaseCSA) && 2555 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2556 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2557 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2558 << CXXBaseDecl; 2559 return nullptr; 2560 } 2561 2562 // A class which contains a flexible array member is not suitable for use as a 2563 // base class: 2564 // - If the layout determines that a base comes before another base, 2565 // the flexible array member would index into the subsequent base. 2566 // - If the layout determines that base comes before the derived class, 2567 // the flexible array member would index into the derived class. 2568 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2569 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2570 << CXXBaseDecl->getDeclName(); 2571 return nullptr; 2572 } 2573 2574 // C++ [class]p3: 2575 // If a class is marked final and it appears as a base-type-specifier in 2576 // base-clause, the program is ill-formed. 2577 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2578 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2579 << CXXBaseDecl->getDeclName() 2580 << FA->isSpelledAsSealed(); 2581 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2582 << CXXBaseDecl->getDeclName() << FA->getRange(); 2583 return nullptr; 2584 } 2585 2586 if (BaseDecl->isInvalidDecl()) 2587 Class->setInvalidDecl(); 2588 2589 // Create the base specifier. 2590 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2591 Class->getTagKind() == TTK_Class, 2592 Access, TInfo, EllipsisLoc); 2593 } 2594 2595 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2596 /// one entry in the base class list of a class specifier, for 2597 /// example: 2598 /// class foo : public bar, virtual private baz { 2599 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2600 BaseResult 2601 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2602 ParsedAttributes &Attributes, 2603 bool Virtual, AccessSpecifier Access, 2604 ParsedType basetype, SourceLocation BaseLoc, 2605 SourceLocation EllipsisLoc) { 2606 if (!classdecl) 2607 return true; 2608 2609 AdjustDeclIfTemplate(classdecl); 2610 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2611 if (!Class) 2612 return true; 2613 2614 // We haven't yet attached the base specifiers. 2615 Class->setIsParsingBaseSpecifiers(); 2616 2617 // We do not support any C++11 attributes on base-specifiers yet. 2618 // Diagnose any attributes we see. 2619 for (const ParsedAttr &AL : Attributes) { 2620 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2621 continue; 2622 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2623 ? (unsigned)diag::warn_unknown_attribute_ignored 2624 : (unsigned)diag::err_base_specifier_attribute) 2625 << AL << AL.getRange(); 2626 } 2627 2628 TypeSourceInfo *TInfo = nullptr; 2629 GetTypeFromParser(basetype, &TInfo); 2630 2631 if (EllipsisLoc.isInvalid() && 2632 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2633 UPPC_BaseType)) 2634 return true; 2635 2636 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2637 Virtual, Access, TInfo, 2638 EllipsisLoc)) 2639 return BaseSpec; 2640 else 2641 Class->setInvalidDecl(); 2642 2643 return true; 2644 } 2645 2646 /// Use small set to collect indirect bases. As this is only used 2647 /// locally, there's no need to abstract the small size parameter. 2648 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2649 2650 /// Recursively add the bases of Type. Don't add Type itself. 2651 static void 2652 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2653 const QualType &Type) 2654 { 2655 // Even though the incoming type is a base, it might not be 2656 // a class -- it could be a template parm, for instance. 2657 if (auto Rec = Type->getAs<RecordType>()) { 2658 auto Decl = Rec->getAsCXXRecordDecl(); 2659 2660 // Iterate over its bases. 2661 for (const auto &BaseSpec : Decl->bases()) { 2662 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2663 .getUnqualifiedType(); 2664 if (Set.insert(Base).second) 2665 // If we've not already seen it, recurse. 2666 NoteIndirectBases(Context, Set, Base); 2667 } 2668 } 2669 } 2670 2671 /// Performs the actual work of attaching the given base class 2672 /// specifiers to a C++ class. 2673 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2674 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2675 if (Bases.empty()) 2676 return false; 2677 2678 // Used to keep track of which base types we have already seen, so 2679 // that we can properly diagnose redundant direct base types. Note 2680 // that the key is always the unqualified canonical type of the base 2681 // class. 2682 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2683 2684 // Used to track indirect bases so we can see if a direct base is 2685 // ambiguous. 2686 IndirectBaseSet IndirectBaseTypes; 2687 2688 // Copy non-redundant base specifiers into permanent storage. 2689 unsigned NumGoodBases = 0; 2690 bool Invalid = false; 2691 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2692 QualType NewBaseType 2693 = Context.getCanonicalType(Bases[idx]->getType()); 2694 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2695 2696 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2697 if (KnownBase) { 2698 // C++ [class.mi]p3: 2699 // A class shall not be specified as a direct base class of a 2700 // derived class more than once. 2701 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2702 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2703 2704 // Delete the duplicate base class specifier; we're going to 2705 // overwrite its pointer later. 2706 Context.Deallocate(Bases[idx]); 2707 2708 Invalid = true; 2709 } else { 2710 // Okay, add this new base class. 2711 KnownBase = Bases[idx]; 2712 Bases[NumGoodBases++] = Bases[idx]; 2713 2714 // Note this base's direct & indirect bases, if there could be ambiguity. 2715 if (Bases.size() > 1) 2716 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2717 2718 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2719 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2720 if (Class->isInterface() && 2721 (!RD->isInterfaceLike() || 2722 KnownBase->getAccessSpecifier() != AS_public)) { 2723 // The Microsoft extension __interface does not permit bases that 2724 // are not themselves public interfaces. 2725 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2726 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2727 << RD->getSourceRange(); 2728 Invalid = true; 2729 } 2730 if (RD->hasAttr<WeakAttr>()) 2731 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2732 } 2733 } 2734 } 2735 2736 // Attach the remaining base class specifiers to the derived class. 2737 Class->setBases(Bases.data(), NumGoodBases); 2738 2739 // Check that the only base classes that are duplicate are virtual. 2740 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2741 // Check whether this direct base is inaccessible due to ambiguity. 2742 QualType BaseType = Bases[idx]->getType(); 2743 2744 // Skip all dependent types in templates being used as base specifiers. 2745 // Checks below assume that the base specifier is a CXXRecord. 2746 if (BaseType->isDependentType()) 2747 continue; 2748 2749 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2750 .getUnqualifiedType(); 2751 2752 if (IndirectBaseTypes.count(CanonicalBase)) { 2753 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2754 /*DetectVirtual=*/true); 2755 bool found 2756 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2757 assert(found); 2758 (void)found; 2759 2760 if (Paths.isAmbiguous(CanonicalBase)) 2761 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2762 << BaseType << getAmbiguousPathsDisplayString(Paths) 2763 << Bases[idx]->getSourceRange(); 2764 else 2765 assert(Bases[idx]->isVirtual()); 2766 } 2767 2768 // Delete the base class specifier, since its data has been copied 2769 // into the CXXRecordDecl. 2770 Context.Deallocate(Bases[idx]); 2771 } 2772 2773 return Invalid; 2774 } 2775 2776 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2777 /// class, after checking whether there are any duplicate base 2778 /// classes. 2779 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2780 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2781 if (!ClassDecl || Bases.empty()) 2782 return; 2783 2784 AdjustDeclIfTemplate(ClassDecl); 2785 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2786 } 2787 2788 /// Determine whether the type \p Derived is a C++ class that is 2789 /// derived from the type \p Base. 2790 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2791 if (!getLangOpts().CPlusPlus) 2792 return false; 2793 2794 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2795 if (!DerivedRD) 2796 return false; 2797 2798 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2799 if (!BaseRD) 2800 return false; 2801 2802 // If either the base or the derived type is invalid, don't try to 2803 // check whether one is derived from the other. 2804 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2805 return false; 2806 2807 // FIXME: In a modules build, do we need the entire path to be visible for us 2808 // to be able to use the inheritance relationship? 2809 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2810 return false; 2811 2812 return DerivedRD->isDerivedFrom(BaseRD); 2813 } 2814 2815 /// Determine whether the type \p Derived is a C++ class that is 2816 /// derived from the type \p Base. 2817 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2818 CXXBasePaths &Paths) { 2819 if (!getLangOpts().CPlusPlus) 2820 return false; 2821 2822 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2823 if (!DerivedRD) 2824 return false; 2825 2826 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2827 if (!BaseRD) 2828 return false; 2829 2830 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2831 return false; 2832 2833 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2834 } 2835 2836 static void BuildBasePathArray(const CXXBasePath &Path, 2837 CXXCastPath &BasePathArray) { 2838 // We first go backward and check if we have a virtual base. 2839 // FIXME: It would be better if CXXBasePath had the base specifier for 2840 // the nearest virtual base. 2841 unsigned Start = 0; 2842 for (unsigned I = Path.size(); I != 0; --I) { 2843 if (Path[I - 1].Base->isVirtual()) { 2844 Start = I - 1; 2845 break; 2846 } 2847 } 2848 2849 // Now add all bases. 2850 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2851 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2852 } 2853 2854 2855 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2856 CXXCastPath &BasePathArray) { 2857 assert(BasePathArray.empty() && "Base path array must be empty!"); 2858 assert(Paths.isRecordingPaths() && "Must record paths!"); 2859 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2860 } 2861 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2862 /// conversion (where Derived and Base are class types) is 2863 /// well-formed, meaning that the conversion is unambiguous (and 2864 /// that all of the base classes are accessible). Returns true 2865 /// and emits a diagnostic if the code is ill-formed, returns false 2866 /// otherwise. Loc is the location where this routine should point to 2867 /// if there is an error, and Range is the source range to highlight 2868 /// if there is an error. 2869 /// 2870 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the 2871 /// diagnostic for the respective type of error will be suppressed, but the 2872 /// check for ill-formed code will still be performed. 2873 bool 2874 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2875 unsigned InaccessibleBaseID, 2876 unsigned AmbiguousBaseConvID, 2877 SourceLocation Loc, SourceRange Range, 2878 DeclarationName Name, 2879 CXXCastPath *BasePath, 2880 bool IgnoreAccess) { 2881 // First, determine whether the path from Derived to Base is 2882 // ambiguous. This is slightly more expensive than checking whether 2883 // the Derived to Base conversion exists, because here we need to 2884 // explore multiple paths to determine if there is an ambiguity. 2885 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2886 /*DetectVirtual=*/false); 2887 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2888 if (!DerivationOkay) 2889 return true; 2890 2891 const CXXBasePath *Path = nullptr; 2892 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2893 Path = &Paths.front(); 2894 2895 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2896 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2897 // user to access such bases. 2898 if (!Path && getLangOpts().MSVCCompat) { 2899 for (const CXXBasePath &PossiblePath : Paths) { 2900 if (PossiblePath.size() == 1) { 2901 Path = &PossiblePath; 2902 if (AmbiguousBaseConvID) 2903 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2904 << Base << Derived << Range; 2905 break; 2906 } 2907 } 2908 } 2909 2910 if (Path) { 2911 if (!IgnoreAccess) { 2912 // Check that the base class can be accessed. 2913 switch ( 2914 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2915 case AR_inaccessible: 2916 return true; 2917 case AR_accessible: 2918 case AR_dependent: 2919 case AR_delayed: 2920 break; 2921 } 2922 } 2923 2924 // Build a base path if necessary. 2925 if (BasePath) 2926 ::BuildBasePathArray(*Path, *BasePath); 2927 return false; 2928 } 2929 2930 if (AmbiguousBaseConvID) { 2931 // We know that the derived-to-base conversion is ambiguous, and 2932 // we're going to produce a diagnostic. Perform the derived-to-base 2933 // search just one more time to compute all of the possible paths so 2934 // that we can print them out. This is more expensive than any of 2935 // the previous derived-to-base checks we've done, but at this point 2936 // performance isn't as much of an issue. 2937 Paths.clear(); 2938 Paths.setRecordingPaths(true); 2939 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2940 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2941 (void)StillOkay; 2942 2943 // Build up a textual representation of the ambiguous paths, e.g., 2944 // D -> B -> A, that will be used to illustrate the ambiguous 2945 // conversions in the diagnostic. We only print one of the paths 2946 // to each base class subobject. 2947 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2948 2949 Diag(Loc, AmbiguousBaseConvID) 2950 << Derived << Base << PathDisplayStr << Range << Name; 2951 } 2952 return true; 2953 } 2954 2955 bool 2956 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2957 SourceLocation Loc, SourceRange Range, 2958 CXXCastPath *BasePath, 2959 bool IgnoreAccess) { 2960 return CheckDerivedToBaseConversion( 2961 Derived, Base, diag::err_upcast_to_inaccessible_base, 2962 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2963 BasePath, IgnoreAccess); 2964 } 2965 2966 2967 /// Builds a string representing ambiguous paths from a 2968 /// specific derived class to different subobjects of the same base 2969 /// class. 2970 /// 2971 /// This function builds a string that can be used in error messages 2972 /// to show the different paths that one can take through the 2973 /// inheritance hierarchy to go from the derived class to different 2974 /// subobjects of a base class. The result looks something like this: 2975 /// @code 2976 /// struct D -> struct B -> struct A 2977 /// struct D -> struct C -> struct A 2978 /// @endcode 2979 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2980 std::string PathDisplayStr; 2981 std::set<unsigned> DisplayedPaths; 2982 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2983 Path != Paths.end(); ++Path) { 2984 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2985 // We haven't displayed a path to this particular base 2986 // class subobject yet. 2987 PathDisplayStr += "\n "; 2988 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2989 for (CXXBasePath::const_iterator Element = Path->begin(); 2990 Element != Path->end(); ++Element) 2991 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2992 } 2993 } 2994 2995 return PathDisplayStr; 2996 } 2997 2998 //===----------------------------------------------------------------------===// 2999 // C++ class member Handling 3000 //===----------------------------------------------------------------------===// 3001 3002 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 3003 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 3004 SourceLocation ColonLoc, 3005 const ParsedAttributesView &Attrs) { 3006 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 3007 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 3008 ASLoc, ColonLoc); 3009 CurContext->addHiddenDecl(ASDecl); 3010 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 3011 } 3012 3013 /// CheckOverrideControl - Check C++11 override control semantics. 3014 void Sema::CheckOverrideControl(NamedDecl *D) { 3015 if (D->isInvalidDecl()) 3016 return; 3017 3018 // We only care about "override" and "final" declarations. 3019 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 3020 return; 3021 3022 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3023 3024 // We can't check dependent instance methods. 3025 if (MD && MD->isInstance() && 3026 (MD->getParent()->hasAnyDependentBases() || 3027 MD->getType()->isDependentType())) 3028 return; 3029 3030 if (MD && !MD->isVirtual()) { 3031 // If we have a non-virtual method, check if if hides a virtual method. 3032 // (In that case, it's most likely the method has the wrong type.) 3033 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 3034 FindHiddenVirtualMethods(MD, OverloadedMethods); 3035 3036 if (!OverloadedMethods.empty()) { 3037 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3038 Diag(OA->getLocation(), 3039 diag::override_keyword_hides_virtual_member_function) 3040 << "override" << (OverloadedMethods.size() > 1); 3041 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3042 Diag(FA->getLocation(), 3043 diag::override_keyword_hides_virtual_member_function) 3044 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3045 << (OverloadedMethods.size() > 1); 3046 } 3047 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3048 MD->setInvalidDecl(); 3049 return; 3050 } 3051 // Fall through into the general case diagnostic. 3052 // FIXME: We might want to attempt typo correction here. 3053 } 3054 3055 if (!MD || !MD->isVirtual()) { 3056 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3057 Diag(OA->getLocation(), 3058 diag::override_keyword_only_allowed_on_virtual_member_functions) 3059 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3060 D->dropAttr<OverrideAttr>(); 3061 } 3062 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3063 Diag(FA->getLocation(), 3064 diag::override_keyword_only_allowed_on_virtual_member_functions) 3065 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3066 << FixItHint::CreateRemoval(FA->getLocation()); 3067 D->dropAttr<FinalAttr>(); 3068 } 3069 return; 3070 } 3071 3072 // C++11 [class.virtual]p5: 3073 // If a function is marked with the virt-specifier override and 3074 // does not override a member function of a base class, the program is 3075 // ill-formed. 3076 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3077 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3078 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3079 << MD->getDeclName(); 3080 } 3081 3082 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { 3083 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3084 return; 3085 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3086 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3087 return; 3088 3089 SourceLocation Loc = MD->getLocation(); 3090 SourceLocation SpellingLoc = Loc; 3091 if (getSourceManager().isMacroArgExpansion(Loc)) 3092 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3093 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3094 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3095 return; 3096 3097 if (MD->size_overridden_methods() > 0) { 3098 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { 3099 unsigned DiagID = 3100 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation()) 3101 ? DiagInconsistent 3102 : DiagSuggest; 3103 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3104 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3105 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3106 }; 3107 if (isa<CXXDestructorDecl>(MD)) 3108 EmitDiag( 3109 diag::warn_inconsistent_destructor_marked_not_override_overriding, 3110 diag::warn_suggest_destructor_marked_not_override_overriding); 3111 else 3112 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding, 3113 diag::warn_suggest_function_marked_not_override_overriding); 3114 } 3115 } 3116 3117 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3118 /// function overrides a virtual member function marked 'final', according to 3119 /// C++11 [class.virtual]p4. 3120 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3121 const CXXMethodDecl *Old) { 3122 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3123 if (!FA) 3124 return false; 3125 3126 Diag(New->getLocation(), diag::err_final_function_overridden) 3127 << New->getDeclName() 3128 << FA->isSpelledAsSealed(); 3129 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3130 return true; 3131 } 3132 3133 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3134 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3135 // FIXME: Destruction of ObjC lifetime types has side-effects. 3136 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3137 return !RD->isCompleteDefinition() || 3138 !RD->hasTrivialDefaultConstructor() || 3139 !RD->hasTrivialDestructor(); 3140 return false; 3141 } 3142 3143 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3144 ParsedAttributesView::const_iterator Itr = 3145 llvm::find_if(list, [](const ParsedAttr &AL) { 3146 return AL.isDeclspecPropertyAttribute(); 3147 }); 3148 if (Itr != list.end()) 3149 return &*Itr; 3150 return nullptr; 3151 } 3152 3153 // Check if there is a field shadowing. 3154 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3155 DeclarationName FieldName, 3156 const CXXRecordDecl *RD, 3157 bool DeclIsField) { 3158 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3159 return; 3160 3161 // To record a shadowed field in a base 3162 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3163 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3164 CXXBasePath &Path) { 3165 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3166 // Record an ambiguous path directly 3167 if (Bases.find(Base) != Bases.end()) 3168 return true; 3169 for (const auto Field : Base->lookup(FieldName)) { 3170 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3171 Field->getAccess() != AS_private) { 3172 assert(Field->getAccess() != AS_none); 3173 assert(Bases.find(Base) == Bases.end()); 3174 Bases[Base] = Field; 3175 return true; 3176 } 3177 } 3178 return false; 3179 }; 3180 3181 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3182 /*DetectVirtual=*/true); 3183 if (!RD->lookupInBases(FieldShadowed, Paths)) 3184 return; 3185 3186 for (const auto &P : Paths) { 3187 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3188 auto It = Bases.find(Base); 3189 // Skip duplicated bases 3190 if (It == Bases.end()) 3191 continue; 3192 auto BaseField = It->second; 3193 assert(BaseField->getAccess() != AS_private); 3194 if (AS_none != 3195 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3196 Diag(Loc, diag::warn_shadow_field) 3197 << FieldName << RD << Base << DeclIsField; 3198 Diag(BaseField->getLocation(), diag::note_shadow_field); 3199 Bases.erase(It); 3200 } 3201 } 3202 } 3203 3204 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3205 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3206 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3207 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3208 /// present (but parsing it has been deferred). 3209 NamedDecl * 3210 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3211 MultiTemplateParamsArg TemplateParameterLists, 3212 Expr *BW, const VirtSpecifiers &VS, 3213 InClassInitStyle InitStyle) { 3214 const DeclSpec &DS = D.getDeclSpec(); 3215 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3216 DeclarationName Name = NameInfo.getName(); 3217 SourceLocation Loc = NameInfo.getLoc(); 3218 3219 // For anonymous bitfields, the location should point to the type. 3220 if (Loc.isInvalid()) 3221 Loc = D.getBeginLoc(); 3222 3223 Expr *BitWidth = static_cast<Expr*>(BW); 3224 3225 assert(isa<CXXRecordDecl>(CurContext)); 3226 assert(!DS.isFriendSpecified()); 3227 3228 bool isFunc = D.isDeclarationOfFunction(); 3229 const ParsedAttr *MSPropertyAttr = 3230 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3231 3232 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3233 // The Microsoft extension __interface only permits public member functions 3234 // and prohibits constructors, destructors, operators, non-public member 3235 // functions, static methods and data members. 3236 unsigned InvalidDecl; 3237 bool ShowDeclName = true; 3238 if (!isFunc && 3239 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3240 InvalidDecl = 0; 3241 else if (!isFunc) 3242 InvalidDecl = 1; 3243 else if (AS != AS_public) 3244 InvalidDecl = 2; 3245 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3246 InvalidDecl = 3; 3247 else switch (Name.getNameKind()) { 3248 case DeclarationName::CXXConstructorName: 3249 InvalidDecl = 4; 3250 ShowDeclName = false; 3251 break; 3252 3253 case DeclarationName::CXXDestructorName: 3254 InvalidDecl = 5; 3255 ShowDeclName = false; 3256 break; 3257 3258 case DeclarationName::CXXOperatorName: 3259 case DeclarationName::CXXConversionFunctionName: 3260 InvalidDecl = 6; 3261 break; 3262 3263 default: 3264 InvalidDecl = 0; 3265 break; 3266 } 3267 3268 if (InvalidDecl) { 3269 if (ShowDeclName) 3270 Diag(Loc, diag::err_invalid_member_in_interface) 3271 << (InvalidDecl-1) << Name; 3272 else 3273 Diag(Loc, diag::err_invalid_member_in_interface) 3274 << (InvalidDecl-1) << ""; 3275 return nullptr; 3276 } 3277 } 3278 3279 // C++ 9.2p6: A member shall not be declared to have automatic storage 3280 // duration (auto, register) or with the extern storage-class-specifier. 3281 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3282 // data members and cannot be applied to names declared const or static, 3283 // and cannot be applied to reference members. 3284 switch (DS.getStorageClassSpec()) { 3285 case DeclSpec::SCS_unspecified: 3286 case DeclSpec::SCS_typedef: 3287 case DeclSpec::SCS_static: 3288 break; 3289 case DeclSpec::SCS_mutable: 3290 if (isFunc) { 3291 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3292 3293 // FIXME: It would be nicer if the keyword was ignored only for this 3294 // declarator. Otherwise we could get follow-up errors. 3295 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3296 } 3297 break; 3298 default: 3299 Diag(DS.getStorageClassSpecLoc(), 3300 diag::err_storageclass_invalid_for_member); 3301 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3302 break; 3303 } 3304 3305 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3306 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3307 !isFunc); 3308 3309 if (DS.hasConstexprSpecifier() && isInstField) { 3310 SemaDiagnosticBuilder B = 3311 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3312 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3313 if (InitStyle == ICIS_NoInit) { 3314 B << 0 << 0; 3315 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3316 B << FixItHint::CreateRemoval(ConstexprLoc); 3317 else { 3318 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3319 D.getMutableDeclSpec().ClearConstexprSpec(); 3320 const char *PrevSpec; 3321 unsigned DiagID; 3322 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3323 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3324 (void)Failed; 3325 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3326 } 3327 } else { 3328 B << 1; 3329 const char *PrevSpec; 3330 unsigned DiagID; 3331 if (D.getMutableDeclSpec().SetStorageClassSpec( 3332 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3333 Context.getPrintingPolicy())) { 3334 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3335 "This is the only DeclSpec that should fail to be applied"); 3336 B << 1; 3337 } else { 3338 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3339 isInstField = false; 3340 } 3341 } 3342 } 3343 3344 NamedDecl *Member; 3345 if (isInstField) { 3346 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3347 3348 // Data members must have identifiers for names. 3349 if (!Name.isIdentifier()) { 3350 Diag(Loc, diag::err_bad_variable_name) 3351 << Name; 3352 return nullptr; 3353 } 3354 3355 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3356 3357 // Member field could not be with "template" keyword. 3358 // So TemplateParameterLists should be empty in this case. 3359 if (TemplateParameterLists.size()) { 3360 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3361 if (TemplateParams->size()) { 3362 // There is no such thing as a member field template. 3363 Diag(D.getIdentifierLoc(), diag::err_template_member) 3364 << II 3365 << SourceRange(TemplateParams->getTemplateLoc(), 3366 TemplateParams->getRAngleLoc()); 3367 } else { 3368 // There is an extraneous 'template<>' for this member. 3369 Diag(TemplateParams->getTemplateLoc(), 3370 diag::err_template_member_noparams) 3371 << II 3372 << SourceRange(TemplateParams->getTemplateLoc(), 3373 TemplateParams->getRAngleLoc()); 3374 } 3375 return nullptr; 3376 } 3377 3378 if (SS.isSet() && !SS.isInvalid()) { 3379 // The user provided a superfluous scope specifier inside a class 3380 // definition: 3381 // 3382 // class X { 3383 // int X::member; 3384 // }; 3385 if (DeclContext *DC = computeDeclContext(SS, false)) 3386 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3387 D.getName().getKind() == 3388 UnqualifiedIdKind::IK_TemplateId); 3389 else 3390 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3391 << Name << SS.getRange(); 3392 3393 SS.clear(); 3394 } 3395 3396 if (MSPropertyAttr) { 3397 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3398 BitWidth, InitStyle, AS, *MSPropertyAttr); 3399 if (!Member) 3400 return nullptr; 3401 isInstField = false; 3402 } else { 3403 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3404 BitWidth, InitStyle, AS); 3405 if (!Member) 3406 return nullptr; 3407 } 3408 3409 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3410 } else { 3411 Member = HandleDeclarator(S, D, TemplateParameterLists); 3412 if (!Member) 3413 return nullptr; 3414 3415 // Non-instance-fields can't have a bitfield. 3416 if (BitWidth) { 3417 if (Member->isInvalidDecl()) { 3418 // don't emit another diagnostic. 3419 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3420 // C++ 9.6p3: A bit-field shall not be a static member. 3421 // "static member 'A' cannot be a bit-field" 3422 Diag(Loc, diag::err_static_not_bitfield) 3423 << Name << BitWidth->getSourceRange(); 3424 } else if (isa<TypedefDecl>(Member)) { 3425 // "typedef member 'x' cannot be a bit-field" 3426 Diag(Loc, diag::err_typedef_not_bitfield) 3427 << Name << BitWidth->getSourceRange(); 3428 } else { 3429 // A function typedef ("typedef int f(); f a;"). 3430 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3431 Diag(Loc, diag::err_not_integral_type_bitfield) 3432 << Name << cast<ValueDecl>(Member)->getType() 3433 << BitWidth->getSourceRange(); 3434 } 3435 3436 BitWidth = nullptr; 3437 Member->setInvalidDecl(); 3438 } 3439 3440 NamedDecl *NonTemplateMember = Member; 3441 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3442 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3443 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3444 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3445 3446 Member->setAccess(AS); 3447 3448 // If we have declared a member function template or static data member 3449 // template, set the access of the templated declaration as well. 3450 if (NonTemplateMember != Member) 3451 NonTemplateMember->setAccess(AS); 3452 3453 // C++ [temp.deduct.guide]p3: 3454 // A deduction guide [...] for a member class template [shall be 3455 // declared] with the same access [as the template]. 3456 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3457 auto *TD = DG->getDeducedTemplate(); 3458 // Access specifiers are only meaningful if both the template and the 3459 // deduction guide are from the same scope. 3460 if (AS != TD->getAccess() && 3461 TD->getDeclContext()->getRedeclContext()->Equals( 3462 DG->getDeclContext()->getRedeclContext())) { 3463 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3464 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3465 << TD->getAccess(); 3466 const AccessSpecDecl *LastAccessSpec = nullptr; 3467 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3468 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3469 LastAccessSpec = AccessSpec; 3470 } 3471 assert(LastAccessSpec && "differing access with no access specifier"); 3472 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3473 << AS; 3474 } 3475 } 3476 } 3477 3478 if (VS.isOverrideSpecified()) 3479 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3480 AttributeCommonInfo::AS_Keyword)); 3481 if (VS.isFinalSpecified()) 3482 Member->addAttr(FinalAttr::Create( 3483 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3484 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3485 3486 if (VS.getLastLocation().isValid()) { 3487 // Update the end location of a method that has a virt-specifiers. 3488 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3489 MD->setRangeEnd(VS.getLastLocation()); 3490 } 3491 3492 CheckOverrideControl(Member); 3493 3494 assert((Name || isInstField) && "No identifier for non-field ?"); 3495 3496 if (isInstField) { 3497 FieldDecl *FD = cast<FieldDecl>(Member); 3498 FieldCollector->Add(FD); 3499 3500 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3501 // Remember all explicit private FieldDecls that have a name, no side 3502 // effects and are not part of a dependent type declaration. 3503 if (!FD->isImplicit() && FD->getDeclName() && 3504 FD->getAccess() == AS_private && 3505 !FD->hasAttr<UnusedAttr>() && 3506 !FD->getParent()->isDependentContext() && 3507 !InitializationHasSideEffects(*FD)) 3508 UnusedPrivateFields.insert(FD); 3509 } 3510 } 3511 3512 return Member; 3513 } 3514 3515 namespace { 3516 class UninitializedFieldVisitor 3517 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3518 Sema &S; 3519 // List of Decls to generate a warning on. Also remove Decls that become 3520 // initialized. 3521 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3522 // List of base classes of the record. Classes are removed after their 3523 // initializers. 3524 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3525 // Vector of decls to be removed from the Decl set prior to visiting the 3526 // nodes. These Decls may have been initialized in the prior initializer. 3527 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3528 // If non-null, add a note to the warning pointing back to the constructor. 3529 const CXXConstructorDecl *Constructor; 3530 // Variables to hold state when processing an initializer list. When 3531 // InitList is true, special case initialization of FieldDecls matching 3532 // InitListFieldDecl. 3533 bool InitList; 3534 FieldDecl *InitListFieldDecl; 3535 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3536 3537 public: 3538 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3539 UninitializedFieldVisitor(Sema &S, 3540 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3541 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3542 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3543 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3544 3545 // Returns true if the use of ME is not an uninitialized use. 3546 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3547 bool CheckReferenceOnly) { 3548 llvm::SmallVector<FieldDecl*, 4> Fields; 3549 bool ReferenceField = false; 3550 while (ME) { 3551 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3552 if (!FD) 3553 return false; 3554 Fields.push_back(FD); 3555 if (FD->getType()->isReferenceType()) 3556 ReferenceField = true; 3557 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3558 } 3559 3560 // Binding a reference to an uninitialized field is not an 3561 // uninitialized use. 3562 if (CheckReferenceOnly && !ReferenceField) 3563 return true; 3564 3565 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3566 // Discard the first field since it is the field decl that is being 3567 // initialized. 3568 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3569 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3570 } 3571 3572 for (auto UsedIter = UsedFieldIndex.begin(), 3573 UsedEnd = UsedFieldIndex.end(), 3574 OrigIter = InitFieldIndex.begin(), 3575 OrigEnd = InitFieldIndex.end(); 3576 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3577 if (*UsedIter < *OrigIter) 3578 return true; 3579 if (*UsedIter > *OrigIter) 3580 break; 3581 } 3582 3583 return false; 3584 } 3585 3586 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3587 bool AddressOf) { 3588 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3589 return; 3590 3591 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3592 // or union. 3593 MemberExpr *FieldME = ME; 3594 3595 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3596 3597 Expr *Base = ME; 3598 while (MemberExpr *SubME = 3599 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3600 3601 if (isa<VarDecl>(SubME->getMemberDecl())) 3602 return; 3603 3604 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3605 if (!FD->isAnonymousStructOrUnion()) 3606 FieldME = SubME; 3607 3608 if (!FieldME->getType().isPODType(S.Context)) 3609 AllPODFields = false; 3610 3611 Base = SubME->getBase(); 3612 } 3613 3614 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) { 3615 Visit(Base); 3616 return; 3617 } 3618 3619 if (AddressOf && AllPODFields) 3620 return; 3621 3622 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3623 3624 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3625 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3626 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3627 } 3628 3629 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3630 QualType T = BaseCast->getType(); 3631 if (T->isPointerType() && 3632 BaseClasses.count(T->getPointeeType())) { 3633 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3634 << T->getPointeeType() << FoundVD; 3635 } 3636 } 3637 } 3638 3639 if (!Decls.count(FoundVD)) 3640 return; 3641 3642 const bool IsReference = FoundVD->getType()->isReferenceType(); 3643 3644 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3645 // Special checking for initializer lists. 3646 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3647 return; 3648 } 3649 } else { 3650 // Prevent double warnings on use of unbounded references. 3651 if (CheckReferenceOnly && !IsReference) 3652 return; 3653 } 3654 3655 unsigned diag = IsReference 3656 ? diag::warn_reference_field_is_uninit 3657 : diag::warn_field_is_uninit; 3658 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3659 if (Constructor) 3660 S.Diag(Constructor->getLocation(), 3661 diag::note_uninit_in_this_constructor) 3662 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3663 3664 } 3665 3666 void HandleValue(Expr *E, bool AddressOf) { 3667 E = E->IgnoreParens(); 3668 3669 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3670 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3671 AddressOf /*AddressOf*/); 3672 return; 3673 } 3674 3675 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3676 Visit(CO->getCond()); 3677 HandleValue(CO->getTrueExpr(), AddressOf); 3678 HandleValue(CO->getFalseExpr(), AddressOf); 3679 return; 3680 } 3681 3682 if (BinaryConditionalOperator *BCO = 3683 dyn_cast<BinaryConditionalOperator>(E)) { 3684 Visit(BCO->getCond()); 3685 HandleValue(BCO->getFalseExpr(), AddressOf); 3686 return; 3687 } 3688 3689 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3690 HandleValue(OVE->getSourceExpr(), AddressOf); 3691 return; 3692 } 3693 3694 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3695 switch (BO->getOpcode()) { 3696 default: 3697 break; 3698 case(BO_PtrMemD): 3699 case(BO_PtrMemI): 3700 HandleValue(BO->getLHS(), AddressOf); 3701 Visit(BO->getRHS()); 3702 return; 3703 case(BO_Comma): 3704 Visit(BO->getLHS()); 3705 HandleValue(BO->getRHS(), AddressOf); 3706 return; 3707 } 3708 } 3709 3710 Visit(E); 3711 } 3712 3713 void CheckInitListExpr(InitListExpr *ILE) { 3714 InitFieldIndex.push_back(0); 3715 for (auto Child : ILE->children()) { 3716 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3717 CheckInitListExpr(SubList); 3718 } else { 3719 Visit(Child); 3720 } 3721 ++InitFieldIndex.back(); 3722 } 3723 InitFieldIndex.pop_back(); 3724 } 3725 3726 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3727 FieldDecl *Field, const Type *BaseClass) { 3728 // Remove Decls that may have been initialized in the previous 3729 // initializer. 3730 for (ValueDecl* VD : DeclsToRemove) 3731 Decls.erase(VD); 3732 DeclsToRemove.clear(); 3733 3734 Constructor = FieldConstructor; 3735 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3736 3737 if (ILE && Field) { 3738 InitList = true; 3739 InitListFieldDecl = Field; 3740 InitFieldIndex.clear(); 3741 CheckInitListExpr(ILE); 3742 } else { 3743 InitList = false; 3744 Visit(E); 3745 } 3746 3747 if (Field) 3748 Decls.erase(Field); 3749 if (BaseClass) 3750 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3751 } 3752 3753 void VisitMemberExpr(MemberExpr *ME) { 3754 // All uses of unbounded reference fields will warn. 3755 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3756 } 3757 3758 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3759 if (E->getCastKind() == CK_LValueToRValue) { 3760 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3761 return; 3762 } 3763 3764 Inherited::VisitImplicitCastExpr(E); 3765 } 3766 3767 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3768 if (E->getConstructor()->isCopyConstructor()) { 3769 Expr *ArgExpr = E->getArg(0); 3770 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3771 if (ILE->getNumInits() == 1) 3772 ArgExpr = ILE->getInit(0); 3773 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3774 if (ICE->getCastKind() == CK_NoOp) 3775 ArgExpr = ICE->getSubExpr(); 3776 HandleValue(ArgExpr, false /*AddressOf*/); 3777 return; 3778 } 3779 Inherited::VisitCXXConstructExpr(E); 3780 } 3781 3782 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3783 Expr *Callee = E->getCallee(); 3784 if (isa<MemberExpr>(Callee)) { 3785 HandleValue(Callee, false /*AddressOf*/); 3786 for (auto Arg : E->arguments()) 3787 Visit(Arg); 3788 return; 3789 } 3790 3791 Inherited::VisitCXXMemberCallExpr(E); 3792 } 3793 3794 void VisitCallExpr(CallExpr *E) { 3795 // Treat std::move as a use. 3796 if (E->isCallToStdMove()) { 3797 HandleValue(E->getArg(0), /*AddressOf=*/false); 3798 return; 3799 } 3800 3801 Inherited::VisitCallExpr(E); 3802 } 3803 3804 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3805 Expr *Callee = E->getCallee(); 3806 3807 if (isa<UnresolvedLookupExpr>(Callee)) 3808 return Inherited::VisitCXXOperatorCallExpr(E); 3809 3810 Visit(Callee); 3811 for (auto Arg : E->arguments()) 3812 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3813 } 3814 3815 void VisitBinaryOperator(BinaryOperator *E) { 3816 // If a field assignment is detected, remove the field from the 3817 // uninitiailized field set. 3818 if (E->getOpcode() == BO_Assign) 3819 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3820 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3821 if (!FD->getType()->isReferenceType()) 3822 DeclsToRemove.push_back(FD); 3823 3824 if (E->isCompoundAssignmentOp()) { 3825 HandleValue(E->getLHS(), false /*AddressOf*/); 3826 Visit(E->getRHS()); 3827 return; 3828 } 3829 3830 Inherited::VisitBinaryOperator(E); 3831 } 3832 3833 void VisitUnaryOperator(UnaryOperator *E) { 3834 if (E->isIncrementDecrementOp()) { 3835 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3836 return; 3837 } 3838 if (E->getOpcode() == UO_AddrOf) { 3839 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3840 HandleValue(ME->getBase(), true /*AddressOf*/); 3841 return; 3842 } 3843 } 3844 3845 Inherited::VisitUnaryOperator(E); 3846 } 3847 }; 3848 3849 // Diagnose value-uses of fields to initialize themselves, e.g. 3850 // foo(foo) 3851 // where foo is not also a parameter to the constructor. 3852 // Also diagnose across field uninitialized use such as 3853 // x(y), y(x) 3854 // TODO: implement -Wuninitialized and fold this into that framework. 3855 static void DiagnoseUninitializedFields( 3856 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3857 3858 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3859 Constructor->getLocation())) { 3860 return; 3861 } 3862 3863 if (Constructor->isInvalidDecl()) 3864 return; 3865 3866 const CXXRecordDecl *RD = Constructor->getParent(); 3867 3868 if (RD->isDependentContext()) 3869 return; 3870 3871 // Holds fields that are uninitialized. 3872 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3873 3874 // At the beginning, all fields are uninitialized. 3875 for (auto *I : RD->decls()) { 3876 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3877 UninitializedFields.insert(FD); 3878 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3879 UninitializedFields.insert(IFD->getAnonField()); 3880 } 3881 } 3882 3883 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3884 for (auto I : RD->bases()) 3885 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3886 3887 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3888 return; 3889 3890 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3891 UninitializedFields, 3892 UninitializedBaseClasses); 3893 3894 for (const auto *FieldInit : Constructor->inits()) { 3895 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3896 break; 3897 3898 Expr *InitExpr = FieldInit->getInit(); 3899 if (!InitExpr) 3900 continue; 3901 3902 if (CXXDefaultInitExpr *Default = 3903 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3904 InitExpr = Default->getExpr(); 3905 if (!InitExpr) 3906 continue; 3907 // In class initializers will point to the constructor. 3908 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3909 FieldInit->getAnyMember(), 3910 FieldInit->getBaseClass()); 3911 } else { 3912 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3913 FieldInit->getAnyMember(), 3914 FieldInit->getBaseClass()); 3915 } 3916 } 3917 } 3918 } // namespace 3919 3920 /// Enter a new C++ default initializer scope. After calling this, the 3921 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3922 /// parsing or instantiating the initializer failed. 3923 void Sema::ActOnStartCXXInClassMemberInitializer() { 3924 // Create a synthetic function scope to represent the call to the constructor 3925 // that notionally surrounds a use of this initializer. 3926 PushFunctionScope(); 3927 } 3928 3929 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 3930 if (!D.isFunctionDeclarator()) 3931 return; 3932 auto &FTI = D.getFunctionTypeInfo(); 3933 if (!FTI.Params) 3934 return; 3935 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 3936 FTI.NumParams)) { 3937 auto *ParamDecl = cast<NamedDecl>(Param.Param); 3938 if (ParamDecl->getDeclName()) 3939 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 3940 } 3941 } 3942 3943 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 3944 return ActOnRequiresClause(ConstraintExpr); 3945 } 3946 3947 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) { 3948 if (ConstraintExpr.isInvalid()) 3949 return ExprError(); 3950 3951 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr); 3952 if (ConstraintExpr.isInvalid()) 3953 return ExprError(); 3954 3955 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(), 3956 UPPC_RequiresClause)) 3957 return ExprError(); 3958 3959 return ConstraintExpr; 3960 } 3961 3962 /// This is invoked after parsing an in-class initializer for a 3963 /// non-static C++ class member, and after instantiating an in-class initializer 3964 /// in a class template. Such actions are deferred until the class is complete. 3965 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3966 SourceLocation InitLoc, 3967 Expr *InitExpr) { 3968 // Pop the notional constructor scope we created earlier. 3969 PopFunctionScopeInfo(nullptr, D); 3970 3971 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3972 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3973 "must set init style when field is created"); 3974 3975 if (!InitExpr) { 3976 D->setInvalidDecl(); 3977 if (FD) 3978 FD->removeInClassInitializer(); 3979 return; 3980 } 3981 3982 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3983 FD->setInvalidDecl(); 3984 FD->removeInClassInitializer(); 3985 return; 3986 } 3987 3988 ExprResult Init = InitExpr; 3989 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3990 InitializedEntity Entity = 3991 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3992 InitializationKind Kind = 3993 FD->getInClassInitStyle() == ICIS_ListInit 3994 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 3995 InitExpr->getBeginLoc(), 3996 InitExpr->getEndLoc()) 3997 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 3998 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3999 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 4000 if (Init.isInvalid()) { 4001 FD->setInvalidDecl(); 4002 return; 4003 } 4004 } 4005 4006 // C++11 [class.base.init]p7: 4007 // The initialization of each base and member constitutes a 4008 // full-expression. 4009 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 4010 if (Init.isInvalid()) { 4011 FD->setInvalidDecl(); 4012 return; 4013 } 4014 4015 InitExpr = Init.get(); 4016 4017 FD->setInClassInitializer(InitExpr); 4018 } 4019 4020 /// Find the direct and/or virtual base specifiers that 4021 /// correspond to the given base type, for use in base initialization 4022 /// within a constructor. 4023 static bool FindBaseInitializer(Sema &SemaRef, 4024 CXXRecordDecl *ClassDecl, 4025 QualType BaseType, 4026 const CXXBaseSpecifier *&DirectBaseSpec, 4027 const CXXBaseSpecifier *&VirtualBaseSpec) { 4028 // First, check for a direct base class. 4029 DirectBaseSpec = nullptr; 4030 for (const auto &Base : ClassDecl->bases()) { 4031 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 4032 // We found a direct base of this type. That's what we're 4033 // initializing. 4034 DirectBaseSpec = &Base; 4035 break; 4036 } 4037 } 4038 4039 // Check for a virtual base class. 4040 // FIXME: We might be able to short-circuit this if we know in advance that 4041 // there are no virtual bases. 4042 VirtualBaseSpec = nullptr; 4043 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 4044 // We haven't found a base yet; search the class hierarchy for a 4045 // virtual base class. 4046 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 4047 /*DetectVirtual=*/false); 4048 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 4049 SemaRef.Context.getTypeDeclType(ClassDecl), 4050 BaseType, Paths)) { 4051 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 4052 Path != Paths.end(); ++Path) { 4053 if (Path->back().Base->isVirtual()) { 4054 VirtualBaseSpec = Path->back().Base; 4055 break; 4056 } 4057 } 4058 } 4059 } 4060 4061 return DirectBaseSpec || VirtualBaseSpec; 4062 } 4063 4064 /// Handle a C++ member initializer using braced-init-list syntax. 4065 MemInitResult 4066 Sema::ActOnMemInitializer(Decl *ConstructorD, 4067 Scope *S, 4068 CXXScopeSpec &SS, 4069 IdentifierInfo *MemberOrBase, 4070 ParsedType TemplateTypeTy, 4071 const DeclSpec &DS, 4072 SourceLocation IdLoc, 4073 Expr *InitList, 4074 SourceLocation EllipsisLoc) { 4075 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4076 DS, IdLoc, InitList, 4077 EllipsisLoc); 4078 } 4079 4080 /// Handle a C++ member initializer using parentheses syntax. 4081 MemInitResult 4082 Sema::ActOnMemInitializer(Decl *ConstructorD, 4083 Scope *S, 4084 CXXScopeSpec &SS, 4085 IdentifierInfo *MemberOrBase, 4086 ParsedType TemplateTypeTy, 4087 const DeclSpec &DS, 4088 SourceLocation IdLoc, 4089 SourceLocation LParenLoc, 4090 ArrayRef<Expr *> Args, 4091 SourceLocation RParenLoc, 4092 SourceLocation EllipsisLoc) { 4093 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4094 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4095 DS, IdLoc, List, EllipsisLoc); 4096 } 4097 4098 namespace { 4099 4100 // Callback to only accept typo corrections that can be a valid C++ member 4101 // intializer: either a non-static field member or a base class. 4102 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4103 public: 4104 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4105 : ClassDecl(ClassDecl) {} 4106 4107 bool ValidateCandidate(const TypoCorrection &candidate) override { 4108 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4109 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4110 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4111 return isa<TypeDecl>(ND); 4112 } 4113 return false; 4114 } 4115 4116 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4117 return std::make_unique<MemInitializerValidatorCCC>(*this); 4118 } 4119 4120 private: 4121 CXXRecordDecl *ClassDecl; 4122 }; 4123 4124 } 4125 4126 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4127 CXXScopeSpec &SS, 4128 ParsedType TemplateTypeTy, 4129 IdentifierInfo *MemberOrBase) { 4130 if (SS.getScopeRep() || TemplateTypeTy) 4131 return nullptr; 4132 for (auto *D : ClassDecl->lookup(MemberOrBase)) 4133 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) 4134 return cast<ValueDecl>(D); 4135 return nullptr; 4136 } 4137 4138 /// Handle a C++ member initializer. 4139 MemInitResult 4140 Sema::BuildMemInitializer(Decl *ConstructorD, 4141 Scope *S, 4142 CXXScopeSpec &SS, 4143 IdentifierInfo *MemberOrBase, 4144 ParsedType TemplateTypeTy, 4145 const DeclSpec &DS, 4146 SourceLocation IdLoc, 4147 Expr *Init, 4148 SourceLocation EllipsisLoc) { 4149 ExprResult Res = CorrectDelayedTyposInExpr(Init); 4150 if (!Res.isUsable()) 4151 return true; 4152 Init = Res.get(); 4153 4154 if (!ConstructorD) 4155 return true; 4156 4157 AdjustDeclIfTemplate(ConstructorD); 4158 4159 CXXConstructorDecl *Constructor 4160 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4161 if (!Constructor) { 4162 // The user wrote a constructor initializer on a function that is 4163 // not a C++ constructor. Ignore the error for now, because we may 4164 // have more member initializers coming; we'll diagnose it just 4165 // once in ActOnMemInitializers. 4166 return true; 4167 } 4168 4169 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4170 4171 // C++ [class.base.init]p2: 4172 // Names in a mem-initializer-id are looked up in the scope of the 4173 // constructor's class and, if not found in that scope, are looked 4174 // up in the scope containing the constructor's definition. 4175 // [Note: if the constructor's class contains a member with the 4176 // same name as a direct or virtual base class of the class, a 4177 // mem-initializer-id naming the member or base class and composed 4178 // of a single identifier refers to the class member. A 4179 // mem-initializer-id for the hidden base class may be specified 4180 // using a qualified name. ] 4181 4182 // Look for a member, first. 4183 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4184 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4185 if (EllipsisLoc.isValid()) 4186 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4187 << MemberOrBase 4188 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4189 4190 return BuildMemberInitializer(Member, Init, IdLoc); 4191 } 4192 // It didn't name a member, so see if it names a class. 4193 QualType BaseType; 4194 TypeSourceInfo *TInfo = nullptr; 4195 4196 if (TemplateTypeTy) { 4197 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4198 if (BaseType.isNull()) 4199 return true; 4200 } else if (DS.getTypeSpecType() == TST_decltype) { 4201 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4202 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4203 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4204 return true; 4205 } else { 4206 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4207 LookupParsedName(R, S, &SS); 4208 4209 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4210 if (!TyD) { 4211 if (R.isAmbiguous()) return true; 4212 4213 // We don't want access-control diagnostics here. 4214 R.suppressDiagnostics(); 4215 4216 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4217 bool NotUnknownSpecialization = false; 4218 DeclContext *DC = computeDeclContext(SS, false); 4219 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4220 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4221 4222 if (!NotUnknownSpecialization) { 4223 // When the scope specifier can refer to a member of an unknown 4224 // specialization, we take it as a type name. 4225 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4226 SS.getWithLocInContext(Context), 4227 *MemberOrBase, IdLoc); 4228 if (BaseType.isNull()) 4229 return true; 4230 4231 TInfo = Context.CreateTypeSourceInfo(BaseType); 4232 DependentNameTypeLoc TL = 4233 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4234 if (!TL.isNull()) { 4235 TL.setNameLoc(IdLoc); 4236 TL.setElaboratedKeywordLoc(SourceLocation()); 4237 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4238 } 4239 4240 R.clear(); 4241 R.setLookupName(MemberOrBase); 4242 } 4243 } 4244 4245 // If no results were found, try to correct typos. 4246 TypoCorrection Corr; 4247 MemInitializerValidatorCCC CCC(ClassDecl); 4248 if (R.empty() && BaseType.isNull() && 4249 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4250 CCC, CTK_ErrorRecovery, ClassDecl))) { 4251 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4252 // We have found a non-static data member with a similar 4253 // name to what was typed; complain and initialize that 4254 // member. 4255 diagnoseTypo(Corr, 4256 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4257 << MemberOrBase << true); 4258 return BuildMemberInitializer(Member, Init, IdLoc); 4259 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4260 const CXXBaseSpecifier *DirectBaseSpec; 4261 const CXXBaseSpecifier *VirtualBaseSpec; 4262 if (FindBaseInitializer(*this, ClassDecl, 4263 Context.getTypeDeclType(Type), 4264 DirectBaseSpec, VirtualBaseSpec)) { 4265 // We have found a direct or virtual base class with a 4266 // similar name to what was typed; complain and initialize 4267 // that base class. 4268 diagnoseTypo(Corr, 4269 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4270 << MemberOrBase << false, 4271 PDiag() /*Suppress note, we provide our own.*/); 4272 4273 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4274 : VirtualBaseSpec; 4275 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4276 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4277 4278 TyD = Type; 4279 } 4280 } 4281 } 4282 4283 if (!TyD && BaseType.isNull()) { 4284 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4285 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4286 return true; 4287 } 4288 } 4289 4290 if (BaseType.isNull()) { 4291 BaseType = Context.getTypeDeclType(TyD); 4292 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4293 if (SS.isSet()) { 4294 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4295 BaseType); 4296 TInfo = Context.CreateTypeSourceInfo(BaseType); 4297 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4298 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4299 TL.setElaboratedKeywordLoc(SourceLocation()); 4300 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4301 } 4302 } 4303 } 4304 4305 if (!TInfo) 4306 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4307 4308 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4309 } 4310 4311 MemInitResult 4312 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4313 SourceLocation IdLoc) { 4314 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4315 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4316 assert((DirectMember || IndirectMember) && 4317 "Member must be a FieldDecl or IndirectFieldDecl"); 4318 4319 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4320 return true; 4321 4322 if (Member->isInvalidDecl()) 4323 return true; 4324 4325 MultiExprArg Args; 4326 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4327 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4328 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4329 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4330 } else { 4331 // Template instantiation doesn't reconstruct ParenListExprs for us. 4332 Args = Init; 4333 } 4334 4335 SourceRange InitRange = Init->getSourceRange(); 4336 4337 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4338 // Can't check initialization for a member of dependent type or when 4339 // any of the arguments are type-dependent expressions. 4340 DiscardCleanupsInEvaluationContext(); 4341 } else { 4342 bool InitList = false; 4343 if (isa<InitListExpr>(Init)) { 4344 InitList = true; 4345 Args = Init; 4346 } 4347 4348 // Initialize the member. 4349 InitializedEntity MemberEntity = 4350 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4351 : InitializedEntity::InitializeMember(IndirectMember, 4352 nullptr); 4353 InitializationKind Kind = 4354 InitList ? InitializationKind::CreateDirectList( 4355 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4356 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4357 InitRange.getEnd()); 4358 4359 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4360 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4361 nullptr); 4362 if (MemberInit.isInvalid()) 4363 return true; 4364 4365 // C++11 [class.base.init]p7: 4366 // The initialization of each base and member constitutes a 4367 // full-expression. 4368 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4369 /*DiscardedValue*/ false); 4370 if (MemberInit.isInvalid()) 4371 return true; 4372 4373 Init = MemberInit.get(); 4374 } 4375 4376 if (DirectMember) { 4377 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4378 InitRange.getBegin(), Init, 4379 InitRange.getEnd()); 4380 } else { 4381 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4382 InitRange.getBegin(), Init, 4383 InitRange.getEnd()); 4384 } 4385 } 4386 4387 MemInitResult 4388 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4389 CXXRecordDecl *ClassDecl) { 4390 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4391 if (!LangOpts.CPlusPlus11) 4392 return Diag(NameLoc, diag::err_delegating_ctor) 4393 << TInfo->getTypeLoc().getLocalSourceRange(); 4394 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4395 4396 bool InitList = true; 4397 MultiExprArg Args = Init; 4398 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4399 InitList = false; 4400 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4401 } 4402 4403 SourceRange InitRange = Init->getSourceRange(); 4404 // Initialize the object. 4405 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4406 QualType(ClassDecl->getTypeForDecl(), 0)); 4407 InitializationKind Kind = 4408 InitList ? InitializationKind::CreateDirectList( 4409 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4410 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4411 InitRange.getEnd()); 4412 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4413 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4414 Args, nullptr); 4415 if (DelegationInit.isInvalid()) 4416 return true; 4417 4418 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4419 "Delegating constructor with no target?"); 4420 4421 // C++11 [class.base.init]p7: 4422 // The initialization of each base and member constitutes a 4423 // full-expression. 4424 DelegationInit = ActOnFinishFullExpr( 4425 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4426 if (DelegationInit.isInvalid()) 4427 return true; 4428 4429 // If we are in a dependent context, template instantiation will 4430 // perform this type-checking again. Just save the arguments that we 4431 // received in a ParenListExpr. 4432 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4433 // of the information that we have about the base 4434 // initializer. However, deconstructing the ASTs is a dicey process, 4435 // and this approach is far more likely to get the corner cases right. 4436 if (CurContext->isDependentContext()) 4437 DelegationInit = Init; 4438 4439 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4440 DelegationInit.getAs<Expr>(), 4441 InitRange.getEnd()); 4442 } 4443 4444 MemInitResult 4445 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4446 Expr *Init, CXXRecordDecl *ClassDecl, 4447 SourceLocation EllipsisLoc) { 4448 SourceLocation BaseLoc 4449 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4450 4451 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4452 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4453 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4454 4455 // C++ [class.base.init]p2: 4456 // [...] Unless the mem-initializer-id names a nonstatic data 4457 // member of the constructor's class or a direct or virtual base 4458 // of that class, the mem-initializer is ill-formed. A 4459 // mem-initializer-list can initialize a base class using any 4460 // name that denotes that base class type. 4461 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4462 4463 SourceRange InitRange = Init->getSourceRange(); 4464 if (EllipsisLoc.isValid()) { 4465 // This is a pack expansion. 4466 if (!BaseType->containsUnexpandedParameterPack()) { 4467 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4468 << SourceRange(BaseLoc, InitRange.getEnd()); 4469 4470 EllipsisLoc = SourceLocation(); 4471 } 4472 } else { 4473 // Check for any unexpanded parameter packs. 4474 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4475 return true; 4476 4477 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4478 return true; 4479 } 4480 4481 // Check for direct and virtual base classes. 4482 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4483 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4484 if (!Dependent) { 4485 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4486 BaseType)) 4487 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4488 4489 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4490 VirtualBaseSpec); 4491 4492 // C++ [base.class.init]p2: 4493 // Unless the mem-initializer-id names a nonstatic data member of the 4494 // constructor's class or a direct or virtual base of that class, the 4495 // mem-initializer is ill-formed. 4496 if (!DirectBaseSpec && !VirtualBaseSpec) { 4497 // If the class has any dependent bases, then it's possible that 4498 // one of those types will resolve to the same type as 4499 // BaseType. Therefore, just treat this as a dependent base 4500 // class initialization. FIXME: Should we try to check the 4501 // initialization anyway? It seems odd. 4502 if (ClassDecl->hasAnyDependentBases()) 4503 Dependent = true; 4504 else 4505 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4506 << BaseType << Context.getTypeDeclType(ClassDecl) 4507 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4508 } 4509 } 4510 4511 if (Dependent) { 4512 DiscardCleanupsInEvaluationContext(); 4513 4514 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4515 /*IsVirtual=*/false, 4516 InitRange.getBegin(), Init, 4517 InitRange.getEnd(), EllipsisLoc); 4518 } 4519 4520 // C++ [base.class.init]p2: 4521 // If a mem-initializer-id is ambiguous because it designates both 4522 // a direct non-virtual base class and an inherited virtual base 4523 // class, the mem-initializer is ill-formed. 4524 if (DirectBaseSpec && VirtualBaseSpec) 4525 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4526 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4527 4528 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4529 if (!BaseSpec) 4530 BaseSpec = VirtualBaseSpec; 4531 4532 // Initialize the base. 4533 bool InitList = true; 4534 MultiExprArg Args = Init; 4535 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4536 InitList = false; 4537 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4538 } 4539 4540 InitializedEntity BaseEntity = 4541 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4542 InitializationKind Kind = 4543 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4544 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4545 InitRange.getEnd()); 4546 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4547 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4548 if (BaseInit.isInvalid()) 4549 return true; 4550 4551 // C++11 [class.base.init]p7: 4552 // The initialization of each base and member constitutes a 4553 // full-expression. 4554 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4555 /*DiscardedValue*/ false); 4556 if (BaseInit.isInvalid()) 4557 return true; 4558 4559 // If we are in a dependent context, template instantiation will 4560 // perform this type-checking again. Just save the arguments that we 4561 // received in a ParenListExpr. 4562 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4563 // of the information that we have about the base 4564 // initializer. However, deconstructing the ASTs is a dicey process, 4565 // and this approach is far more likely to get the corner cases right. 4566 if (CurContext->isDependentContext()) 4567 BaseInit = Init; 4568 4569 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4570 BaseSpec->isVirtual(), 4571 InitRange.getBegin(), 4572 BaseInit.getAs<Expr>(), 4573 InitRange.getEnd(), EllipsisLoc); 4574 } 4575 4576 // Create a static_cast\<T&&>(expr). 4577 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4578 if (T.isNull()) T = E->getType(); 4579 QualType TargetType = SemaRef.BuildReferenceType( 4580 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4581 SourceLocation ExprLoc = E->getBeginLoc(); 4582 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4583 TargetType, ExprLoc); 4584 4585 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4586 SourceRange(ExprLoc, ExprLoc), 4587 E->getSourceRange()).get(); 4588 } 4589 4590 /// ImplicitInitializerKind - How an implicit base or member initializer should 4591 /// initialize its base or member. 4592 enum ImplicitInitializerKind { 4593 IIK_Default, 4594 IIK_Copy, 4595 IIK_Move, 4596 IIK_Inherit 4597 }; 4598 4599 static bool 4600 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4601 ImplicitInitializerKind ImplicitInitKind, 4602 CXXBaseSpecifier *BaseSpec, 4603 bool IsInheritedVirtualBase, 4604 CXXCtorInitializer *&CXXBaseInit) { 4605 InitializedEntity InitEntity 4606 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4607 IsInheritedVirtualBase); 4608 4609 ExprResult BaseInit; 4610 4611 switch (ImplicitInitKind) { 4612 case IIK_Inherit: 4613 case IIK_Default: { 4614 InitializationKind InitKind 4615 = InitializationKind::CreateDefault(Constructor->getLocation()); 4616 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4617 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4618 break; 4619 } 4620 4621 case IIK_Move: 4622 case IIK_Copy: { 4623 bool Moving = ImplicitInitKind == IIK_Move; 4624 ParmVarDecl *Param = Constructor->getParamDecl(0); 4625 QualType ParamType = Param->getType().getNonReferenceType(); 4626 4627 Expr *CopyCtorArg = 4628 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4629 SourceLocation(), Param, false, 4630 Constructor->getLocation(), ParamType, 4631 VK_LValue, nullptr); 4632 4633 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4634 4635 // Cast to the base class to avoid ambiguities. 4636 QualType ArgTy = 4637 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4638 ParamType.getQualifiers()); 4639 4640 if (Moving) { 4641 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4642 } 4643 4644 CXXCastPath BasePath; 4645 BasePath.push_back(BaseSpec); 4646 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4647 CK_UncheckedDerivedToBase, 4648 Moving ? VK_XValue : VK_LValue, 4649 &BasePath).get(); 4650 4651 InitializationKind InitKind 4652 = InitializationKind::CreateDirect(Constructor->getLocation(), 4653 SourceLocation(), SourceLocation()); 4654 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4655 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4656 break; 4657 } 4658 } 4659 4660 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4661 if (BaseInit.isInvalid()) 4662 return true; 4663 4664 CXXBaseInit = 4665 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4666 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4667 SourceLocation()), 4668 BaseSpec->isVirtual(), 4669 SourceLocation(), 4670 BaseInit.getAs<Expr>(), 4671 SourceLocation(), 4672 SourceLocation()); 4673 4674 return false; 4675 } 4676 4677 static bool RefersToRValueRef(Expr *MemRef) { 4678 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4679 return Referenced->getType()->isRValueReferenceType(); 4680 } 4681 4682 static bool 4683 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4684 ImplicitInitializerKind ImplicitInitKind, 4685 FieldDecl *Field, IndirectFieldDecl *Indirect, 4686 CXXCtorInitializer *&CXXMemberInit) { 4687 if (Field->isInvalidDecl()) 4688 return true; 4689 4690 SourceLocation Loc = Constructor->getLocation(); 4691 4692 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4693 bool Moving = ImplicitInitKind == IIK_Move; 4694 ParmVarDecl *Param = Constructor->getParamDecl(0); 4695 QualType ParamType = Param->getType().getNonReferenceType(); 4696 4697 // Suppress copying zero-width bitfields. 4698 if (Field->isZeroLengthBitField(SemaRef.Context)) 4699 return false; 4700 4701 Expr *MemberExprBase = 4702 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4703 SourceLocation(), Param, false, 4704 Loc, ParamType, VK_LValue, nullptr); 4705 4706 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4707 4708 if (Moving) { 4709 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4710 } 4711 4712 // Build a reference to this field within the parameter. 4713 CXXScopeSpec SS; 4714 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4715 Sema::LookupMemberName); 4716 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4717 : cast<ValueDecl>(Field), AS_public); 4718 MemberLookup.resolveKind(); 4719 ExprResult CtorArg 4720 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4721 ParamType, Loc, 4722 /*IsArrow=*/false, 4723 SS, 4724 /*TemplateKWLoc=*/SourceLocation(), 4725 /*FirstQualifierInScope=*/nullptr, 4726 MemberLookup, 4727 /*TemplateArgs=*/nullptr, 4728 /*S*/nullptr); 4729 if (CtorArg.isInvalid()) 4730 return true; 4731 4732 // C++11 [class.copy]p15: 4733 // - if a member m has rvalue reference type T&&, it is direct-initialized 4734 // with static_cast<T&&>(x.m); 4735 if (RefersToRValueRef(CtorArg.get())) { 4736 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4737 } 4738 4739 InitializedEntity Entity = 4740 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4741 /*Implicit*/ true) 4742 : InitializedEntity::InitializeMember(Field, nullptr, 4743 /*Implicit*/ true); 4744 4745 // Direct-initialize to use the copy constructor. 4746 InitializationKind InitKind = 4747 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4748 4749 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4750 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4751 ExprResult MemberInit = 4752 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4753 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4754 if (MemberInit.isInvalid()) 4755 return true; 4756 4757 if (Indirect) 4758 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4759 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4760 else 4761 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4762 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4763 return false; 4764 } 4765 4766 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4767 "Unhandled implicit init kind!"); 4768 4769 QualType FieldBaseElementType = 4770 SemaRef.Context.getBaseElementType(Field->getType()); 4771 4772 if (FieldBaseElementType->isRecordType()) { 4773 InitializedEntity InitEntity = 4774 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4775 /*Implicit*/ true) 4776 : InitializedEntity::InitializeMember(Field, nullptr, 4777 /*Implicit*/ true); 4778 InitializationKind InitKind = 4779 InitializationKind::CreateDefault(Loc); 4780 4781 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4782 ExprResult MemberInit = 4783 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4784 4785 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4786 if (MemberInit.isInvalid()) 4787 return true; 4788 4789 if (Indirect) 4790 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4791 Indirect, Loc, 4792 Loc, 4793 MemberInit.get(), 4794 Loc); 4795 else 4796 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4797 Field, Loc, Loc, 4798 MemberInit.get(), 4799 Loc); 4800 return false; 4801 } 4802 4803 if (!Field->getParent()->isUnion()) { 4804 if (FieldBaseElementType->isReferenceType()) { 4805 SemaRef.Diag(Constructor->getLocation(), 4806 diag::err_uninitialized_member_in_ctor) 4807 << (int)Constructor->isImplicit() 4808 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4809 << 0 << Field->getDeclName(); 4810 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4811 return true; 4812 } 4813 4814 if (FieldBaseElementType.isConstQualified()) { 4815 SemaRef.Diag(Constructor->getLocation(), 4816 diag::err_uninitialized_member_in_ctor) 4817 << (int)Constructor->isImplicit() 4818 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4819 << 1 << Field->getDeclName(); 4820 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4821 return true; 4822 } 4823 } 4824 4825 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4826 // ARC and Weak: 4827 // Default-initialize Objective-C pointers to NULL. 4828 CXXMemberInit 4829 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4830 Loc, Loc, 4831 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4832 Loc); 4833 return false; 4834 } 4835 4836 // Nothing to initialize. 4837 CXXMemberInit = nullptr; 4838 return false; 4839 } 4840 4841 namespace { 4842 struct BaseAndFieldInfo { 4843 Sema &S; 4844 CXXConstructorDecl *Ctor; 4845 bool AnyErrorsInInits; 4846 ImplicitInitializerKind IIK; 4847 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4848 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4849 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4850 4851 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4852 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4853 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4854 if (Ctor->getInheritedConstructor()) 4855 IIK = IIK_Inherit; 4856 else if (Generated && Ctor->isCopyConstructor()) 4857 IIK = IIK_Copy; 4858 else if (Generated && Ctor->isMoveConstructor()) 4859 IIK = IIK_Move; 4860 else 4861 IIK = IIK_Default; 4862 } 4863 4864 bool isImplicitCopyOrMove() const { 4865 switch (IIK) { 4866 case IIK_Copy: 4867 case IIK_Move: 4868 return true; 4869 4870 case IIK_Default: 4871 case IIK_Inherit: 4872 return false; 4873 } 4874 4875 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4876 } 4877 4878 bool addFieldInitializer(CXXCtorInitializer *Init) { 4879 AllToInit.push_back(Init); 4880 4881 // Check whether this initializer makes the field "used". 4882 if (Init->getInit()->HasSideEffects(S.Context)) 4883 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4884 4885 return false; 4886 } 4887 4888 bool isInactiveUnionMember(FieldDecl *Field) { 4889 RecordDecl *Record = Field->getParent(); 4890 if (!Record->isUnion()) 4891 return false; 4892 4893 if (FieldDecl *Active = 4894 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4895 return Active != Field->getCanonicalDecl(); 4896 4897 // In an implicit copy or move constructor, ignore any in-class initializer. 4898 if (isImplicitCopyOrMove()) 4899 return true; 4900 4901 // If there's no explicit initialization, the field is active only if it 4902 // has an in-class initializer... 4903 if (Field->hasInClassInitializer()) 4904 return false; 4905 // ... or it's an anonymous struct or union whose class has an in-class 4906 // initializer. 4907 if (!Field->isAnonymousStructOrUnion()) 4908 return true; 4909 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4910 return !FieldRD->hasInClassInitializer(); 4911 } 4912 4913 /// Determine whether the given field is, or is within, a union member 4914 /// that is inactive (because there was an initializer given for a different 4915 /// member of the union, or because the union was not initialized at all). 4916 bool isWithinInactiveUnionMember(FieldDecl *Field, 4917 IndirectFieldDecl *Indirect) { 4918 if (!Indirect) 4919 return isInactiveUnionMember(Field); 4920 4921 for (auto *C : Indirect->chain()) { 4922 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4923 if (Field && isInactiveUnionMember(Field)) 4924 return true; 4925 } 4926 return false; 4927 } 4928 }; 4929 } 4930 4931 /// Determine whether the given type is an incomplete or zero-lenfgth 4932 /// array type. 4933 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4934 if (T->isIncompleteArrayType()) 4935 return true; 4936 4937 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4938 if (!ArrayT->getSize()) 4939 return true; 4940 4941 T = ArrayT->getElementType(); 4942 } 4943 4944 return false; 4945 } 4946 4947 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4948 FieldDecl *Field, 4949 IndirectFieldDecl *Indirect = nullptr) { 4950 if (Field->isInvalidDecl()) 4951 return false; 4952 4953 // Overwhelmingly common case: we have a direct initializer for this field. 4954 if (CXXCtorInitializer *Init = 4955 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4956 return Info.addFieldInitializer(Init); 4957 4958 // C++11 [class.base.init]p8: 4959 // if the entity is a non-static data member that has a 4960 // brace-or-equal-initializer and either 4961 // -- the constructor's class is a union and no other variant member of that 4962 // union is designated by a mem-initializer-id or 4963 // -- the constructor's class is not a union, and, if the entity is a member 4964 // of an anonymous union, no other member of that union is designated by 4965 // a mem-initializer-id, 4966 // the entity is initialized as specified in [dcl.init]. 4967 // 4968 // We also apply the same rules to handle anonymous structs within anonymous 4969 // unions. 4970 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4971 return false; 4972 4973 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4974 ExprResult DIE = 4975 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4976 if (DIE.isInvalid()) 4977 return true; 4978 4979 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4980 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4981 4982 CXXCtorInitializer *Init; 4983 if (Indirect) 4984 Init = new (SemaRef.Context) 4985 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4986 SourceLocation(), DIE.get(), SourceLocation()); 4987 else 4988 Init = new (SemaRef.Context) 4989 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4990 SourceLocation(), DIE.get(), SourceLocation()); 4991 return Info.addFieldInitializer(Init); 4992 } 4993 4994 // Don't initialize incomplete or zero-length arrays. 4995 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4996 return false; 4997 4998 // Don't try to build an implicit initializer if there were semantic 4999 // errors in any of the initializers (and therefore we might be 5000 // missing some that the user actually wrote). 5001 if (Info.AnyErrorsInInits) 5002 return false; 5003 5004 CXXCtorInitializer *Init = nullptr; 5005 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 5006 Indirect, Init)) 5007 return true; 5008 5009 if (!Init) 5010 return false; 5011 5012 return Info.addFieldInitializer(Init); 5013 } 5014 5015 bool 5016 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 5017 CXXCtorInitializer *Initializer) { 5018 assert(Initializer->isDelegatingInitializer()); 5019 Constructor->setNumCtorInitializers(1); 5020 CXXCtorInitializer **initializer = 5021 new (Context) CXXCtorInitializer*[1]; 5022 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 5023 Constructor->setCtorInitializers(initializer); 5024 5025 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 5026 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 5027 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 5028 } 5029 5030 DelegatingCtorDecls.push_back(Constructor); 5031 5032 DiagnoseUninitializedFields(*this, Constructor); 5033 5034 return false; 5035 } 5036 5037 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 5038 ArrayRef<CXXCtorInitializer *> Initializers) { 5039 if (Constructor->isDependentContext()) { 5040 // Just store the initializers as written, they will be checked during 5041 // instantiation. 5042 if (!Initializers.empty()) { 5043 Constructor->setNumCtorInitializers(Initializers.size()); 5044 CXXCtorInitializer **baseOrMemberInitializers = 5045 new (Context) CXXCtorInitializer*[Initializers.size()]; 5046 memcpy(baseOrMemberInitializers, Initializers.data(), 5047 Initializers.size() * sizeof(CXXCtorInitializer*)); 5048 Constructor->setCtorInitializers(baseOrMemberInitializers); 5049 } 5050 5051 // Let template instantiation know whether we had errors. 5052 if (AnyErrors) 5053 Constructor->setInvalidDecl(); 5054 5055 return false; 5056 } 5057 5058 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 5059 5060 // We need to build the initializer AST according to order of construction 5061 // and not what user specified in the Initializers list. 5062 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 5063 if (!ClassDecl) 5064 return true; 5065 5066 bool HadError = false; 5067 5068 for (unsigned i = 0; i < Initializers.size(); i++) { 5069 CXXCtorInitializer *Member = Initializers[i]; 5070 5071 if (Member->isBaseInitializer()) 5072 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5073 else { 5074 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5075 5076 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5077 for (auto *C : F->chain()) { 5078 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5079 if (FD && FD->getParent()->isUnion()) 5080 Info.ActiveUnionMember.insert(std::make_pair( 5081 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5082 } 5083 } else if (FieldDecl *FD = Member->getMember()) { 5084 if (FD->getParent()->isUnion()) 5085 Info.ActiveUnionMember.insert(std::make_pair( 5086 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5087 } 5088 } 5089 } 5090 5091 // Keep track of the direct virtual bases. 5092 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5093 for (auto &I : ClassDecl->bases()) { 5094 if (I.isVirtual()) 5095 DirectVBases.insert(&I); 5096 } 5097 5098 // Push virtual bases before others. 5099 for (auto &VBase : ClassDecl->vbases()) { 5100 if (CXXCtorInitializer *Value 5101 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5102 // [class.base.init]p7, per DR257: 5103 // A mem-initializer where the mem-initializer-id names a virtual base 5104 // class is ignored during execution of a constructor of any class that 5105 // is not the most derived class. 5106 if (ClassDecl->isAbstract()) { 5107 // FIXME: Provide a fixit to remove the base specifier. This requires 5108 // tracking the location of the associated comma for a base specifier. 5109 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5110 << VBase.getType() << ClassDecl; 5111 DiagnoseAbstractType(ClassDecl); 5112 } 5113 5114 Info.AllToInit.push_back(Value); 5115 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5116 // [class.base.init]p8, per DR257: 5117 // If a given [...] base class is not named by a mem-initializer-id 5118 // [...] and the entity is not a virtual base class of an abstract 5119 // class, then [...] the entity is default-initialized. 5120 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5121 CXXCtorInitializer *CXXBaseInit; 5122 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5123 &VBase, IsInheritedVirtualBase, 5124 CXXBaseInit)) { 5125 HadError = true; 5126 continue; 5127 } 5128 5129 Info.AllToInit.push_back(CXXBaseInit); 5130 } 5131 } 5132 5133 // Non-virtual bases. 5134 for (auto &Base : ClassDecl->bases()) { 5135 // Virtuals are in the virtual base list and already constructed. 5136 if (Base.isVirtual()) 5137 continue; 5138 5139 if (CXXCtorInitializer *Value 5140 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5141 Info.AllToInit.push_back(Value); 5142 } else if (!AnyErrors) { 5143 CXXCtorInitializer *CXXBaseInit; 5144 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5145 &Base, /*IsInheritedVirtualBase=*/false, 5146 CXXBaseInit)) { 5147 HadError = true; 5148 continue; 5149 } 5150 5151 Info.AllToInit.push_back(CXXBaseInit); 5152 } 5153 } 5154 5155 // Fields. 5156 for (auto *Mem : ClassDecl->decls()) { 5157 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5158 // C++ [class.bit]p2: 5159 // A declaration for a bit-field that omits the identifier declares an 5160 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5161 // initialized. 5162 if (F->isUnnamedBitfield()) 5163 continue; 5164 5165 // If we're not generating the implicit copy/move constructor, then we'll 5166 // handle anonymous struct/union fields based on their individual 5167 // indirect fields. 5168 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5169 continue; 5170 5171 if (CollectFieldInitializer(*this, Info, F)) 5172 HadError = true; 5173 continue; 5174 } 5175 5176 // Beyond this point, we only consider default initialization. 5177 if (Info.isImplicitCopyOrMove()) 5178 continue; 5179 5180 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5181 if (F->getType()->isIncompleteArrayType()) { 5182 assert(ClassDecl->hasFlexibleArrayMember() && 5183 "Incomplete array type is not valid"); 5184 continue; 5185 } 5186 5187 // Initialize each field of an anonymous struct individually. 5188 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5189 HadError = true; 5190 5191 continue; 5192 } 5193 } 5194 5195 unsigned NumInitializers = Info.AllToInit.size(); 5196 if (NumInitializers > 0) { 5197 Constructor->setNumCtorInitializers(NumInitializers); 5198 CXXCtorInitializer **baseOrMemberInitializers = 5199 new (Context) CXXCtorInitializer*[NumInitializers]; 5200 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5201 NumInitializers * sizeof(CXXCtorInitializer*)); 5202 Constructor->setCtorInitializers(baseOrMemberInitializers); 5203 5204 // Constructors implicitly reference the base and member 5205 // destructors. 5206 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5207 Constructor->getParent()); 5208 } 5209 5210 return HadError; 5211 } 5212 5213 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5214 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5215 const RecordDecl *RD = RT->getDecl(); 5216 if (RD->isAnonymousStructOrUnion()) { 5217 for (auto *Field : RD->fields()) 5218 PopulateKeysForFields(Field, IdealInits); 5219 return; 5220 } 5221 } 5222 IdealInits.push_back(Field->getCanonicalDecl()); 5223 } 5224 5225 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5226 return Context.getCanonicalType(BaseType).getTypePtr(); 5227 } 5228 5229 static const void *GetKeyForMember(ASTContext &Context, 5230 CXXCtorInitializer *Member) { 5231 if (!Member->isAnyMemberInitializer()) 5232 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5233 5234 return Member->getAnyMember()->getCanonicalDecl(); 5235 } 5236 5237 static void DiagnoseBaseOrMemInitializerOrder( 5238 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5239 ArrayRef<CXXCtorInitializer *> Inits) { 5240 if (Constructor->getDeclContext()->isDependentContext()) 5241 return; 5242 5243 // Don't check initializers order unless the warning is enabled at the 5244 // location of at least one initializer. 5245 bool ShouldCheckOrder = false; 5246 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5247 CXXCtorInitializer *Init = Inits[InitIndex]; 5248 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5249 Init->getSourceLocation())) { 5250 ShouldCheckOrder = true; 5251 break; 5252 } 5253 } 5254 if (!ShouldCheckOrder) 5255 return; 5256 5257 // Build the list of bases and members in the order that they'll 5258 // actually be initialized. The explicit initializers should be in 5259 // this same order but may be missing things. 5260 SmallVector<const void*, 32> IdealInitKeys; 5261 5262 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5263 5264 // 1. Virtual bases. 5265 for (const auto &VBase : ClassDecl->vbases()) 5266 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5267 5268 // 2. Non-virtual bases. 5269 for (const auto &Base : ClassDecl->bases()) { 5270 if (Base.isVirtual()) 5271 continue; 5272 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5273 } 5274 5275 // 3. Direct fields. 5276 for (auto *Field : ClassDecl->fields()) { 5277 if (Field->isUnnamedBitfield()) 5278 continue; 5279 5280 PopulateKeysForFields(Field, IdealInitKeys); 5281 } 5282 5283 unsigned NumIdealInits = IdealInitKeys.size(); 5284 unsigned IdealIndex = 0; 5285 5286 CXXCtorInitializer *PrevInit = nullptr; 5287 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5288 CXXCtorInitializer *Init = Inits[InitIndex]; 5289 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 5290 5291 // Scan forward to try to find this initializer in the idealized 5292 // initializers list. 5293 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5294 if (InitKey == IdealInitKeys[IdealIndex]) 5295 break; 5296 5297 // If we didn't find this initializer, it must be because we 5298 // scanned past it on a previous iteration. That can only 5299 // happen if we're out of order; emit a warning. 5300 if (IdealIndex == NumIdealInits && PrevInit) { 5301 Sema::SemaDiagnosticBuilder D = 5302 SemaRef.Diag(PrevInit->getSourceLocation(), 5303 diag::warn_initializer_out_of_order); 5304 5305 if (PrevInit->isAnyMemberInitializer()) 5306 D << 0 << PrevInit->getAnyMember()->getDeclName(); 5307 else 5308 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 5309 5310 if (Init->isAnyMemberInitializer()) 5311 D << 0 << Init->getAnyMember()->getDeclName(); 5312 else 5313 D << 1 << Init->getTypeSourceInfo()->getType(); 5314 5315 // Move back to the initializer's location in the ideal list. 5316 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5317 if (InitKey == IdealInitKeys[IdealIndex]) 5318 break; 5319 5320 assert(IdealIndex < NumIdealInits && 5321 "initializer not found in initializer list"); 5322 } 5323 5324 PrevInit = Init; 5325 } 5326 } 5327 5328 namespace { 5329 bool CheckRedundantInit(Sema &S, 5330 CXXCtorInitializer *Init, 5331 CXXCtorInitializer *&PrevInit) { 5332 if (!PrevInit) { 5333 PrevInit = Init; 5334 return false; 5335 } 5336 5337 if (FieldDecl *Field = Init->getAnyMember()) 5338 S.Diag(Init->getSourceLocation(), 5339 diag::err_multiple_mem_initialization) 5340 << Field->getDeclName() 5341 << Init->getSourceRange(); 5342 else { 5343 const Type *BaseClass = Init->getBaseClass(); 5344 assert(BaseClass && "neither field nor base"); 5345 S.Diag(Init->getSourceLocation(), 5346 diag::err_multiple_base_initialization) 5347 << QualType(BaseClass, 0) 5348 << Init->getSourceRange(); 5349 } 5350 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5351 << 0 << PrevInit->getSourceRange(); 5352 5353 return true; 5354 } 5355 5356 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5357 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5358 5359 bool CheckRedundantUnionInit(Sema &S, 5360 CXXCtorInitializer *Init, 5361 RedundantUnionMap &Unions) { 5362 FieldDecl *Field = Init->getAnyMember(); 5363 RecordDecl *Parent = Field->getParent(); 5364 NamedDecl *Child = Field; 5365 5366 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5367 if (Parent->isUnion()) { 5368 UnionEntry &En = Unions[Parent]; 5369 if (En.first && En.first != Child) { 5370 S.Diag(Init->getSourceLocation(), 5371 diag::err_multiple_mem_union_initialization) 5372 << Field->getDeclName() 5373 << Init->getSourceRange(); 5374 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5375 << 0 << En.second->getSourceRange(); 5376 return true; 5377 } 5378 if (!En.first) { 5379 En.first = Child; 5380 En.second = Init; 5381 } 5382 if (!Parent->isAnonymousStructOrUnion()) 5383 return false; 5384 } 5385 5386 Child = Parent; 5387 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5388 } 5389 5390 return false; 5391 } 5392 } 5393 5394 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5395 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5396 SourceLocation ColonLoc, 5397 ArrayRef<CXXCtorInitializer*> MemInits, 5398 bool AnyErrors) { 5399 if (!ConstructorDecl) 5400 return; 5401 5402 AdjustDeclIfTemplate(ConstructorDecl); 5403 5404 CXXConstructorDecl *Constructor 5405 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5406 5407 if (!Constructor) { 5408 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5409 return; 5410 } 5411 5412 // Mapping for the duplicate initializers check. 5413 // For member initializers, this is keyed with a FieldDecl*. 5414 // For base initializers, this is keyed with a Type*. 5415 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5416 5417 // Mapping for the inconsistent anonymous-union initializers check. 5418 RedundantUnionMap MemberUnions; 5419 5420 bool HadError = false; 5421 for (unsigned i = 0; i < MemInits.size(); i++) { 5422 CXXCtorInitializer *Init = MemInits[i]; 5423 5424 // Set the source order index. 5425 Init->setSourceOrder(i); 5426 5427 if (Init->isAnyMemberInitializer()) { 5428 const void *Key = GetKeyForMember(Context, Init); 5429 if (CheckRedundantInit(*this, Init, Members[Key]) || 5430 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5431 HadError = true; 5432 } else if (Init->isBaseInitializer()) { 5433 const void *Key = GetKeyForMember(Context, Init); 5434 if (CheckRedundantInit(*this, Init, Members[Key])) 5435 HadError = true; 5436 } else { 5437 assert(Init->isDelegatingInitializer()); 5438 // This must be the only initializer 5439 if (MemInits.size() != 1) { 5440 Diag(Init->getSourceLocation(), 5441 diag::err_delegating_initializer_alone) 5442 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5443 // We will treat this as being the only initializer. 5444 } 5445 SetDelegatingInitializer(Constructor, MemInits[i]); 5446 // Return immediately as the initializer is set. 5447 return; 5448 } 5449 } 5450 5451 if (HadError) 5452 return; 5453 5454 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5455 5456 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5457 5458 DiagnoseUninitializedFields(*this, Constructor); 5459 } 5460 5461 void 5462 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5463 CXXRecordDecl *ClassDecl) { 5464 // Ignore dependent contexts. Also ignore unions, since their members never 5465 // have destructors implicitly called. 5466 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5467 return; 5468 5469 // FIXME: all the access-control diagnostics are positioned on the 5470 // field/base declaration. That's probably good; that said, the 5471 // user might reasonably want to know why the destructor is being 5472 // emitted, and we currently don't say. 5473 5474 // Non-static data members. 5475 for (auto *Field : ClassDecl->fields()) { 5476 if (Field->isInvalidDecl()) 5477 continue; 5478 5479 // Don't destroy incomplete or zero-length arrays. 5480 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5481 continue; 5482 5483 QualType FieldType = Context.getBaseElementType(Field->getType()); 5484 5485 const RecordType* RT = FieldType->getAs<RecordType>(); 5486 if (!RT) 5487 continue; 5488 5489 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5490 if (FieldClassDecl->isInvalidDecl()) 5491 continue; 5492 if (FieldClassDecl->hasIrrelevantDestructor()) 5493 continue; 5494 // The destructor for an implicit anonymous union member is never invoked. 5495 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5496 continue; 5497 5498 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5499 assert(Dtor && "No dtor found for FieldClassDecl!"); 5500 CheckDestructorAccess(Field->getLocation(), Dtor, 5501 PDiag(diag::err_access_dtor_field) 5502 << Field->getDeclName() 5503 << FieldType); 5504 5505 MarkFunctionReferenced(Location, Dtor); 5506 DiagnoseUseOfDecl(Dtor, Location); 5507 } 5508 5509 // We only potentially invoke the destructors of potentially constructed 5510 // subobjects. 5511 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5512 5513 // If the destructor exists and has already been marked used in the MS ABI, 5514 // then virtual base destructors have already been checked and marked used. 5515 // Skip checking them again to avoid duplicate diagnostics. 5516 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5517 CXXDestructorDecl *Dtor = ClassDecl->getDestructor(); 5518 if (Dtor && Dtor->isUsed()) 5519 VisitVirtualBases = false; 5520 } 5521 5522 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5523 5524 // Bases. 5525 for (const auto &Base : ClassDecl->bases()) { 5526 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5527 if (!RT) 5528 continue; 5529 5530 // Remember direct virtual bases. 5531 if (Base.isVirtual()) { 5532 if (!VisitVirtualBases) 5533 continue; 5534 DirectVirtualBases.insert(RT); 5535 } 5536 5537 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5538 // If our base class is invalid, we probably can't get its dtor anyway. 5539 if (BaseClassDecl->isInvalidDecl()) 5540 continue; 5541 if (BaseClassDecl->hasIrrelevantDestructor()) 5542 continue; 5543 5544 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5545 assert(Dtor && "No dtor found for BaseClassDecl!"); 5546 5547 // FIXME: caret should be on the start of the class name 5548 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5549 PDiag(diag::err_access_dtor_base) 5550 << Base.getType() << Base.getSourceRange(), 5551 Context.getTypeDeclType(ClassDecl)); 5552 5553 MarkFunctionReferenced(Location, Dtor); 5554 DiagnoseUseOfDecl(Dtor, Location); 5555 } 5556 5557 if (VisitVirtualBases) 5558 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl, 5559 &DirectVirtualBases); 5560 } 5561 5562 void Sema::MarkVirtualBaseDestructorsReferenced( 5563 SourceLocation Location, CXXRecordDecl *ClassDecl, 5564 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) { 5565 // Virtual bases. 5566 for (const auto &VBase : ClassDecl->vbases()) { 5567 // Bases are always records in a well-formed non-dependent class. 5568 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5569 5570 // Ignore already visited direct virtual bases. 5571 if (DirectVirtualBases && DirectVirtualBases->count(RT)) 5572 continue; 5573 5574 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5575 // If our base class is invalid, we probably can't get its dtor anyway. 5576 if (BaseClassDecl->isInvalidDecl()) 5577 continue; 5578 if (BaseClassDecl->hasIrrelevantDestructor()) 5579 continue; 5580 5581 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5582 assert(Dtor && "No dtor found for BaseClassDecl!"); 5583 if (CheckDestructorAccess( 5584 ClassDecl->getLocation(), Dtor, 5585 PDiag(diag::err_access_dtor_vbase) 5586 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5587 Context.getTypeDeclType(ClassDecl)) == 5588 AR_accessible) { 5589 CheckDerivedToBaseConversion( 5590 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5591 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5592 SourceRange(), DeclarationName(), nullptr); 5593 } 5594 5595 MarkFunctionReferenced(Location, Dtor); 5596 DiagnoseUseOfDecl(Dtor, Location); 5597 } 5598 } 5599 5600 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5601 if (!CDtorDecl) 5602 return; 5603 5604 if (CXXConstructorDecl *Constructor 5605 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5606 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5607 DiagnoseUninitializedFields(*this, Constructor); 5608 } 5609 } 5610 5611 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5612 if (!getLangOpts().CPlusPlus) 5613 return false; 5614 5615 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5616 if (!RD) 5617 return false; 5618 5619 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5620 // class template specialization here, but doing so breaks a lot of code. 5621 5622 // We can't answer whether something is abstract until it has a 5623 // definition. If it's currently being defined, we'll walk back 5624 // over all the declarations when we have a full definition. 5625 const CXXRecordDecl *Def = RD->getDefinition(); 5626 if (!Def || Def->isBeingDefined()) 5627 return false; 5628 5629 return RD->isAbstract(); 5630 } 5631 5632 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5633 TypeDiagnoser &Diagnoser) { 5634 if (!isAbstractType(Loc, T)) 5635 return false; 5636 5637 T = Context.getBaseElementType(T); 5638 Diagnoser.diagnose(*this, Loc, T); 5639 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5640 return true; 5641 } 5642 5643 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5644 // Check if we've already emitted the list of pure virtual functions 5645 // for this class. 5646 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5647 return; 5648 5649 // If the diagnostic is suppressed, don't emit the notes. We're only 5650 // going to emit them once, so try to attach them to a diagnostic we're 5651 // actually going to show. 5652 if (Diags.isLastDiagnosticIgnored()) 5653 return; 5654 5655 CXXFinalOverriderMap FinalOverriders; 5656 RD->getFinalOverriders(FinalOverriders); 5657 5658 // Keep a set of seen pure methods so we won't diagnose the same method 5659 // more than once. 5660 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5661 5662 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5663 MEnd = FinalOverriders.end(); 5664 M != MEnd; 5665 ++M) { 5666 for (OverridingMethods::iterator SO = M->second.begin(), 5667 SOEnd = M->second.end(); 5668 SO != SOEnd; ++SO) { 5669 // C++ [class.abstract]p4: 5670 // A class is abstract if it contains or inherits at least one 5671 // pure virtual function for which the final overrider is pure 5672 // virtual. 5673 5674 // 5675 if (SO->second.size() != 1) 5676 continue; 5677 5678 if (!SO->second.front().Method->isPure()) 5679 continue; 5680 5681 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5682 continue; 5683 5684 Diag(SO->second.front().Method->getLocation(), 5685 diag::note_pure_virtual_function) 5686 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5687 } 5688 } 5689 5690 if (!PureVirtualClassDiagSet) 5691 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5692 PureVirtualClassDiagSet->insert(RD); 5693 } 5694 5695 namespace { 5696 struct AbstractUsageInfo { 5697 Sema &S; 5698 CXXRecordDecl *Record; 5699 CanQualType AbstractType; 5700 bool Invalid; 5701 5702 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5703 : S(S), Record(Record), 5704 AbstractType(S.Context.getCanonicalType( 5705 S.Context.getTypeDeclType(Record))), 5706 Invalid(false) {} 5707 5708 void DiagnoseAbstractType() { 5709 if (Invalid) return; 5710 S.DiagnoseAbstractType(Record); 5711 Invalid = true; 5712 } 5713 5714 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5715 }; 5716 5717 struct CheckAbstractUsage { 5718 AbstractUsageInfo &Info; 5719 const NamedDecl *Ctx; 5720 5721 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5722 : Info(Info), Ctx(Ctx) {} 5723 5724 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5725 switch (TL.getTypeLocClass()) { 5726 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5727 #define TYPELOC(CLASS, PARENT) \ 5728 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5729 #include "clang/AST/TypeLocNodes.def" 5730 } 5731 } 5732 5733 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5734 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5735 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5736 if (!TL.getParam(I)) 5737 continue; 5738 5739 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5740 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5741 } 5742 } 5743 5744 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5745 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5746 } 5747 5748 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5749 // Visit the type parameters from a permissive context. 5750 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5751 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5752 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5753 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5754 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5755 // TODO: other template argument types? 5756 } 5757 } 5758 5759 // Visit pointee types from a permissive context. 5760 #define CheckPolymorphic(Type) \ 5761 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5762 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5763 } 5764 CheckPolymorphic(PointerTypeLoc) 5765 CheckPolymorphic(ReferenceTypeLoc) 5766 CheckPolymorphic(MemberPointerTypeLoc) 5767 CheckPolymorphic(BlockPointerTypeLoc) 5768 CheckPolymorphic(AtomicTypeLoc) 5769 5770 /// Handle all the types we haven't given a more specific 5771 /// implementation for above. 5772 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5773 // Every other kind of type that we haven't called out already 5774 // that has an inner type is either (1) sugar or (2) contains that 5775 // inner type in some way as a subobject. 5776 if (TypeLoc Next = TL.getNextTypeLoc()) 5777 return Visit(Next, Sel); 5778 5779 // If there's no inner type and we're in a permissive context, 5780 // don't diagnose. 5781 if (Sel == Sema::AbstractNone) return; 5782 5783 // Check whether the type matches the abstract type. 5784 QualType T = TL.getType(); 5785 if (T->isArrayType()) { 5786 Sel = Sema::AbstractArrayType; 5787 T = Info.S.Context.getBaseElementType(T); 5788 } 5789 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5790 if (CT != Info.AbstractType) return; 5791 5792 // It matched; do some magic. 5793 if (Sel == Sema::AbstractArrayType) { 5794 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5795 << T << TL.getSourceRange(); 5796 } else { 5797 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5798 << Sel << T << TL.getSourceRange(); 5799 } 5800 Info.DiagnoseAbstractType(); 5801 } 5802 }; 5803 5804 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5805 Sema::AbstractDiagSelID Sel) { 5806 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5807 } 5808 5809 } 5810 5811 /// Check for invalid uses of an abstract type in a method declaration. 5812 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5813 CXXMethodDecl *MD) { 5814 // No need to do the check on definitions, which require that 5815 // the return/param types be complete. 5816 if (MD->doesThisDeclarationHaveABody()) 5817 return; 5818 5819 // For safety's sake, just ignore it if we don't have type source 5820 // information. This should never happen for non-implicit methods, 5821 // but... 5822 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5823 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5824 } 5825 5826 /// Check for invalid uses of an abstract type within a class definition. 5827 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5828 CXXRecordDecl *RD) { 5829 for (auto *D : RD->decls()) { 5830 if (D->isImplicit()) continue; 5831 5832 // Methods and method templates. 5833 if (isa<CXXMethodDecl>(D)) { 5834 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5835 } else if (isa<FunctionTemplateDecl>(D)) { 5836 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5837 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5838 5839 // Fields and static variables. 5840 } else if (isa<FieldDecl>(D)) { 5841 FieldDecl *FD = cast<FieldDecl>(D); 5842 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5843 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5844 } else if (isa<VarDecl>(D)) { 5845 VarDecl *VD = cast<VarDecl>(D); 5846 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5847 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5848 5849 // Nested classes and class templates. 5850 } else if (isa<CXXRecordDecl>(D)) { 5851 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5852 } else if (isa<ClassTemplateDecl>(D)) { 5853 CheckAbstractClassUsage(Info, 5854 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5855 } 5856 } 5857 } 5858 5859 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5860 Attr *ClassAttr = getDLLAttr(Class); 5861 if (!ClassAttr) 5862 return; 5863 5864 assert(ClassAttr->getKind() == attr::DLLExport); 5865 5866 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5867 5868 if (TSK == TSK_ExplicitInstantiationDeclaration) 5869 // Don't go any further if this is just an explicit instantiation 5870 // declaration. 5871 return; 5872 5873 // Add a context note to explain how we got to any diagnostics produced below. 5874 struct MarkingClassDllexported { 5875 Sema &S; 5876 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class, 5877 SourceLocation AttrLoc) 5878 : S(S) { 5879 Sema::CodeSynthesisContext Ctx; 5880 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported; 5881 Ctx.PointOfInstantiation = AttrLoc; 5882 Ctx.Entity = Class; 5883 S.pushCodeSynthesisContext(Ctx); 5884 } 5885 ~MarkingClassDllexported() { 5886 S.popCodeSynthesisContext(); 5887 } 5888 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); 5889 5890 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5891 S.MarkVTableUsed(Class->getLocation(), Class, true); 5892 5893 for (Decl *Member : Class->decls()) { 5894 // Defined static variables that are members of an exported base 5895 // class must be marked export too. 5896 auto *VD = dyn_cast<VarDecl>(Member); 5897 if (VD && Member->getAttr<DLLExportAttr>() && 5898 VD->getStorageClass() == SC_Static && 5899 TSK == TSK_ImplicitInstantiation) 5900 S.MarkVariableReferenced(VD->getLocation(), VD); 5901 5902 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5903 if (!MD) 5904 continue; 5905 5906 if (Member->getAttr<DLLExportAttr>()) { 5907 if (MD->isUserProvided()) { 5908 // Instantiate non-default class member functions ... 5909 5910 // .. except for certain kinds of template specializations. 5911 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5912 continue; 5913 5914 S.MarkFunctionReferenced(Class->getLocation(), MD); 5915 5916 // The function will be passed to the consumer when its definition is 5917 // encountered. 5918 } else if (MD->isExplicitlyDefaulted()) { 5919 // Synthesize and instantiate explicitly defaulted methods. 5920 S.MarkFunctionReferenced(Class->getLocation(), MD); 5921 5922 if (TSK != TSK_ExplicitInstantiationDefinition) { 5923 // Except for explicit instantiation defs, we will not see the 5924 // definition again later, so pass it to the consumer now. 5925 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5926 } 5927 } else if (!MD->isTrivial() || 5928 MD->isCopyAssignmentOperator() || 5929 MD->isMoveAssignmentOperator()) { 5930 // Synthesize and instantiate non-trivial implicit methods, and the copy 5931 // and move assignment operators. The latter are exported even if they 5932 // are trivial, because the address of an operator can be taken and 5933 // should compare equal across libraries. 5934 S.MarkFunctionReferenced(Class->getLocation(), MD); 5935 5936 // There is no later point when we will see the definition of this 5937 // function, so pass it to the consumer now. 5938 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5939 } 5940 } 5941 } 5942 } 5943 5944 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5945 CXXRecordDecl *Class) { 5946 // Only the MS ABI has default constructor closures, so we don't need to do 5947 // this semantic checking anywhere else. 5948 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5949 return; 5950 5951 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5952 for (Decl *Member : Class->decls()) { 5953 // Look for exported default constructors. 5954 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5955 if (!CD || !CD->isDefaultConstructor()) 5956 continue; 5957 auto *Attr = CD->getAttr<DLLExportAttr>(); 5958 if (!Attr) 5959 continue; 5960 5961 // If the class is non-dependent, mark the default arguments as ODR-used so 5962 // that we can properly codegen the constructor closure. 5963 if (!Class->isDependentContext()) { 5964 for (ParmVarDecl *PD : CD->parameters()) { 5965 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5966 S.DiscardCleanupsInEvaluationContext(); 5967 } 5968 } 5969 5970 if (LastExportedDefaultCtor) { 5971 S.Diag(LastExportedDefaultCtor->getLocation(), 5972 diag::err_attribute_dll_ambiguous_default_ctor) 5973 << Class; 5974 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5975 << CD->getDeclName(); 5976 return; 5977 } 5978 LastExportedDefaultCtor = CD; 5979 } 5980 } 5981 5982 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, 5983 CXXRecordDecl *Class) { 5984 bool ErrorReported = false; 5985 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 5986 ClassTemplateDecl *TD) { 5987 if (ErrorReported) 5988 return; 5989 S.Diag(TD->getLocation(), 5990 diag::err_cuda_device_builtin_surftex_cls_template) 5991 << /*surface*/ 0 << TD; 5992 ErrorReported = true; 5993 }; 5994 5995 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 5996 if (!TD) { 5997 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 5998 if (!SD) { 5999 S.Diag(Class->getLocation(), 6000 diag::err_cuda_device_builtin_surftex_ref_decl) 6001 << /*surface*/ 0 << Class; 6002 S.Diag(Class->getLocation(), 6003 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6004 << Class; 6005 return; 6006 } 6007 TD = SD->getSpecializedTemplate(); 6008 } 6009 6010 TemplateParameterList *Params = TD->getTemplateParameters(); 6011 unsigned N = Params->size(); 6012 6013 if (N != 2) { 6014 reportIllegalClassTemplate(S, TD); 6015 S.Diag(TD->getLocation(), 6016 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6017 << TD << 2; 6018 } 6019 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6020 reportIllegalClassTemplate(S, TD); 6021 S.Diag(TD->getLocation(), 6022 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6023 << TD << /*1st*/ 0 << /*type*/ 0; 6024 } 6025 if (N > 1) { 6026 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6027 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6028 reportIllegalClassTemplate(S, TD); 6029 S.Diag(TD->getLocation(), 6030 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6031 << TD << /*2nd*/ 1 << /*integer*/ 1; 6032 } 6033 } 6034 } 6035 6036 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, 6037 CXXRecordDecl *Class) { 6038 bool ErrorReported = false; 6039 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6040 ClassTemplateDecl *TD) { 6041 if (ErrorReported) 6042 return; 6043 S.Diag(TD->getLocation(), 6044 diag::err_cuda_device_builtin_surftex_cls_template) 6045 << /*texture*/ 1 << TD; 6046 ErrorReported = true; 6047 }; 6048 6049 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6050 if (!TD) { 6051 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6052 if (!SD) { 6053 S.Diag(Class->getLocation(), 6054 diag::err_cuda_device_builtin_surftex_ref_decl) 6055 << /*texture*/ 1 << Class; 6056 S.Diag(Class->getLocation(), 6057 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6058 << Class; 6059 return; 6060 } 6061 TD = SD->getSpecializedTemplate(); 6062 } 6063 6064 TemplateParameterList *Params = TD->getTemplateParameters(); 6065 unsigned N = Params->size(); 6066 6067 if (N != 3) { 6068 reportIllegalClassTemplate(S, TD); 6069 S.Diag(TD->getLocation(), 6070 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6071 << TD << 3; 6072 } 6073 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6074 reportIllegalClassTemplate(S, TD); 6075 S.Diag(TD->getLocation(), 6076 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6077 << TD << /*1st*/ 0 << /*type*/ 0; 6078 } 6079 if (N > 1) { 6080 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6081 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6082 reportIllegalClassTemplate(S, TD); 6083 S.Diag(TD->getLocation(), 6084 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6085 << TD << /*2nd*/ 1 << /*integer*/ 1; 6086 } 6087 } 6088 if (N > 2) { 6089 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2)); 6090 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6091 reportIllegalClassTemplate(S, TD); 6092 S.Diag(TD->getLocation(), 6093 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6094 << TD << /*3rd*/ 2 << /*integer*/ 1; 6095 } 6096 } 6097 } 6098 6099 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 6100 // Mark any compiler-generated routines with the implicit code_seg attribute. 6101 for (auto *Method : Class->methods()) { 6102 if (Method->isUserProvided()) 6103 continue; 6104 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 6105 Method->addAttr(A); 6106 } 6107 } 6108 6109 /// Check class-level dllimport/dllexport attribute. 6110 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 6111 Attr *ClassAttr = getDLLAttr(Class); 6112 6113 // MSVC inherits DLL attributes to partial class template specializations. 6114 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) { 6115 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 6116 if (Attr *TemplateAttr = 6117 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 6118 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 6119 A->setInherited(true); 6120 ClassAttr = A; 6121 } 6122 } 6123 } 6124 6125 if (!ClassAttr) 6126 return; 6127 6128 if (!Class->isExternallyVisible()) { 6129 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 6130 << Class << ClassAttr; 6131 return; 6132 } 6133 6134 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6135 !ClassAttr->isInherited()) { 6136 // Diagnose dll attributes on members of class with dll attribute. 6137 for (Decl *Member : Class->decls()) { 6138 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 6139 continue; 6140 InheritableAttr *MemberAttr = getDLLAttr(Member); 6141 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 6142 continue; 6143 6144 Diag(MemberAttr->getLocation(), 6145 diag::err_attribute_dll_member_of_dll_class) 6146 << MemberAttr << ClassAttr; 6147 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 6148 Member->setInvalidDecl(); 6149 } 6150 } 6151 6152 if (Class->getDescribedClassTemplate()) 6153 // Don't inherit dll attribute until the template is instantiated. 6154 return; 6155 6156 // The class is either imported or exported. 6157 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 6158 6159 // Check if this was a dllimport attribute propagated from a derived class to 6160 // a base class template specialization. We don't apply these attributes to 6161 // static data members. 6162 const bool PropagatedImport = 6163 !ClassExported && 6164 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 6165 6166 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6167 6168 // Ignore explicit dllexport on explicit class template instantiation 6169 // declarations, except in MinGW mode. 6170 if (ClassExported && !ClassAttr->isInherited() && 6171 TSK == TSK_ExplicitInstantiationDeclaration && 6172 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 6173 Class->dropAttr<DLLExportAttr>(); 6174 return; 6175 } 6176 6177 // Force declaration of implicit members so they can inherit the attribute. 6178 ForceDeclarationOfImplicitMembers(Class); 6179 6180 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 6181 // seem to be true in practice? 6182 6183 for (Decl *Member : Class->decls()) { 6184 VarDecl *VD = dyn_cast<VarDecl>(Member); 6185 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 6186 6187 // Only methods and static fields inherit the attributes. 6188 if (!VD && !MD) 6189 continue; 6190 6191 if (MD) { 6192 // Don't process deleted methods. 6193 if (MD->isDeleted()) 6194 continue; 6195 6196 if (MD->isInlined()) { 6197 // MinGW does not import or export inline methods. But do it for 6198 // template instantiations. 6199 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6200 TSK != TSK_ExplicitInstantiationDeclaration && 6201 TSK != TSK_ExplicitInstantiationDefinition) 6202 continue; 6203 6204 // MSVC versions before 2015 don't export the move assignment operators 6205 // and move constructor, so don't attempt to import/export them if 6206 // we have a definition. 6207 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 6208 if ((MD->isMoveAssignmentOperator() || 6209 (Ctor && Ctor->isMoveConstructor())) && 6210 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 6211 continue; 6212 6213 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 6214 // operator is exported anyway. 6215 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6216 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 6217 continue; 6218 } 6219 } 6220 6221 // Don't apply dllimport attributes to static data members of class template 6222 // instantiations when the attribute is propagated from a derived class. 6223 if (VD && PropagatedImport) 6224 continue; 6225 6226 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6227 continue; 6228 6229 if (!getDLLAttr(Member)) { 6230 InheritableAttr *NewAttr = nullptr; 6231 6232 // Do not export/import inline function when -fno-dllexport-inlines is 6233 // passed. But add attribute for later local static var check. 6234 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6235 TSK != TSK_ExplicitInstantiationDeclaration && 6236 TSK != TSK_ExplicitInstantiationDefinition) { 6237 if (ClassExported) { 6238 NewAttr = ::new (getASTContext()) 6239 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6240 } else { 6241 NewAttr = ::new (getASTContext()) 6242 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6243 } 6244 } else { 6245 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6246 } 6247 6248 NewAttr->setInherited(true); 6249 Member->addAttr(NewAttr); 6250 6251 if (MD) { 6252 // Propagate DLLAttr to friend re-declarations of MD that have already 6253 // been constructed. 6254 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6255 FD = FD->getPreviousDecl()) { 6256 if (FD->getFriendObjectKind() == Decl::FOK_None) 6257 continue; 6258 assert(!getDLLAttr(FD) && 6259 "friend re-decl should not already have a DLLAttr"); 6260 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6261 NewAttr->setInherited(true); 6262 FD->addAttr(NewAttr); 6263 } 6264 } 6265 } 6266 } 6267 6268 if (ClassExported) 6269 DelayedDllExportClasses.push_back(Class); 6270 } 6271 6272 /// Perform propagation of DLL attributes from a derived class to a 6273 /// templated base class for MS compatibility. 6274 void Sema::propagateDLLAttrToBaseClassTemplate( 6275 CXXRecordDecl *Class, Attr *ClassAttr, 6276 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6277 if (getDLLAttr( 6278 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6279 // If the base class template has a DLL attribute, don't try to change it. 6280 return; 6281 } 6282 6283 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6284 if (!getDLLAttr(BaseTemplateSpec) && 6285 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6286 TSK == TSK_ImplicitInstantiation)) { 6287 // The template hasn't been instantiated yet (or it has, but only as an 6288 // explicit instantiation declaration or implicit instantiation, which means 6289 // we haven't codegenned any members yet), so propagate the attribute. 6290 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6291 NewAttr->setInherited(true); 6292 BaseTemplateSpec->addAttr(NewAttr); 6293 6294 // If this was an import, mark that we propagated it from a derived class to 6295 // a base class template specialization. 6296 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6297 ImportAttr->setPropagatedToBaseTemplate(); 6298 6299 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6300 // needs to be run again to work see the new attribute. Otherwise this will 6301 // get run whenever the template is instantiated. 6302 if (TSK != TSK_Undeclared) 6303 checkClassLevelDLLAttribute(BaseTemplateSpec); 6304 6305 return; 6306 } 6307 6308 if (getDLLAttr(BaseTemplateSpec)) { 6309 // The template has already been specialized or instantiated with an 6310 // attribute, explicitly or through propagation. We should not try to change 6311 // it. 6312 return; 6313 } 6314 6315 // The template was previously instantiated or explicitly specialized without 6316 // a dll attribute, It's too late for us to add an attribute, so warn that 6317 // this is unsupported. 6318 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6319 << BaseTemplateSpec->isExplicitSpecialization(); 6320 Diag(ClassAttr->getLocation(), diag::note_attribute); 6321 if (BaseTemplateSpec->isExplicitSpecialization()) { 6322 Diag(BaseTemplateSpec->getLocation(), 6323 diag::note_template_class_explicit_specialization_was_here) 6324 << BaseTemplateSpec; 6325 } else { 6326 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6327 diag::note_template_class_instantiation_was_here) 6328 << BaseTemplateSpec; 6329 } 6330 } 6331 6332 /// Determine the kind of defaulting that would be done for a given function. 6333 /// 6334 /// If the function is both a default constructor and a copy / move constructor 6335 /// (due to having a default argument for the first parameter), this picks 6336 /// CXXDefaultConstructor. 6337 /// 6338 /// FIXME: Check that case is properly handled by all callers. 6339 Sema::DefaultedFunctionKind 6340 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6341 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6342 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6343 if (Ctor->isDefaultConstructor()) 6344 return Sema::CXXDefaultConstructor; 6345 6346 if (Ctor->isCopyConstructor()) 6347 return Sema::CXXCopyConstructor; 6348 6349 if (Ctor->isMoveConstructor()) 6350 return Sema::CXXMoveConstructor; 6351 } 6352 6353 if (MD->isCopyAssignmentOperator()) 6354 return Sema::CXXCopyAssignment; 6355 6356 if (MD->isMoveAssignmentOperator()) 6357 return Sema::CXXMoveAssignment; 6358 6359 if (isa<CXXDestructorDecl>(FD)) 6360 return Sema::CXXDestructor; 6361 } 6362 6363 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6364 case OO_EqualEqual: 6365 return DefaultedComparisonKind::Equal; 6366 6367 case OO_ExclaimEqual: 6368 return DefaultedComparisonKind::NotEqual; 6369 6370 case OO_Spaceship: 6371 // No point allowing this if <=> doesn't exist in the current language mode. 6372 if (!getLangOpts().CPlusPlus20) 6373 break; 6374 return DefaultedComparisonKind::ThreeWay; 6375 6376 case OO_Less: 6377 case OO_LessEqual: 6378 case OO_Greater: 6379 case OO_GreaterEqual: 6380 // No point allowing this if <=> doesn't exist in the current language mode. 6381 if (!getLangOpts().CPlusPlus20) 6382 break; 6383 return DefaultedComparisonKind::Relational; 6384 6385 default: 6386 break; 6387 } 6388 6389 // Not defaultable. 6390 return DefaultedFunctionKind(); 6391 } 6392 6393 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, 6394 SourceLocation DefaultLoc) { 6395 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD); 6396 if (DFK.isComparison()) 6397 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison()); 6398 6399 switch (DFK.asSpecialMember()) { 6400 case Sema::CXXDefaultConstructor: 6401 S.DefineImplicitDefaultConstructor(DefaultLoc, 6402 cast<CXXConstructorDecl>(FD)); 6403 break; 6404 case Sema::CXXCopyConstructor: 6405 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6406 break; 6407 case Sema::CXXCopyAssignment: 6408 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6409 break; 6410 case Sema::CXXDestructor: 6411 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD)); 6412 break; 6413 case Sema::CXXMoveConstructor: 6414 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6415 break; 6416 case Sema::CXXMoveAssignment: 6417 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6418 break; 6419 case Sema::CXXInvalid: 6420 llvm_unreachable("Invalid special member."); 6421 } 6422 } 6423 6424 /// Determine whether a type is permitted to be passed or returned in 6425 /// registers, per C++ [class.temporary]p3. 6426 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6427 TargetInfo::CallingConvKind CCK) { 6428 if (D->isDependentType() || D->isInvalidDecl()) 6429 return false; 6430 6431 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6432 // The PS4 platform ABI follows the behavior of Clang 3.2. 6433 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6434 return !D->hasNonTrivialDestructorForCall() && 6435 !D->hasNonTrivialCopyConstructorForCall(); 6436 6437 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6438 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6439 bool DtorIsTrivialForCall = false; 6440 6441 // If a class has at least one non-deleted, trivial copy constructor, it 6442 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6443 // 6444 // Note: This permits classes with non-trivial copy or move ctors to be 6445 // passed in registers, so long as they *also* have a trivial copy ctor, 6446 // which is non-conforming. 6447 if (D->needsImplicitCopyConstructor()) { 6448 if (!D->defaultedCopyConstructorIsDeleted()) { 6449 if (D->hasTrivialCopyConstructor()) 6450 CopyCtorIsTrivial = true; 6451 if (D->hasTrivialCopyConstructorForCall()) 6452 CopyCtorIsTrivialForCall = true; 6453 } 6454 } else { 6455 for (const CXXConstructorDecl *CD : D->ctors()) { 6456 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6457 if (CD->isTrivial()) 6458 CopyCtorIsTrivial = true; 6459 if (CD->isTrivialForCall()) 6460 CopyCtorIsTrivialForCall = true; 6461 } 6462 } 6463 } 6464 6465 if (D->needsImplicitDestructor()) { 6466 if (!D->defaultedDestructorIsDeleted() && 6467 D->hasTrivialDestructorForCall()) 6468 DtorIsTrivialForCall = true; 6469 } else if (const auto *DD = D->getDestructor()) { 6470 if (!DD->isDeleted() && DD->isTrivialForCall()) 6471 DtorIsTrivialForCall = true; 6472 } 6473 6474 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6475 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6476 return true; 6477 6478 // If a class has a destructor, we'd really like to pass it indirectly 6479 // because it allows us to elide copies. Unfortunately, MSVC makes that 6480 // impossible for small types, which it will pass in a single register or 6481 // stack slot. Most objects with dtors are large-ish, so handle that early. 6482 // We can't call out all large objects as being indirect because there are 6483 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6484 // how we pass large POD types. 6485 6486 // Note: This permits small classes with nontrivial destructors to be 6487 // passed in registers, which is non-conforming. 6488 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6489 uint64_t TypeSize = isAArch64 ? 128 : 64; 6490 6491 if (CopyCtorIsTrivial && 6492 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6493 return true; 6494 return false; 6495 } 6496 6497 // Per C++ [class.temporary]p3, the relevant condition is: 6498 // each copy constructor, move constructor, and destructor of X is 6499 // either trivial or deleted, and X has at least one non-deleted copy 6500 // or move constructor 6501 bool HasNonDeletedCopyOrMove = false; 6502 6503 if (D->needsImplicitCopyConstructor() && 6504 !D->defaultedCopyConstructorIsDeleted()) { 6505 if (!D->hasTrivialCopyConstructorForCall()) 6506 return false; 6507 HasNonDeletedCopyOrMove = true; 6508 } 6509 6510 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6511 !D->defaultedMoveConstructorIsDeleted()) { 6512 if (!D->hasTrivialMoveConstructorForCall()) 6513 return false; 6514 HasNonDeletedCopyOrMove = true; 6515 } 6516 6517 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6518 !D->hasTrivialDestructorForCall()) 6519 return false; 6520 6521 for (const CXXMethodDecl *MD : D->methods()) { 6522 if (MD->isDeleted()) 6523 continue; 6524 6525 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6526 if (CD && CD->isCopyOrMoveConstructor()) 6527 HasNonDeletedCopyOrMove = true; 6528 else if (!isa<CXXDestructorDecl>(MD)) 6529 continue; 6530 6531 if (!MD->isTrivialForCall()) 6532 return false; 6533 } 6534 6535 return HasNonDeletedCopyOrMove; 6536 } 6537 6538 /// Report an error regarding overriding, along with any relevant 6539 /// overridden methods. 6540 /// 6541 /// \param DiagID the primary error to report. 6542 /// \param MD the overriding method. 6543 static bool 6544 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, 6545 llvm::function_ref<bool(const CXXMethodDecl *)> Report) { 6546 bool IssuedDiagnostic = false; 6547 for (const CXXMethodDecl *O : MD->overridden_methods()) { 6548 if (Report(O)) { 6549 if (!IssuedDiagnostic) { 6550 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6551 IssuedDiagnostic = true; 6552 } 6553 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 6554 } 6555 } 6556 return IssuedDiagnostic; 6557 } 6558 6559 /// Perform semantic checks on a class definition that has been 6560 /// completing, introducing implicitly-declared members, checking for 6561 /// abstract types, etc. 6562 /// 6563 /// \param S The scope in which the class was parsed. Null if we didn't just 6564 /// parse a class definition. 6565 /// \param Record The completed class. 6566 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6567 if (!Record) 6568 return; 6569 6570 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6571 AbstractUsageInfo Info(*this, Record); 6572 CheckAbstractClassUsage(Info, Record); 6573 } 6574 6575 // If this is not an aggregate type and has no user-declared constructor, 6576 // complain about any non-static data members of reference or const scalar 6577 // type, since they will never get initializers. 6578 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6579 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6580 !Record->isLambda()) { 6581 bool Complained = false; 6582 for (const auto *F : Record->fields()) { 6583 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6584 continue; 6585 6586 if (F->getType()->isReferenceType() || 6587 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6588 if (!Complained) { 6589 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6590 << Record->getTagKind() << Record; 6591 Complained = true; 6592 } 6593 6594 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6595 << F->getType()->isReferenceType() 6596 << F->getDeclName(); 6597 } 6598 } 6599 } 6600 6601 if (Record->getIdentifier()) { 6602 // C++ [class.mem]p13: 6603 // If T is the name of a class, then each of the following shall have a 6604 // name different from T: 6605 // - every member of every anonymous union that is a member of class T. 6606 // 6607 // C++ [class.mem]p14: 6608 // In addition, if class T has a user-declared constructor (12.1), every 6609 // non-static data member of class T shall have a name different from T. 6610 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6611 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6612 ++I) { 6613 NamedDecl *D = (*I)->getUnderlyingDecl(); 6614 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6615 Record->hasUserDeclaredConstructor()) || 6616 isa<IndirectFieldDecl>(D)) { 6617 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6618 << D->getDeclName(); 6619 break; 6620 } 6621 } 6622 } 6623 6624 // Warn if the class has virtual methods but non-virtual public destructor. 6625 if (Record->isPolymorphic() && !Record->isDependentType()) { 6626 CXXDestructorDecl *dtor = Record->getDestructor(); 6627 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6628 !Record->hasAttr<FinalAttr>()) 6629 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6630 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6631 } 6632 6633 if (Record->isAbstract()) { 6634 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6635 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6636 << FA->isSpelledAsSealed(); 6637 DiagnoseAbstractType(Record); 6638 } 6639 } 6640 6641 // Warn if the class has a final destructor but is not itself marked final. 6642 if (!Record->hasAttr<FinalAttr>()) { 6643 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6644 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6645 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6646 << FA->isSpelledAsSealed() 6647 << FixItHint::CreateInsertion( 6648 getLocForEndOfToken(Record->getLocation()), 6649 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6650 Diag(Record->getLocation(), 6651 diag::note_final_dtor_non_final_class_silence) 6652 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6653 } 6654 } 6655 } 6656 6657 // See if trivial_abi has to be dropped. 6658 if (Record->hasAttr<TrivialABIAttr>()) 6659 checkIllFormedTrivialABIStruct(*Record); 6660 6661 // Set HasTrivialSpecialMemberForCall if the record has attribute 6662 // "trivial_abi". 6663 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6664 6665 if (HasTrivialABI) 6666 Record->setHasTrivialSpecialMemberForCall(); 6667 6668 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6669 // We check these last because they can depend on the properties of the 6670 // primary comparison functions (==, <=>). 6671 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6672 6673 // Perform checks that can't be done until we know all the properties of a 6674 // member function (whether it's defaulted, deleted, virtual, overriding, 6675 // ...). 6676 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) { 6677 // A static function cannot override anything. 6678 if (MD->getStorageClass() == SC_Static) { 6679 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD, 6680 [](const CXXMethodDecl *) { return true; })) 6681 return; 6682 } 6683 6684 // A deleted function cannot override a non-deleted function and vice 6685 // versa. 6686 if (ReportOverrides(*this, 6687 MD->isDeleted() ? diag::err_deleted_override 6688 : diag::err_non_deleted_override, 6689 MD, [&](const CXXMethodDecl *V) { 6690 return MD->isDeleted() != V->isDeleted(); 6691 })) { 6692 if (MD->isDefaulted() && MD->isDeleted()) 6693 // Explain why this defaulted function was deleted. 6694 DiagnoseDeletedDefaultedFunction(MD); 6695 return; 6696 } 6697 6698 // A consteval function cannot override a non-consteval function and vice 6699 // versa. 6700 if (ReportOverrides(*this, 6701 MD->isConsteval() ? diag::err_consteval_override 6702 : diag::err_non_consteval_override, 6703 MD, [&](const CXXMethodDecl *V) { 6704 return MD->isConsteval() != V->isConsteval(); 6705 })) { 6706 if (MD->isDefaulted() && MD->isDeleted()) 6707 // Explain why this defaulted function was deleted. 6708 DiagnoseDeletedDefaultedFunction(MD); 6709 return; 6710 } 6711 }; 6712 6713 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool { 6714 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6715 return false; 6716 6717 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6718 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6719 DFK.asComparison() == DefaultedComparisonKind::Relational) { 6720 DefaultedSecondaryComparisons.push_back(FD); 6721 return true; 6722 } 6723 6724 CheckExplicitlyDefaultedFunction(S, FD); 6725 return false; 6726 }; 6727 6728 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6729 // Check whether the explicitly-defaulted members are valid. 6730 bool Incomplete = CheckForDefaultedFunction(M); 6731 6732 // Skip the rest of the checks for a member of a dependent class. 6733 if (Record->isDependentType()) 6734 return; 6735 6736 // For an explicitly defaulted or deleted special member, we defer 6737 // determining triviality until the class is complete. That time is now! 6738 CXXSpecialMember CSM = getSpecialMember(M); 6739 if (!M->isImplicit() && !M->isUserProvided()) { 6740 if (CSM != CXXInvalid) { 6741 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6742 // Inform the class that we've finished declaring this member. 6743 Record->finishedDefaultedOrDeletedMember(M); 6744 M->setTrivialForCall( 6745 HasTrivialABI || 6746 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6747 Record->setTrivialForCallFlags(M); 6748 } 6749 } 6750 6751 // Set triviality for the purpose of calls if this is a user-provided 6752 // copy/move constructor or destructor. 6753 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6754 CSM == CXXDestructor) && M->isUserProvided()) { 6755 M->setTrivialForCall(HasTrivialABI); 6756 Record->setTrivialForCallFlags(M); 6757 } 6758 6759 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6760 M->hasAttr<DLLExportAttr>()) { 6761 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6762 M->isTrivial() && 6763 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6764 CSM == CXXDestructor)) 6765 M->dropAttr<DLLExportAttr>(); 6766 6767 if (M->hasAttr<DLLExportAttr>()) { 6768 // Define after any fields with in-class initializers have been parsed. 6769 DelayedDllExportMemberFunctions.push_back(M); 6770 } 6771 } 6772 6773 // Define defaulted constexpr virtual functions that override a base class 6774 // function right away. 6775 // FIXME: We can defer doing this until the vtable is marked as used. 6776 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6777 DefineDefaultedFunction(*this, M, M->getLocation()); 6778 6779 if (!Incomplete) 6780 CheckCompletedMemberFunction(M); 6781 }; 6782 6783 // Check the destructor before any other member function. We need to 6784 // determine whether it's trivial in order to determine whether the claas 6785 // type is a literal type, which is a prerequisite for determining whether 6786 // other special member functions are valid and whether they're implicitly 6787 // 'constexpr'. 6788 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6789 CompleteMemberFunction(Dtor); 6790 6791 bool HasMethodWithOverrideControl = false, 6792 HasOverridingMethodWithoutOverrideControl = false; 6793 for (auto *D : Record->decls()) { 6794 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 6795 // FIXME: We could do this check for dependent types with non-dependent 6796 // bases. 6797 if (!Record->isDependentType()) { 6798 // See if a method overloads virtual methods in a base 6799 // class without overriding any. 6800 if (!M->isStatic()) 6801 DiagnoseHiddenVirtualMethods(M); 6802 if (M->hasAttr<OverrideAttr>()) 6803 HasMethodWithOverrideControl = true; 6804 else if (M->size_overridden_methods() > 0) 6805 HasOverridingMethodWithoutOverrideControl = true; 6806 } 6807 6808 if (!isa<CXXDestructorDecl>(M)) 6809 CompleteMemberFunction(M); 6810 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 6811 CheckForDefaultedFunction( 6812 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 6813 } 6814 } 6815 6816 if (HasOverridingMethodWithoutOverrideControl) { 6817 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl; 6818 for (auto *M : Record->methods()) 6819 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl); 6820 } 6821 6822 // Check the defaulted secondary comparisons after any other member functions. 6823 for (FunctionDecl *FD : DefaultedSecondaryComparisons) { 6824 CheckExplicitlyDefaultedFunction(S, FD); 6825 6826 // If this is a member function, we deferred checking it until now. 6827 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) 6828 CheckCompletedMemberFunction(MD); 6829 } 6830 6831 // ms_struct is a request to use the same ABI rules as MSVC. Check 6832 // whether this class uses any C++ features that are implemented 6833 // completely differently in MSVC, and if so, emit a diagnostic. 6834 // That diagnostic defaults to an error, but we allow projects to 6835 // map it down to a warning (or ignore it). It's a fairly common 6836 // practice among users of the ms_struct pragma to mass-annotate 6837 // headers, sweeping up a bunch of types that the project doesn't 6838 // really rely on MSVC-compatible layout for. We must therefore 6839 // support "ms_struct except for C++ stuff" as a secondary ABI. 6840 // Don't emit this diagnostic if the feature was enabled as a 6841 // language option (as opposed to via a pragma or attribute), as 6842 // the option -mms-bitfields otherwise essentially makes it impossible 6843 // to build C++ code, unless this diagnostic is turned off. 6844 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields && 6845 (Record->isPolymorphic() || Record->getNumBases())) { 6846 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6847 } 6848 6849 checkClassLevelDLLAttribute(Record); 6850 checkClassLevelCodeSegAttribute(Record); 6851 6852 bool ClangABICompat4 = 6853 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6854 TargetInfo::CallingConvKind CCK = 6855 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6856 bool CanPass = canPassInRegisters(*this, Record, CCK); 6857 6858 // Do not change ArgPassingRestrictions if it has already been set to 6859 // APK_CanNeverPassInRegs. 6860 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6861 Record->setArgPassingRestrictions(CanPass 6862 ? RecordDecl::APK_CanPassInRegs 6863 : RecordDecl::APK_CannotPassInRegs); 6864 6865 // If canPassInRegisters returns true despite the record having a non-trivial 6866 // destructor, the record is destructed in the callee. This happens only when 6867 // the record or one of its subobjects has a field annotated with trivial_abi 6868 // or a field qualified with ObjC __strong/__weak. 6869 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6870 Record->setParamDestroyedInCallee(true); 6871 else if (Record->hasNonTrivialDestructor()) 6872 Record->setParamDestroyedInCallee(CanPass); 6873 6874 if (getLangOpts().ForceEmitVTables) { 6875 // If we want to emit all the vtables, we need to mark it as used. This 6876 // is especially required for cases like vtable assumption loads. 6877 MarkVTableUsed(Record->getInnerLocStart(), Record); 6878 } 6879 6880 if (getLangOpts().CUDA) { 6881 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) 6882 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record); 6883 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>()) 6884 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record); 6885 } 6886 } 6887 6888 /// Look up the special member function that would be called by a special 6889 /// member function for a subobject of class type. 6890 /// 6891 /// \param Class The class type of the subobject. 6892 /// \param CSM The kind of special member function. 6893 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6894 /// \param ConstRHS True if this is a copy operation with a const object 6895 /// on its RHS, that is, if the argument to the outer special member 6896 /// function is 'const' and this is not a field marked 'mutable'. 6897 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6898 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6899 unsigned FieldQuals, bool ConstRHS) { 6900 unsigned LHSQuals = 0; 6901 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6902 LHSQuals = FieldQuals; 6903 6904 unsigned RHSQuals = FieldQuals; 6905 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6906 RHSQuals = 0; 6907 else if (ConstRHS) 6908 RHSQuals |= Qualifiers::Const; 6909 6910 return S.LookupSpecialMember(Class, CSM, 6911 RHSQuals & Qualifiers::Const, 6912 RHSQuals & Qualifiers::Volatile, 6913 false, 6914 LHSQuals & Qualifiers::Const, 6915 LHSQuals & Qualifiers::Volatile); 6916 } 6917 6918 class Sema::InheritedConstructorInfo { 6919 Sema &S; 6920 SourceLocation UseLoc; 6921 6922 /// A mapping from the base classes through which the constructor was 6923 /// inherited to the using shadow declaration in that base class (or a null 6924 /// pointer if the constructor was declared in that base class). 6925 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6926 InheritedFromBases; 6927 6928 public: 6929 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6930 ConstructorUsingShadowDecl *Shadow) 6931 : S(S), UseLoc(UseLoc) { 6932 bool DiagnosedMultipleConstructedBases = false; 6933 CXXRecordDecl *ConstructedBase = nullptr; 6934 UsingDecl *ConstructedBaseUsing = nullptr; 6935 6936 // Find the set of such base class subobjects and check that there's a 6937 // unique constructed subobject. 6938 for (auto *D : Shadow->redecls()) { 6939 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6940 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6941 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6942 6943 InheritedFromBases.insert( 6944 std::make_pair(DNominatedBase->getCanonicalDecl(), 6945 DShadow->getNominatedBaseClassShadowDecl())); 6946 if (DShadow->constructsVirtualBase()) 6947 InheritedFromBases.insert( 6948 std::make_pair(DConstructedBase->getCanonicalDecl(), 6949 DShadow->getConstructedBaseClassShadowDecl())); 6950 else 6951 assert(DNominatedBase == DConstructedBase); 6952 6953 // [class.inhctor.init]p2: 6954 // If the constructor was inherited from multiple base class subobjects 6955 // of type B, the program is ill-formed. 6956 if (!ConstructedBase) { 6957 ConstructedBase = DConstructedBase; 6958 ConstructedBaseUsing = D->getUsingDecl(); 6959 } else if (ConstructedBase != DConstructedBase && 6960 !Shadow->isInvalidDecl()) { 6961 if (!DiagnosedMultipleConstructedBases) { 6962 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6963 << Shadow->getTargetDecl(); 6964 S.Diag(ConstructedBaseUsing->getLocation(), 6965 diag::note_ambiguous_inherited_constructor_using) 6966 << ConstructedBase; 6967 DiagnosedMultipleConstructedBases = true; 6968 } 6969 S.Diag(D->getUsingDecl()->getLocation(), 6970 diag::note_ambiguous_inherited_constructor_using) 6971 << DConstructedBase; 6972 } 6973 } 6974 6975 if (DiagnosedMultipleConstructedBases) 6976 Shadow->setInvalidDecl(); 6977 } 6978 6979 /// Find the constructor to use for inherited construction of a base class, 6980 /// and whether that base class constructor inherits the constructor from a 6981 /// virtual base class (in which case it won't actually invoke it). 6982 std::pair<CXXConstructorDecl *, bool> 6983 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6984 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6985 if (It == InheritedFromBases.end()) 6986 return std::make_pair(nullptr, false); 6987 6988 // This is an intermediary class. 6989 if (It->second) 6990 return std::make_pair( 6991 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6992 It->second->constructsVirtualBase()); 6993 6994 // This is the base class from which the constructor was inherited. 6995 return std::make_pair(Ctor, false); 6996 } 6997 }; 6998 6999 /// Is the special member function which would be selected to perform the 7000 /// specified operation on the specified class type a constexpr constructor? 7001 static bool 7002 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 7003 Sema::CXXSpecialMember CSM, unsigned Quals, 7004 bool ConstRHS, 7005 CXXConstructorDecl *InheritedCtor = nullptr, 7006 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7007 // If we're inheriting a constructor, see if we need to call it for this base 7008 // class. 7009 if (InheritedCtor) { 7010 assert(CSM == Sema::CXXDefaultConstructor); 7011 auto BaseCtor = 7012 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 7013 if (BaseCtor) 7014 return BaseCtor->isConstexpr(); 7015 } 7016 7017 if (CSM == Sema::CXXDefaultConstructor) 7018 return ClassDecl->hasConstexprDefaultConstructor(); 7019 if (CSM == Sema::CXXDestructor) 7020 return ClassDecl->hasConstexprDestructor(); 7021 7022 Sema::SpecialMemberOverloadResult SMOR = 7023 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 7024 if (!SMOR.getMethod()) 7025 // A constructor we wouldn't select can't be "involved in initializing" 7026 // anything. 7027 return true; 7028 return SMOR.getMethod()->isConstexpr(); 7029 } 7030 7031 /// Determine whether the specified special member function would be constexpr 7032 /// if it were implicitly defined. 7033 static bool defaultedSpecialMemberIsConstexpr( 7034 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 7035 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 7036 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7037 if (!S.getLangOpts().CPlusPlus11) 7038 return false; 7039 7040 // C++11 [dcl.constexpr]p4: 7041 // In the definition of a constexpr constructor [...] 7042 bool Ctor = true; 7043 switch (CSM) { 7044 case Sema::CXXDefaultConstructor: 7045 if (Inherited) 7046 break; 7047 // Since default constructor lookup is essentially trivial (and cannot 7048 // involve, for instance, template instantiation), we compute whether a 7049 // defaulted default constructor is constexpr directly within CXXRecordDecl. 7050 // 7051 // This is important for performance; we need to know whether the default 7052 // constructor is constexpr to determine whether the type is a literal type. 7053 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 7054 7055 case Sema::CXXCopyConstructor: 7056 case Sema::CXXMoveConstructor: 7057 // For copy or move constructors, we need to perform overload resolution. 7058 break; 7059 7060 case Sema::CXXCopyAssignment: 7061 case Sema::CXXMoveAssignment: 7062 if (!S.getLangOpts().CPlusPlus14) 7063 return false; 7064 // In C++1y, we need to perform overload resolution. 7065 Ctor = false; 7066 break; 7067 7068 case Sema::CXXDestructor: 7069 return ClassDecl->defaultedDestructorIsConstexpr(); 7070 7071 case Sema::CXXInvalid: 7072 return false; 7073 } 7074 7075 // -- if the class is a non-empty union, or for each non-empty anonymous 7076 // union member of a non-union class, exactly one non-static data member 7077 // shall be initialized; [DR1359] 7078 // 7079 // If we squint, this is guaranteed, since exactly one non-static data member 7080 // will be initialized (if the constructor isn't deleted), we just don't know 7081 // which one. 7082 if (Ctor && ClassDecl->isUnion()) 7083 return CSM == Sema::CXXDefaultConstructor 7084 ? ClassDecl->hasInClassInitializer() || 7085 !ClassDecl->hasVariantMembers() 7086 : true; 7087 7088 // -- the class shall not have any virtual base classes; 7089 if (Ctor && ClassDecl->getNumVBases()) 7090 return false; 7091 7092 // C++1y [class.copy]p26: 7093 // -- [the class] is a literal type, and 7094 if (!Ctor && !ClassDecl->isLiteral()) 7095 return false; 7096 7097 // -- every constructor involved in initializing [...] base class 7098 // sub-objects shall be a constexpr constructor; 7099 // -- the assignment operator selected to copy/move each direct base 7100 // class is a constexpr function, and 7101 for (const auto &B : ClassDecl->bases()) { 7102 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 7103 if (!BaseType) continue; 7104 7105 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7106 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 7107 InheritedCtor, Inherited)) 7108 return false; 7109 } 7110 7111 // -- every constructor involved in initializing non-static data members 7112 // [...] shall be a constexpr constructor; 7113 // -- every non-static data member and base class sub-object shall be 7114 // initialized 7115 // -- for each non-static data member of X that is of class type (or array 7116 // thereof), the assignment operator selected to copy/move that member is 7117 // a constexpr function 7118 for (const auto *F : ClassDecl->fields()) { 7119 if (F->isInvalidDecl()) 7120 continue; 7121 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 7122 continue; 7123 QualType BaseType = S.Context.getBaseElementType(F->getType()); 7124 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 7125 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7126 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 7127 BaseType.getCVRQualifiers(), 7128 ConstArg && !F->isMutable())) 7129 return false; 7130 } else if (CSM == Sema::CXXDefaultConstructor) { 7131 return false; 7132 } 7133 } 7134 7135 // All OK, it's constexpr! 7136 return true; 7137 } 7138 7139 namespace { 7140 /// RAII object to register a defaulted function as having its exception 7141 /// specification computed. 7142 struct ComputingExceptionSpec { 7143 Sema &S; 7144 7145 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 7146 : S(S) { 7147 Sema::CodeSynthesisContext Ctx; 7148 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 7149 Ctx.PointOfInstantiation = Loc; 7150 Ctx.Entity = FD; 7151 S.pushCodeSynthesisContext(Ctx); 7152 } 7153 ~ComputingExceptionSpec() { 7154 S.popCodeSynthesisContext(); 7155 } 7156 }; 7157 } 7158 7159 static Sema::ImplicitExceptionSpecification 7160 ComputeDefaultedSpecialMemberExceptionSpec( 7161 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 7162 Sema::InheritedConstructorInfo *ICI); 7163 7164 static Sema::ImplicitExceptionSpecification 7165 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 7166 FunctionDecl *FD, 7167 Sema::DefaultedComparisonKind DCK); 7168 7169 static Sema::ImplicitExceptionSpecification 7170 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 7171 auto DFK = S.getDefaultedFunctionKind(FD); 7172 if (DFK.isSpecialMember()) 7173 return ComputeDefaultedSpecialMemberExceptionSpec( 7174 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 7175 if (DFK.isComparison()) 7176 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 7177 DFK.asComparison()); 7178 7179 auto *CD = cast<CXXConstructorDecl>(FD); 7180 assert(CD->getInheritedConstructor() && 7181 "only defaulted functions and inherited constructors have implicit " 7182 "exception specs"); 7183 Sema::InheritedConstructorInfo ICI( 7184 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 7185 return ComputeDefaultedSpecialMemberExceptionSpec( 7186 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 7187 } 7188 7189 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 7190 CXXMethodDecl *MD) { 7191 FunctionProtoType::ExtProtoInfo EPI; 7192 7193 // Build an exception specification pointing back at this member. 7194 EPI.ExceptionSpec.Type = EST_Unevaluated; 7195 EPI.ExceptionSpec.SourceDecl = MD; 7196 7197 // Set the calling convention to the default for C++ instance methods. 7198 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 7199 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 7200 /*IsCXXMethod=*/true)); 7201 return EPI; 7202 } 7203 7204 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 7205 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 7206 if (FPT->getExceptionSpecType() != EST_Unevaluated) 7207 return; 7208 7209 // Evaluate the exception specification. 7210 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 7211 auto ESI = IES.getExceptionSpec(); 7212 7213 // Update the type of the special member to use it. 7214 UpdateExceptionSpec(FD, ESI); 7215 } 7216 7217 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 7218 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted"); 7219 7220 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 7221 if (!DefKind) { 7222 assert(FD->getDeclContext()->isDependentContext()); 7223 return; 7224 } 7225 7226 if (DefKind.isSpecialMember() 7227 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 7228 DefKind.asSpecialMember()) 7229 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 7230 FD->setInvalidDecl(); 7231 } 7232 7233 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7234 CXXSpecialMember CSM) { 7235 CXXRecordDecl *RD = MD->getParent(); 7236 7237 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 7238 "not an explicitly-defaulted special member"); 7239 7240 // Defer all checking for special members of a dependent type. 7241 if (RD->isDependentType()) 7242 return false; 7243 7244 // Whether this was the first-declared instance of the constructor. 7245 // This affects whether we implicitly add an exception spec and constexpr. 7246 bool First = MD == MD->getCanonicalDecl(); 7247 7248 bool HadError = false; 7249 7250 // C++11 [dcl.fct.def.default]p1: 7251 // A function that is explicitly defaulted shall 7252 // -- be a special member function [...] (checked elsewhere), 7253 // -- have the same type (except for ref-qualifiers, and except that a 7254 // copy operation can take a non-const reference) as an implicit 7255 // declaration, and 7256 // -- not have default arguments. 7257 // C++2a changes the second bullet to instead delete the function if it's 7258 // defaulted on its first declaration, unless it's "an assignment operator, 7259 // and its return type differs or its parameter type is not a reference". 7260 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First; 7261 bool ShouldDeleteForTypeMismatch = false; 7262 unsigned ExpectedParams = 1; 7263 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 7264 ExpectedParams = 0; 7265 if (MD->getNumParams() != ExpectedParams) { 7266 // This checks for default arguments: a copy or move constructor with a 7267 // default argument is classified as a default constructor, and assignment 7268 // operations and destructors can't have default arguments. 7269 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 7270 << CSM << MD->getSourceRange(); 7271 HadError = true; 7272 } else if (MD->isVariadic()) { 7273 if (DeleteOnTypeMismatch) 7274 ShouldDeleteForTypeMismatch = true; 7275 else { 7276 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 7277 << CSM << MD->getSourceRange(); 7278 HadError = true; 7279 } 7280 } 7281 7282 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 7283 7284 bool CanHaveConstParam = false; 7285 if (CSM == CXXCopyConstructor) 7286 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 7287 else if (CSM == CXXCopyAssignment) 7288 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 7289 7290 QualType ReturnType = Context.VoidTy; 7291 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 7292 // Check for return type matching. 7293 ReturnType = Type->getReturnType(); 7294 7295 QualType DeclType = Context.getTypeDeclType(RD); 7296 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 7297 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 7298 7299 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 7300 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 7301 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 7302 HadError = true; 7303 } 7304 7305 // A defaulted special member cannot have cv-qualifiers. 7306 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 7307 if (DeleteOnTypeMismatch) 7308 ShouldDeleteForTypeMismatch = true; 7309 else { 7310 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 7311 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 7312 HadError = true; 7313 } 7314 } 7315 } 7316 7317 // Check for parameter type matching. 7318 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 7319 bool HasConstParam = false; 7320 if (ExpectedParams && ArgType->isReferenceType()) { 7321 // Argument must be reference to possibly-const T. 7322 QualType ReferentType = ArgType->getPointeeType(); 7323 HasConstParam = ReferentType.isConstQualified(); 7324 7325 if (ReferentType.isVolatileQualified()) { 7326 if (DeleteOnTypeMismatch) 7327 ShouldDeleteForTypeMismatch = true; 7328 else { 7329 Diag(MD->getLocation(), 7330 diag::err_defaulted_special_member_volatile_param) << CSM; 7331 HadError = true; 7332 } 7333 } 7334 7335 if (HasConstParam && !CanHaveConstParam) { 7336 if (DeleteOnTypeMismatch) 7337 ShouldDeleteForTypeMismatch = true; 7338 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7339 Diag(MD->getLocation(), 7340 diag::err_defaulted_special_member_copy_const_param) 7341 << (CSM == CXXCopyAssignment); 7342 // FIXME: Explain why this special member can't be const. 7343 HadError = true; 7344 } else { 7345 Diag(MD->getLocation(), 7346 diag::err_defaulted_special_member_move_const_param) 7347 << (CSM == CXXMoveAssignment); 7348 HadError = true; 7349 } 7350 } 7351 } else if (ExpectedParams) { 7352 // A copy assignment operator can take its argument by value, but a 7353 // defaulted one cannot. 7354 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 7355 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7356 HadError = true; 7357 } 7358 7359 // C++11 [dcl.fct.def.default]p2: 7360 // An explicitly-defaulted function may be declared constexpr only if it 7361 // would have been implicitly declared as constexpr, 7362 // Do not apply this rule to members of class templates, since core issue 1358 7363 // makes such functions always instantiate to constexpr functions. For 7364 // functions which cannot be constexpr (for non-constructors in C++11 and for 7365 // destructors in C++14 and C++17), this is checked elsewhere. 7366 // 7367 // FIXME: This should not apply if the member is deleted. 7368 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7369 HasConstParam); 7370 if ((getLangOpts().CPlusPlus20 || 7371 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7372 : isa<CXXConstructorDecl>(MD))) && 7373 MD->isConstexpr() && !Constexpr && 7374 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7375 Diag(MD->getBeginLoc(), MD->isConsteval() 7376 ? diag::err_incorrect_defaulted_consteval 7377 : diag::err_incorrect_defaulted_constexpr) 7378 << CSM; 7379 // FIXME: Explain why the special member can't be constexpr. 7380 HadError = true; 7381 } 7382 7383 if (First) { 7384 // C++2a [dcl.fct.def.default]p3: 7385 // If a function is explicitly defaulted on its first declaration, it is 7386 // implicitly considered to be constexpr if the implicit declaration 7387 // would be. 7388 MD->setConstexprKind(Constexpr ? (MD->isConsteval() 7389 ? ConstexprSpecKind::Consteval 7390 : ConstexprSpecKind::Constexpr) 7391 : ConstexprSpecKind::Unspecified); 7392 7393 if (!Type->hasExceptionSpec()) { 7394 // C++2a [except.spec]p3: 7395 // If a declaration of a function does not have a noexcept-specifier 7396 // [and] is defaulted on its first declaration, [...] the exception 7397 // specification is as specified below 7398 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7399 EPI.ExceptionSpec.Type = EST_Unevaluated; 7400 EPI.ExceptionSpec.SourceDecl = MD; 7401 MD->setType(Context.getFunctionType(ReturnType, 7402 llvm::makeArrayRef(&ArgType, 7403 ExpectedParams), 7404 EPI)); 7405 } 7406 } 7407 7408 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7409 if (First) { 7410 SetDeclDeleted(MD, MD->getLocation()); 7411 if (!inTemplateInstantiation() && !HadError) { 7412 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7413 if (ShouldDeleteForTypeMismatch) { 7414 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7415 } else { 7416 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7417 } 7418 } 7419 if (ShouldDeleteForTypeMismatch && !HadError) { 7420 Diag(MD->getLocation(), 7421 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7422 } 7423 } else { 7424 // C++11 [dcl.fct.def.default]p4: 7425 // [For a] user-provided explicitly-defaulted function [...] if such a 7426 // function is implicitly defined as deleted, the program is ill-formed. 7427 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7428 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 7429 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7430 HadError = true; 7431 } 7432 } 7433 7434 return HadError; 7435 } 7436 7437 namespace { 7438 /// Helper class for building and checking a defaulted comparison. 7439 /// 7440 /// Defaulted functions are built in two phases: 7441 /// 7442 /// * First, the set of operations that the function will perform are 7443 /// identified, and some of them are checked. If any of the checked 7444 /// operations is invalid in certain ways, the comparison function is 7445 /// defined as deleted and no body is built. 7446 /// * Then, if the function is not defined as deleted, the body is built. 7447 /// 7448 /// This is accomplished by performing two visitation steps over the eventual 7449 /// body of the function. 7450 template<typename Derived, typename ResultList, typename Result, 7451 typename Subobject> 7452 class DefaultedComparisonVisitor { 7453 public: 7454 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7455 7456 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7457 DefaultedComparisonKind DCK) 7458 : S(S), RD(RD), FD(FD), DCK(DCK) { 7459 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7460 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7461 // UnresolvedSet to avoid this copy. 7462 Fns.assign(Info->getUnqualifiedLookups().begin(), 7463 Info->getUnqualifiedLookups().end()); 7464 } 7465 } 7466 7467 ResultList visit() { 7468 // The type of an lvalue naming a parameter of this function. 7469 QualType ParamLvalType = 7470 FD->getParamDecl(0)->getType().getNonReferenceType(); 7471 7472 ResultList Results; 7473 7474 switch (DCK) { 7475 case DefaultedComparisonKind::None: 7476 llvm_unreachable("not a defaulted comparison"); 7477 7478 case DefaultedComparisonKind::Equal: 7479 case DefaultedComparisonKind::ThreeWay: 7480 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7481 return Results; 7482 7483 case DefaultedComparisonKind::NotEqual: 7484 case DefaultedComparisonKind::Relational: 7485 Results.add(getDerived().visitExpandedSubobject( 7486 ParamLvalType, getDerived().getCompleteObject())); 7487 return Results; 7488 } 7489 llvm_unreachable(""); 7490 } 7491 7492 protected: 7493 Derived &getDerived() { return static_cast<Derived&>(*this); } 7494 7495 /// Visit the expanded list of subobjects of the given type, as specified in 7496 /// C++2a [class.compare.default]. 7497 /// 7498 /// \return \c true if the ResultList object said we're done, \c false if not. 7499 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7500 Qualifiers Quals) { 7501 // C++2a [class.compare.default]p4: 7502 // The direct base class subobjects of C 7503 for (CXXBaseSpecifier &Base : Record->bases()) 7504 if (Results.add(getDerived().visitSubobject( 7505 S.Context.getQualifiedType(Base.getType(), Quals), 7506 getDerived().getBase(&Base)))) 7507 return true; 7508 7509 // followed by the non-static data members of C 7510 for (FieldDecl *Field : Record->fields()) { 7511 // Recursively expand anonymous structs. 7512 if (Field->isAnonymousStructOrUnion()) { 7513 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7514 Quals)) 7515 return true; 7516 continue; 7517 } 7518 7519 // Figure out the type of an lvalue denoting this field. 7520 Qualifiers FieldQuals = Quals; 7521 if (Field->isMutable()) 7522 FieldQuals.removeConst(); 7523 QualType FieldType = 7524 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7525 7526 if (Results.add(getDerived().visitSubobject( 7527 FieldType, getDerived().getField(Field)))) 7528 return true; 7529 } 7530 7531 // form a list of subobjects. 7532 return false; 7533 } 7534 7535 Result visitSubobject(QualType Type, Subobject Subobj) { 7536 // In that list, any subobject of array type is recursively expanded 7537 const ArrayType *AT = S.Context.getAsArrayType(Type); 7538 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7539 return getDerived().visitSubobjectArray(CAT->getElementType(), 7540 CAT->getSize(), Subobj); 7541 return getDerived().visitExpandedSubobject(Type, Subobj); 7542 } 7543 7544 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7545 Subobject Subobj) { 7546 return getDerived().visitSubobject(Type, Subobj); 7547 } 7548 7549 protected: 7550 Sema &S; 7551 CXXRecordDecl *RD; 7552 FunctionDecl *FD; 7553 DefaultedComparisonKind DCK; 7554 UnresolvedSet<16> Fns; 7555 }; 7556 7557 /// Information about a defaulted comparison, as determined by 7558 /// DefaultedComparisonAnalyzer. 7559 struct DefaultedComparisonInfo { 7560 bool Deleted = false; 7561 bool Constexpr = true; 7562 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7563 7564 static DefaultedComparisonInfo deleted() { 7565 DefaultedComparisonInfo Deleted; 7566 Deleted.Deleted = true; 7567 return Deleted; 7568 } 7569 7570 bool add(const DefaultedComparisonInfo &R) { 7571 Deleted |= R.Deleted; 7572 Constexpr &= R.Constexpr; 7573 Category = commonComparisonType(Category, R.Category); 7574 return Deleted; 7575 } 7576 }; 7577 7578 /// An element in the expanded list of subobjects of a defaulted comparison, as 7579 /// specified in C++2a [class.compare.default]p4. 7580 struct DefaultedComparisonSubobject { 7581 enum { CompleteObject, Member, Base } Kind; 7582 NamedDecl *Decl; 7583 SourceLocation Loc; 7584 }; 7585 7586 /// A visitor over the notional body of a defaulted comparison that determines 7587 /// whether that body would be deleted or constexpr. 7588 class DefaultedComparisonAnalyzer 7589 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7590 DefaultedComparisonInfo, 7591 DefaultedComparisonInfo, 7592 DefaultedComparisonSubobject> { 7593 public: 7594 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7595 7596 private: 7597 DiagnosticKind Diagnose; 7598 7599 public: 7600 using Base = DefaultedComparisonVisitor; 7601 using Result = DefaultedComparisonInfo; 7602 using Subobject = DefaultedComparisonSubobject; 7603 7604 friend Base; 7605 7606 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7607 DefaultedComparisonKind DCK, 7608 DiagnosticKind Diagnose = NoDiagnostics) 7609 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7610 7611 Result visit() { 7612 if ((DCK == DefaultedComparisonKind::Equal || 7613 DCK == DefaultedComparisonKind::ThreeWay) && 7614 RD->hasVariantMembers()) { 7615 // C++2a [class.compare.default]p2 [P2002R0]: 7616 // A defaulted comparison operator function for class C is defined as 7617 // deleted if [...] C has variant members. 7618 if (Diagnose == ExplainDeleted) { 7619 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7620 << FD << RD->isUnion() << RD; 7621 } 7622 return Result::deleted(); 7623 } 7624 7625 return Base::visit(); 7626 } 7627 7628 private: 7629 Subobject getCompleteObject() { 7630 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()}; 7631 } 7632 7633 Subobject getBase(CXXBaseSpecifier *Base) { 7634 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7635 Base->getBaseTypeLoc()}; 7636 } 7637 7638 Subobject getField(FieldDecl *Field) { 7639 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7640 } 7641 7642 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7643 // C++2a [class.compare.default]p2 [P2002R0]: 7644 // A defaulted <=> or == operator function for class C is defined as 7645 // deleted if any non-static data member of C is of reference type 7646 if (Type->isReferenceType()) { 7647 if (Diagnose == ExplainDeleted) { 7648 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7649 << FD << RD; 7650 } 7651 return Result::deleted(); 7652 } 7653 7654 // [...] Let xi be an lvalue denoting the ith element [...] 7655 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7656 Expr *Args[] = {&Xi, &Xi}; 7657 7658 // All operators start by trying to apply that same operator recursively. 7659 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7660 assert(OO != OO_None && "not an overloaded operator!"); 7661 return visitBinaryOperator(OO, Args, Subobj); 7662 } 7663 7664 Result 7665 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7666 Subobject Subobj, 7667 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7668 // Note that there is no need to consider rewritten candidates here if 7669 // we've already found there is no viable 'operator<=>' candidate (and are 7670 // considering synthesizing a '<=>' from '==' and '<'). 7671 OverloadCandidateSet CandidateSet( 7672 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7673 OverloadCandidateSet::OperatorRewriteInfo( 7674 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7675 7676 /// C++2a [class.compare.default]p1 [P2002R0]: 7677 /// [...] the defaulted function itself is never a candidate for overload 7678 /// resolution [...] 7679 CandidateSet.exclude(FD); 7680 7681 if (Args[0]->getType()->isOverloadableType()) 7682 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7683 else if (OO == OO_EqualEqual || 7684 !Args[0]->getType()->isFunctionPointerType()) { 7685 // FIXME: We determine whether this is a valid expression by checking to 7686 // see if there's a viable builtin operator candidate for it. That isn't 7687 // really what the rules ask us to do, but should give the right results. 7688 // 7689 // Note that the builtin operator for relational comparisons on function 7690 // pointers is the only known case which cannot be used. 7691 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet); 7692 } 7693 7694 Result R; 7695 7696 OverloadCandidateSet::iterator Best; 7697 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7698 case OR_Success: { 7699 // C++2a [class.compare.secondary]p2 [P2002R0]: 7700 // The operator function [...] is defined as deleted if [...] the 7701 // candidate selected by overload resolution is not a rewritten 7702 // candidate. 7703 if ((DCK == DefaultedComparisonKind::NotEqual || 7704 DCK == DefaultedComparisonKind::Relational) && 7705 !Best->RewriteKind) { 7706 if (Diagnose == ExplainDeleted) { 7707 S.Diag(Best->Function->getLocation(), 7708 diag::note_defaulted_comparison_not_rewritten_callee) 7709 << FD; 7710 } 7711 return Result::deleted(); 7712 } 7713 7714 // Throughout C++2a [class.compare]: if overload resolution does not 7715 // result in a usable function, the candidate function is defined as 7716 // deleted. This requires that we selected an accessible function. 7717 // 7718 // Note that this only considers the access of the function when named 7719 // within the type of the subobject, and not the access path for any 7720 // derived-to-base conversion. 7721 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7722 if (ArgClass && Best->FoundDecl.getDecl() && 7723 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7724 QualType ObjectType = Subobj.Kind == Subobject::Member 7725 ? Args[0]->getType() 7726 : S.Context.getRecordType(RD); 7727 if (!S.isMemberAccessibleForDeletion( 7728 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7729 Diagnose == ExplainDeleted 7730 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7731 << FD << Subobj.Kind << Subobj.Decl 7732 : S.PDiag())) 7733 return Result::deleted(); 7734 } 7735 7736 // C++2a [class.compare.default]p3 [P2002R0]: 7737 // A defaulted comparison function is constexpr-compatible if [...] 7738 // no overlod resolution performed [...] results in a non-constexpr 7739 // function. 7740 if (FunctionDecl *BestFD = Best->Function) { 7741 assert(!BestFD->isDeleted() && "wrong overload resolution result"); 7742 // If it's not constexpr, explain why not. 7743 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 7744 if (Subobj.Kind != Subobject::CompleteObject) 7745 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7746 << Subobj.Kind << Subobj.Decl; 7747 S.Diag(BestFD->getLocation(), 7748 diag::note_defaulted_comparison_not_constexpr_here); 7749 // Bail out after explaining; we don't want any more notes. 7750 return Result::deleted(); 7751 } 7752 R.Constexpr &= BestFD->isConstexpr(); 7753 } 7754 7755 if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) { 7756 if (auto *BestFD = Best->Function) { 7757 // If any callee has an undeduced return type, deduce it now. 7758 // FIXME: It's not clear how a failure here should be handled. For 7759 // now, we produce an eager diagnostic, because that is forward 7760 // compatible with most (all?) other reasonable options. 7761 if (BestFD->getReturnType()->isUndeducedType() && 7762 S.DeduceReturnType(BestFD, FD->getLocation(), 7763 /*Diagnose=*/false)) { 7764 // Don't produce a duplicate error when asked to explain why the 7765 // comparison is deleted: we diagnosed that when initially checking 7766 // the defaulted operator. 7767 if (Diagnose == NoDiagnostics) { 7768 S.Diag( 7769 FD->getLocation(), 7770 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) 7771 << Subobj.Kind << Subobj.Decl; 7772 S.Diag( 7773 Subobj.Loc, 7774 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) 7775 << Subobj.Kind << Subobj.Decl; 7776 S.Diag(BestFD->getLocation(), 7777 diag::note_defaulted_comparison_cannot_deduce_callee) 7778 << Subobj.Kind << Subobj.Decl; 7779 } 7780 return Result::deleted(); 7781 } 7782 if (auto *Info = S.Context.CompCategories.lookupInfoForType( 7783 BestFD->getCallResultType())) { 7784 R.Category = Info->Kind; 7785 } else { 7786 if (Diagnose == ExplainDeleted) { 7787 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 7788 << Subobj.Kind << Subobj.Decl 7789 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 7790 S.Diag(BestFD->getLocation(), 7791 diag::note_defaulted_comparison_cannot_deduce_callee) 7792 << Subobj.Kind << Subobj.Decl; 7793 } 7794 return Result::deleted(); 7795 } 7796 } else { 7797 Optional<ComparisonCategoryType> Cat = 7798 getComparisonCategoryForBuiltinCmp(Args[0]->getType()); 7799 assert(Cat && "no category for builtin comparison?"); 7800 R.Category = *Cat; 7801 } 7802 } 7803 7804 // Note that we might be rewriting to a different operator. That call is 7805 // not considered until we come to actually build the comparison function. 7806 break; 7807 } 7808 7809 case OR_Ambiguous: 7810 if (Diagnose == ExplainDeleted) { 7811 unsigned Kind = 0; 7812 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 7813 Kind = OO == OO_EqualEqual ? 1 : 2; 7814 CandidateSet.NoteCandidates( 7815 PartialDiagnosticAt( 7816 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 7817 << FD << Kind << Subobj.Kind << Subobj.Decl), 7818 S, OCD_AmbiguousCandidates, Args); 7819 } 7820 R = Result::deleted(); 7821 break; 7822 7823 case OR_Deleted: 7824 if (Diagnose == ExplainDeleted) { 7825 if ((DCK == DefaultedComparisonKind::NotEqual || 7826 DCK == DefaultedComparisonKind::Relational) && 7827 !Best->RewriteKind) { 7828 S.Diag(Best->Function->getLocation(), 7829 diag::note_defaulted_comparison_not_rewritten_callee) 7830 << FD; 7831 } else { 7832 S.Diag(Subobj.Loc, 7833 diag::note_defaulted_comparison_calls_deleted) 7834 << FD << Subobj.Kind << Subobj.Decl; 7835 S.NoteDeletedFunction(Best->Function); 7836 } 7837 } 7838 R = Result::deleted(); 7839 break; 7840 7841 case OR_No_Viable_Function: 7842 // If there's no usable candidate, we're done unless we can rewrite a 7843 // '<=>' in terms of '==' and '<'. 7844 if (OO == OO_Spaceship && 7845 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 7846 // For any kind of comparison category return type, we need a usable 7847 // '==' and a usable '<'. 7848 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 7849 &CandidateSet))) 7850 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 7851 break; 7852 } 7853 7854 if (Diagnose == ExplainDeleted) { 7855 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 7856 << FD << Subobj.Kind << Subobj.Decl; 7857 7858 // For a three-way comparison, list both the candidates for the 7859 // original operator and the candidates for the synthesized operator. 7860 if (SpaceshipCandidates) { 7861 SpaceshipCandidates->NoteCandidates( 7862 S, Args, 7863 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 7864 Args, FD->getLocation())); 7865 S.Diag(Subobj.Loc, 7866 diag::note_defaulted_comparison_no_viable_function_synthesized) 7867 << (OO == OO_EqualEqual ? 0 : 1); 7868 } 7869 7870 CandidateSet.NoteCandidates( 7871 S, Args, 7872 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 7873 FD->getLocation())); 7874 } 7875 R = Result::deleted(); 7876 break; 7877 } 7878 7879 return R; 7880 } 7881 }; 7882 7883 /// A list of statements. 7884 struct StmtListResult { 7885 bool IsInvalid = false; 7886 llvm::SmallVector<Stmt*, 16> Stmts; 7887 7888 bool add(const StmtResult &S) { 7889 IsInvalid |= S.isInvalid(); 7890 if (IsInvalid) 7891 return true; 7892 Stmts.push_back(S.get()); 7893 return false; 7894 } 7895 }; 7896 7897 /// A visitor over the notional body of a defaulted comparison that synthesizes 7898 /// the actual body. 7899 class DefaultedComparisonSynthesizer 7900 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 7901 StmtListResult, StmtResult, 7902 std::pair<ExprResult, ExprResult>> { 7903 SourceLocation Loc; 7904 unsigned ArrayDepth = 0; 7905 7906 public: 7907 using Base = DefaultedComparisonVisitor; 7908 using ExprPair = std::pair<ExprResult, ExprResult>; 7909 7910 friend Base; 7911 7912 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7913 DefaultedComparisonKind DCK, 7914 SourceLocation BodyLoc) 7915 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 7916 7917 /// Build a suitable function body for this defaulted comparison operator. 7918 StmtResult build() { 7919 Sema::CompoundScopeRAII CompoundScope(S); 7920 7921 StmtListResult Stmts = visit(); 7922 if (Stmts.IsInvalid) 7923 return StmtError(); 7924 7925 ExprResult RetVal; 7926 switch (DCK) { 7927 case DefaultedComparisonKind::None: 7928 llvm_unreachable("not a defaulted comparison"); 7929 7930 case DefaultedComparisonKind::Equal: { 7931 // C++2a [class.eq]p3: 7932 // [...] compar[e] the corresponding elements [...] until the first 7933 // index i where xi == yi yields [...] false. If no such index exists, 7934 // V is true. Otherwise, V is false. 7935 // 7936 // Join the comparisons with '&&'s and return the result. Use a right 7937 // fold (traversing the conditions right-to-left), because that 7938 // short-circuits more naturally. 7939 auto OldStmts = std::move(Stmts.Stmts); 7940 Stmts.Stmts.clear(); 7941 ExprResult CmpSoFar; 7942 // Finish a particular comparison chain. 7943 auto FinishCmp = [&] { 7944 if (Expr *Prior = CmpSoFar.get()) { 7945 // Convert the last expression to 'return ...;' 7946 if (RetVal.isUnset() && Stmts.Stmts.empty()) 7947 RetVal = CmpSoFar; 7948 // Convert any prior comparison to 'if (!(...)) return false;' 7949 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 7950 return true; 7951 CmpSoFar = ExprResult(); 7952 } 7953 return false; 7954 }; 7955 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 7956 Expr *E = dyn_cast<Expr>(EAsStmt); 7957 if (!E) { 7958 // Found an array comparison. 7959 if (FinishCmp() || Stmts.add(EAsStmt)) 7960 return StmtError(); 7961 continue; 7962 } 7963 7964 if (CmpSoFar.isUnset()) { 7965 CmpSoFar = E; 7966 continue; 7967 } 7968 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 7969 if (CmpSoFar.isInvalid()) 7970 return StmtError(); 7971 } 7972 if (FinishCmp()) 7973 return StmtError(); 7974 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 7975 // If no such index exists, V is true. 7976 if (RetVal.isUnset()) 7977 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 7978 break; 7979 } 7980 7981 case DefaultedComparisonKind::ThreeWay: { 7982 // Per C++2a [class.spaceship]p3, as a fallback add: 7983 // return static_cast<R>(std::strong_ordering::equal); 7984 QualType StrongOrdering = S.CheckComparisonCategoryType( 7985 ComparisonCategoryType::StrongOrdering, Loc, 7986 Sema::ComparisonCategoryUsage::DefaultedOperator); 7987 if (StrongOrdering.isNull()) 7988 return StmtError(); 7989 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 7990 .getValueInfo(ComparisonCategoryResult::Equal) 7991 ->VD; 7992 RetVal = getDecl(EqualVD); 7993 if (RetVal.isInvalid()) 7994 return StmtError(); 7995 RetVal = buildStaticCastToR(RetVal.get()); 7996 break; 7997 } 7998 7999 case DefaultedComparisonKind::NotEqual: 8000 case DefaultedComparisonKind::Relational: 8001 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 8002 break; 8003 } 8004 8005 // Build the final return statement. 8006 if (RetVal.isInvalid()) 8007 return StmtError(); 8008 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 8009 if (ReturnStmt.isInvalid()) 8010 return StmtError(); 8011 Stmts.Stmts.push_back(ReturnStmt.get()); 8012 8013 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 8014 } 8015 8016 private: 8017 ExprResult getDecl(ValueDecl *VD) { 8018 return S.BuildDeclarationNameExpr( 8019 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 8020 } 8021 8022 ExprResult getParam(unsigned I) { 8023 ParmVarDecl *PD = FD->getParamDecl(I); 8024 return getDecl(PD); 8025 } 8026 8027 ExprPair getCompleteObject() { 8028 unsigned Param = 0; 8029 ExprResult LHS; 8030 if (isa<CXXMethodDecl>(FD)) { 8031 // LHS is '*this'. 8032 LHS = S.ActOnCXXThis(Loc); 8033 if (!LHS.isInvalid()) 8034 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 8035 } else { 8036 LHS = getParam(Param++); 8037 } 8038 ExprResult RHS = getParam(Param++); 8039 assert(Param == FD->getNumParams()); 8040 return {LHS, RHS}; 8041 } 8042 8043 ExprPair getBase(CXXBaseSpecifier *Base) { 8044 ExprPair Obj = getCompleteObject(); 8045 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8046 return {ExprError(), ExprError()}; 8047 CXXCastPath Path = {Base}; 8048 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 8049 CK_DerivedToBase, VK_LValue, &Path), 8050 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 8051 CK_DerivedToBase, VK_LValue, &Path)}; 8052 } 8053 8054 ExprPair getField(FieldDecl *Field) { 8055 ExprPair Obj = getCompleteObject(); 8056 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8057 return {ExprError(), ExprError()}; 8058 8059 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 8060 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 8061 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 8062 CXXScopeSpec(), Field, Found, NameInfo), 8063 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 8064 CXXScopeSpec(), Field, Found, NameInfo)}; 8065 } 8066 8067 // FIXME: When expanding a subobject, register a note in the code synthesis 8068 // stack to say which subobject we're comparing. 8069 8070 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 8071 if (Cond.isInvalid()) 8072 return StmtError(); 8073 8074 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 8075 if (NotCond.isInvalid()) 8076 return StmtError(); 8077 8078 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 8079 assert(!False.isInvalid() && "should never fail"); 8080 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 8081 if (ReturnFalse.isInvalid()) 8082 return StmtError(); 8083 8084 return S.ActOnIfStmt(Loc, false, Loc, nullptr, 8085 S.ActOnCondition(nullptr, Loc, NotCond.get(), 8086 Sema::ConditionKind::Boolean), 8087 Loc, ReturnFalse.get(), SourceLocation(), nullptr); 8088 } 8089 8090 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 8091 ExprPair Subobj) { 8092 QualType SizeType = S.Context.getSizeType(); 8093 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 8094 8095 // Build 'size_t i$n = 0'. 8096 IdentifierInfo *IterationVarName = nullptr; 8097 { 8098 SmallString<8> Str; 8099 llvm::raw_svector_ostream OS(Str); 8100 OS << "i" << ArrayDepth; 8101 IterationVarName = &S.Context.Idents.get(OS.str()); 8102 } 8103 VarDecl *IterationVar = VarDecl::Create( 8104 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 8105 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 8106 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8107 IterationVar->setInit( 8108 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8109 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 8110 8111 auto IterRef = [&] { 8112 ExprResult Ref = S.BuildDeclarationNameExpr( 8113 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 8114 IterationVar); 8115 assert(!Ref.isInvalid() && "can't reference our own variable?"); 8116 return Ref.get(); 8117 }; 8118 8119 // Build 'i$n != Size'. 8120 ExprResult Cond = S.CreateBuiltinBinOp( 8121 Loc, BO_NE, IterRef(), 8122 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 8123 assert(!Cond.isInvalid() && "should never fail"); 8124 8125 // Build '++i$n'. 8126 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 8127 assert(!Inc.isInvalid() && "should never fail"); 8128 8129 // Build 'a[i$n]' and 'b[i$n]'. 8130 auto Index = [&](ExprResult E) { 8131 if (E.isInvalid()) 8132 return ExprError(); 8133 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 8134 }; 8135 Subobj.first = Index(Subobj.first); 8136 Subobj.second = Index(Subobj.second); 8137 8138 // Compare the array elements. 8139 ++ArrayDepth; 8140 StmtResult Substmt = visitSubobject(Type, Subobj); 8141 --ArrayDepth; 8142 8143 if (Substmt.isInvalid()) 8144 return StmtError(); 8145 8146 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 8147 // For outer levels or for an 'operator<=>' we already have a suitable 8148 // statement that returns as necessary. 8149 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 8150 assert(DCK == DefaultedComparisonKind::Equal && 8151 "should have non-expression statement"); 8152 Substmt = buildIfNotCondReturnFalse(ElemCmp); 8153 if (Substmt.isInvalid()) 8154 return StmtError(); 8155 } 8156 8157 // Build 'for (...) ...' 8158 return S.ActOnForStmt(Loc, Loc, Init, 8159 S.ActOnCondition(nullptr, Loc, Cond.get(), 8160 Sema::ConditionKind::Boolean), 8161 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 8162 Substmt.get()); 8163 } 8164 8165 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 8166 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8167 return StmtError(); 8168 8169 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 8170 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); 8171 ExprResult Op; 8172 if (Type->isOverloadableType()) 8173 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(), 8174 Obj.second.get(), /*PerformADL=*/true, 8175 /*AllowRewrittenCandidates=*/true, FD); 8176 else 8177 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get()); 8178 if (Op.isInvalid()) 8179 return StmtError(); 8180 8181 switch (DCK) { 8182 case DefaultedComparisonKind::None: 8183 llvm_unreachable("not a defaulted comparison"); 8184 8185 case DefaultedComparisonKind::Equal: 8186 // Per C++2a [class.eq]p2, each comparison is individually contextually 8187 // converted to bool. 8188 Op = S.PerformContextuallyConvertToBool(Op.get()); 8189 if (Op.isInvalid()) 8190 return StmtError(); 8191 return Op.get(); 8192 8193 case DefaultedComparisonKind::ThreeWay: { 8194 // Per C++2a [class.spaceship]p3, form: 8195 // if (R cmp = static_cast<R>(op); cmp != 0) 8196 // return cmp; 8197 QualType R = FD->getReturnType(); 8198 Op = buildStaticCastToR(Op.get()); 8199 if (Op.isInvalid()) 8200 return StmtError(); 8201 8202 // R cmp = ...; 8203 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 8204 VarDecl *VD = 8205 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 8206 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 8207 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 8208 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 8209 8210 // cmp != 0 8211 ExprResult VDRef = getDecl(VD); 8212 if (VDRef.isInvalid()) 8213 return StmtError(); 8214 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 8215 Expr *Zero = 8216 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 8217 ExprResult Comp; 8218 if (VDRef.get()->getType()->isOverloadableType()) 8219 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true, 8220 true, FD); 8221 else 8222 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero); 8223 if (Comp.isInvalid()) 8224 return StmtError(); 8225 Sema::ConditionResult Cond = S.ActOnCondition( 8226 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 8227 if (Cond.isInvalid()) 8228 return StmtError(); 8229 8230 // return cmp; 8231 VDRef = getDecl(VD); 8232 if (VDRef.isInvalid()) 8233 return StmtError(); 8234 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 8235 if (ReturnStmt.isInvalid()) 8236 return StmtError(); 8237 8238 // if (...) 8239 return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc, 8240 ReturnStmt.get(), 8241 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr); 8242 } 8243 8244 case DefaultedComparisonKind::NotEqual: 8245 case DefaultedComparisonKind::Relational: 8246 // C++2a [class.compare.secondary]p2: 8247 // Otherwise, the operator function yields x @ y. 8248 return Op.get(); 8249 } 8250 llvm_unreachable(""); 8251 } 8252 8253 /// Build "static_cast<R>(E)". 8254 ExprResult buildStaticCastToR(Expr *E) { 8255 QualType R = FD->getReturnType(); 8256 assert(!R->isUndeducedType() && "type should have been deduced already"); 8257 8258 // Don't bother forming a no-op cast in the common case. 8259 if (E->isRValue() && S.Context.hasSameType(E->getType(), R)) 8260 return E; 8261 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 8262 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 8263 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 8264 } 8265 }; 8266 } 8267 8268 /// Perform the unqualified lookups that might be needed to form a defaulted 8269 /// comparison function for the given operator. 8270 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 8271 UnresolvedSetImpl &Operators, 8272 OverloadedOperatorKind Op) { 8273 auto Lookup = [&](OverloadedOperatorKind OO) { 8274 Self.LookupOverloadedOperatorName(OO, S, Operators); 8275 }; 8276 8277 // Every defaulted operator looks up itself. 8278 Lookup(Op); 8279 // ... and the rewritten form of itself, if any. 8280 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 8281 Lookup(ExtraOp); 8282 8283 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 8284 // synthesize a three-way comparison from '<' and '=='. In a dependent 8285 // context, we also need to look up '==' in case we implicitly declare a 8286 // defaulted 'operator=='. 8287 if (Op == OO_Spaceship) { 8288 Lookup(OO_ExclaimEqual); 8289 Lookup(OO_Less); 8290 Lookup(OO_EqualEqual); 8291 } 8292 } 8293 8294 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 8295 DefaultedComparisonKind DCK) { 8296 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison"); 8297 8298 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 8299 assert(RD && "defaulted comparison is not defaulted in a class"); 8300 8301 // Perform any unqualified lookups we're going to need to default this 8302 // function. 8303 if (S) { 8304 UnresolvedSet<32> Operators; 8305 lookupOperatorsForDefaultedComparison(*this, S, Operators, 8306 FD->getOverloadedOperator()); 8307 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 8308 Context, Operators.pairs())); 8309 } 8310 8311 // C++2a [class.compare.default]p1: 8312 // A defaulted comparison operator function for some class C shall be a 8313 // non-template function declared in the member-specification of C that is 8314 // -- a non-static const member of C having one parameter of type 8315 // const C&, or 8316 // -- a friend of C having two parameters of type const C& or two 8317 // parameters of type C. 8318 QualType ExpectedParmType1 = Context.getRecordType(RD); 8319 QualType ExpectedParmType2 = 8320 Context.getLValueReferenceType(ExpectedParmType1.withConst()); 8321 if (isa<CXXMethodDecl>(FD)) 8322 ExpectedParmType1 = ExpectedParmType2; 8323 for (const ParmVarDecl *Param : FD->parameters()) { 8324 if (!Param->getType()->isDependentType() && 8325 !Context.hasSameType(Param->getType(), ExpectedParmType1) && 8326 !Context.hasSameType(Param->getType(), ExpectedParmType2)) { 8327 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8328 // corresponding defaulted 'operator<=>' already. 8329 if (!FD->isImplicit()) { 8330 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 8331 << (int)DCK << Param->getType() << ExpectedParmType1 8332 << !isa<CXXMethodDecl>(FD) 8333 << ExpectedParmType2 << Param->getSourceRange(); 8334 } 8335 return true; 8336 } 8337 } 8338 if (FD->getNumParams() == 2 && 8339 !Context.hasSameType(FD->getParamDecl(0)->getType(), 8340 FD->getParamDecl(1)->getType())) { 8341 if (!FD->isImplicit()) { 8342 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 8343 << (int)DCK 8344 << FD->getParamDecl(0)->getType() 8345 << FD->getParamDecl(0)->getSourceRange() 8346 << FD->getParamDecl(1)->getType() 8347 << FD->getParamDecl(1)->getSourceRange(); 8348 } 8349 return true; 8350 } 8351 8352 // ... non-static const member ... 8353 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 8354 assert(!MD->isStatic() && "comparison function cannot be a static member"); 8355 if (!MD->isConst()) { 8356 SourceLocation InsertLoc; 8357 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 8358 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 8359 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8360 // corresponding defaulted 'operator<=>' already. 8361 if (!MD->isImplicit()) { 8362 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 8363 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 8364 } 8365 8366 // Add the 'const' to the type to recover. 8367 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 8368 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8369 EPI.TypeQuals.addConst(); 8370 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8371 FPT->getParamTypes(), EPI)); 8372 } 8373 } else { 8374 // A non-member function declared in a class must be a friend. 8375 assert(FD->getFriendObjectKind() && "expected a friend declaration"); 8376 } 8377 8378 // C++2a [class.eq]p1, [class.rel]p1: 8379 // A [defaulted comparison other than <=>] shall have a declared return 8380 // type bool. 8381 if (DCK != DefaultedComparisonKind::ThreeWay && 8382 !FD->getDeclaredReturnType()->isDependentType() && 8383 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8384 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8385 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8386 << FD->getReturnTypeSourceRange(); 8387 return true; 8388 } 8389 // C++2a [class.spaceship]p2 [P2002R0]: 8390 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8391 // R shall not contain a placeholder type. 8392 if (DCK == DefaultedComparisonKind::ThreeWay && 8393 FD->getDeclaredReturnType()->getContainedDeducedType() && 8394 !Context.hasSameType(FD->getDeclaredReturnType(), 8395 Context.getAutoDeductType())) { 8396 Diag(FD->getLocation(), 8397 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8398 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8399 << FD->getReturnTypeSourceRange(); 8400 return true; 8401 } 8402 8403 // For a defaulted function in a dependent class, defer all remaining checks 8404 // until instantiation. 8405 if (RD->isDependentType()) 8406 return false; 8407 8408 // Determine whether the function should be defined as deleted. 8409 DefaultedComparisonInfo Info = 8410 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8411 8412 bool First = FD == FD->getCanonicalDecl(); 8413 8414 // If we want to delete the function, then do so; there's nothing else to 8415 // check in that case. 8416 if (Info.Deleted) { 8417 if (!First) { 8418 // C++11 [dcl.fct.def.default]p4: 8419 // [For a] user-provided explicitly-defaulted function [...] if such a 8420 // function is implicitly defined as deleted, the program is ill-formed. 8421 // 8422 // This is really just a consequence of the general rule that you can 8423 // only delete a function on its first declaration. 8424 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8425 << FD->isImplicit() << (int)DCK; 8426 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8427 DefaultedComparisonAnalyzer::ExplainDeleted) 8428 .visit(); 8429 return true; 8430 } 8431 8432 SetDeclDeleted(FD, FD->getLocation()); 8433 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8434 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8435 << (int)DCK; 8436 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8437 DefaultedComparisonAnalyzer::ExplainDeleted) 8438 .visit(); 8439 } 8440 return false; 8441 } 8442 8443 // C++2a [class.spaceship]p2: 8444 // The return type is deduced as the common comparison type of R0, R1, ... 8445 if (DCK == DefaultedComparisonKind::ThreeWay && 8446 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8447 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8448 if (RetLoc.isInvalid()) 8449 RetLoc = FD->getBeginLoc(); 8450 // FIXME: Should we really care whether we have the complete type and the 8451 // 'enumerator' constants here? A forward declaration seems sufficient. 8452 QualType Cat = CheckComparisonCategoryType( 8453 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8454 if (Cat.isNull()) 8455 return true; 8456 Context.adjustDeducedFunctionResultType( 8457 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8458 } 8459 8460 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8461 // An explicitly-defaulted function that is not defined as deleted may be 8462 // declared constexpr or consteval only if it is constexpr-compatible. 8463 // C++2a [class.compare.default]p3 [P2002R0]: 8464 // A defaulted comparison function is constexpr-compatible if it satisfies 8465 // the requirements for a constexpr function [...] 8466 // The only relevant requirements are that the parameter and return types are 8467 // literal types. The remaining conditions are checked by the analyzer. 8468 if (FD->isConstexpr()) { 8469 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8470 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8471 !Info.Constexpr) { 8472 Diag(FD->getBeginLoc(), 8473 diag::err_incorrect_defaulted_comparison_constexpr) 8474 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8475 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8476 DefaultedComparisonAnalyzer::ExplainConstexpr) 8477 .visit(); 8478 } 8479 } 8480 8481 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8482 // If a constexpr-compatible function is explicitly defaulted on its first 8483 // declaration, it is implicitly considered to be constexpr. 8484 // FIXME: Only applying this to the first declaration seems problematic, as 8485 // simple reorderings can affect the meaning of the program. 8486 if (First && !FD->isConstexpr() && Info.Constexpr) 8487 FD->setConstexprKind(ConstexprSpecKind::Constexpr); 8488 8489 // C++2a [except.spec]p3: 8490 // If a declaration of a function does not have a noexcept-specifier 8491 // [and] is defaulted on its first declaration, [...] the exception 8492 // specification is as specified below 8493 if (FD->getExceptionSpecType() == EST_None) { 8494 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8495 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8496 EPI.ExceptionSpec.Type = EST_Unevaluated; 8497 EPI.ExceptionSpec.SourceDecl = FD; 8498 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8499 FPT->getParamTypes(), EPI)); 8500 } 8501 8502 return false; 8503 } 8504 8505 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8506 FunctionDecl *Spaceship) { 8507 Sema::CodeSynthesisContext Ctx; 8508 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8509 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8510 Ctx.Entity = Spaceship; 8511 pushCodeSynthesisContext(Ctx); 8512 8513 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8514 EqualEqual->setImplicit(); 8515 8516 popCodeSynthesisContext(); 8517 } 8518 8519 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8520 DefaultedComparisonKind DCK) { 8521 assert(FD->isDefaulted() && !FD->isDeleted() && 8522 !FD->doesThisDeclarationHaveABody()); 8523 if (FD->willHaveBody() || FD->isInvalidDecl()) 8524 return; 8525 8526 SynthesizedFunctionScope Scope(*this, FD); 8527 8528 // Add a context note for diagnostics produced after this point. 8529 Scope.addContextNote(UseLoc); 8530 8531 { 8532 // Build and set up the function body. 8533 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8534 SourceLocation BodyLoc = 8535 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8536 StmtResult Body = 8537 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8538 if (Body.isInvalid()) { 8539 FD->setInvalidDecl(); 8540 return; 8541 } 8542 FD->setBody(Body.get()); 8543 FD->markUsed(Context); 8544 } 8545 8546 // The exception specification is needed because we are defining the 8547 // function. Note that this will reuse the body we just built. 8548 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8549 8550 if (ASTMutationListener *L = getASTMutationListener()) 8551 L->CompletedImplicitDefinition(FD); 8552 } 8553 8554 static Sema::ImplicitExceptionSpecification 8555 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8556 FunctionDecl *FD, 8557 Sema::DefaultedComparisonKind DCK) { 8558 ComputingExceptionSpec CES(S, FD, Loc); 8559 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8560 8561 if (FD->isInvalidDecl()) 8562 return ExceptSpec; 8563 8564 // The common case is that we just defined the comparison function. In that 8565 // case, just look at whether the body can throw. 8566 if (FD->hasBody()) { 8567 ExceptSpec.CalledStmt(FD->getBody()); 8568 } else { 8569 // Otherwise, build a body so we can check it. This should ideally only 8570 // happen when we're not actually marking the function referenced. (This is 8571 // only really important for efficiency: we don't want to build and throw 8572 // away bodies for comparison functions more than we strictly need to.) 8573 8574 // Pretend to synthesize the function body in an unevaluated context. 8575 // Note that we can't actually just go ahead and define the function here: 8576 // we are not permitted to mark its callees as referenced. 8577 Sema::SynthesizedFunctionScope Scope(S, FD); 8578 EnterExpressionEvaluationContext Context( 8579 S, Sema::ExpressionEvaluationContext::Unevaluated); 8580 8581 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8582 SourceLocation BodyLoc = 8583 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8584 StmtResult Body = 8585 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8586 if (!Body.isInvalid()) 8587 ExceptSpec.CalledStmt(Body.get()); 8588 8589 // FIXME: Can we hold onto this body and just transform it to potentially 8590 // evaluated when we're asked to define the function rather than rebuilding 8591 // it? Either that, or we should only build the bits of the body that we 8592 // need (the expressions, not the statements). 8593 } 8594 8595 return ExceptSpec; 8596 } 8597 8598 void Sema::CheckDelayedMemberExceptionSpecs() { 8599 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8600 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8601 8602 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8603 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8604 8605 // Perform any deferred checking of exception specifications for virtual 8606 // destructors. 8607 for (auto &Check : Overriding) 8608 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8609 8610 // Perform any deferred checking of exception specifications for befriended 8611 // special members. 8612 for (auto &Check : Equivalent) 8613 CheckEquivalentExceptionSpec(Check.second, Check.first); 8614 } 8615 8616 namespace { 8617 /// CRTP base class for visiting operations performed by a special member 8618 /// function (or inherited constructor). 8619 template<typename Derived> 8620 struct SpecialMemberVisitor { 8621 Sema &S; 8622 CXXMethodDecl *MD; 8623 Sema::CXXSpecialMember CSM; 8624 Sema::InheritedConstructorInfo *ICI; 8625 8626 // Properties of the special member, computed for convenience. 8627 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8628 8629 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8630 Sema::InheritedConstructorInfo *ICI) 8631 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8632 switch (CSM) { 8633 case Sema::CXXDefaultConstructor: 8634 case Sema::CXXCopyConstructor: 8635 case Sema::CXXMoveConstructor: 8636 IsConstructor = true; 8637 break; 8638 case Sema::CXXCopyAssignment: 8639 case Sema::CXXMoveAssignment: 8640 IsAssignment = true; 8641 break; 8642 case Sema::CXXDestructor: 8643 break; 8644 case Sema::CXXInvalid: 8645 llvm_unreachable("invalid special member kind"); 8646 } 8647 8648 if (MD->getNumParams()) { 8649 if (const ReferenceType *RT = 8650 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8651 ConstArg = RT->getPointeeType().isConstQualified(); 8652 } 8653 } 8654 8655 Derived &getDerived() { return static_cast<Derived&>(*this); } 8656 8657 /// Is this a "move" special member? 8658 bool isMove() const { 8659 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8660 } 8661 8662 /// Look up the corresponding special member in the given class. 8663 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8664 unsigned Quals, bool IsMutable) { 8665 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8666 ConstArg && !IsMutable); 8667 } 8668 8669 /// Look up the constructor for the specified base class to see if it's 8670 /// overridden due to this being an inherited constructor. 8671 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8672 if (!ICI) 8673 return {}; 8674 assert(CSM == Sema::CXXDefaultConstructor); 8675 auto *BaseCtor = 8676 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8677 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8678 return MD; 8679 return {}; 8680 } 8681 8682 /// A base or member subobject. 8683 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8684 8685 /// Get the location to use for a subobject in diagnostics. 8686 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8687 // FIXME: For an indirect virtual base, the direct base leading to 8688 // the indirect virtual base would be a more useful choice. 8689 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8690 return B->getBaseTypeLoc(); 8691 else 8692 return Subobj.get<FieldDecl*>()->getLocation(); 8693 } 8694 8695 enum BasesToVisit { 8696 /// Visit all non-virtual (direct) bases. 8697 VisitNonVirtualBases, 8698 /// Visit all direct bases, virtual or not. 8699 VisitDirectBases, 8700 /// Visit all non-virtual bases, and all virtual bases if the class 8701 /// is not abstract. 8702 VisitPotentiallyConstructedBases, 8703 /// Visit all direct or virtual bases. 8704 VisitAllBases 8705 }; 8706 8707 // Visit the bases and members of the class. 8708 bool visit(BasesToVisit Bases) { 8709 CXXRecordDecl *RD = MD->getParent(); 8710 8711 if (Bases == VisitPotentiallyConstructedBases) 8712 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8713 8714 for (auto &B : RD->bases()) 8715 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8716 getDerived().visitBase(&B)) 8717 return true; 8718 8719 if (Bases == VisitAllBases) 8720 for (auto &B : RD->vbases()) 8721 if (getDerived().visitBase(&B)) 8722 return true; 8723 8724 for (auto *F : RD->fields()) 8725 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8726 getDerived().visitField(F)) 8727 return true; 8728 8729 return false; 8730 } 8731 }; 8732 } 8733 8734 namespace { 8735 struct SpecialMemberDeletionInfo 8736 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8737 bool Diagnose; 8738 8739 SourceLocation Loc; 8740 8741 bool AllFieldsAreConst; 8742 8743 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 8744 Sema::CXXSpecialMember CSM, 8745 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 8746 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 8747 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 8748 8749 bool inUnion() const { return MD->getParent()->isUnion(); } 8750 8751 Sema::CXXSpecialMember getEffectiveCSM() { 8752 return ICI ? Sema::CXXInvalid : CSM; 8753 } 8754 8755 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 8756 8757 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 8758 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 8759 8760 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 8761 bool shouldDeleteForField(FieldDecl *FD); 8762 bool shouldDeleteForAllConstMembers(); 8763 8764 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 8765 unsigned Quals); 8766 bool shouldDeleteForSubobjectCall(Subobject Subobj, 8767 Sema::SpecialMemberOverloadResult SMOR, 8768 bool IsDtorCallInCtor); 8769 8770 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 8771 }; 8772 } 8773 8774 /// Is the given special member inaccessible when used on the given 8775 /// sub-object. 8776 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 8777 CXXMethodDecl *target) { 8778 /// If we're operating on a base class, the object type is the 8779 /// type of this special member. 8780 QualType objectTy; 8781 AccessSpecifier access = target->getAccess(); 8782 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 8783 objectTy = S.Context.getTypeDeclType(MD->getParent()); 8784 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 8785 8786 // If we're operating on a field, the object type is the type of the field. 8787 } else { 8788 objectTy = S.Context.getTypeDeclType(target->getParent()); 8789 } 8790 8791 return S.isMemberAccessibleForDeletion( 8792 target->getParent(), DeclAccessPair::make(target, access), objectTy); 8793 } 8794 8795 /// Check whether we should delete a special member due to the implicit 8796 /// definition containing a call to a special member of a subobject. 8797 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 8798 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 8799 bool IsDtorCallInCtor) { 8800 CXXMethodDecl *Decl = SMOR.getMethod(); 8801 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8802 8803 int DiagKind = -1; 8804 8805 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 8806 DiagKind = !Decl ? 0 : 1; 8807 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 8808 DiagKind = 2; 8809 else if (!isAccessible(Subobj, Decl)) 8810 DiagKind = 3; 8811 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 8812 !Decl->isTrivial()) { 8813 // A member of a union must have a trivial corresponding special member. 8814 // As a weird special case, a destructor call from a union's constructor 8815 // must be accessible and non-deleted, but need not be trivial. Such a 8816 // destructor is never actually called, but is semantically checked as 8817 // if it were. 8818 DiagKind = 4; 8819 } 8820 8821 if (DiagKind == -1) 8822 return false; 8823 8824 if (Diagnose) { 8825 if (Field) { 8826 S.Diag(Field->getLocation(), 8827 diag::note_deleted_special_member_class_subobject) 8828 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 8829 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 8830 } else { 8831 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 8832 S.Diag(Base->getBeginLoc(), 8833 diag::note_deleted_special_member_class_subobject) 8834 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8835 << Base->getType() << DiagKind << IsDtorCallInCtor 8836 << /*IsObjCPtr*/false; 8837 } 8838 8839 if (DiagKind == 1) 8840 S.NoteDeletedFunction(Decl); 8841 // FIXME: Explain inaccessibility if DiagKind == 3. 8842 } 8843 8844 return true; 8845 } 8846 8847 /// Check whether we should delete a special member function due to having a 8848 /// direct or virtual base class or non-static data member of class type M. 8849 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 8850 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 8851 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8852 bool IsMutable = Field && Field->isMutable(); 8853 8854 // C++11 [class.ctor]p5: 8855 // -- any direct or virtual base class, or non-static data member with no 8856 // brace-or-equal-initializer, has class type M (or array thereof) and 8857 // either M has no default constructor or overload resolution as applied 8858 // to M's default constructor results in an ambiguity or in a function 8859 // that is deleted or inaccessible 8860 // C++11 [class.copy]p11, C++11 [class.copy]p23: 8861 // -- a direct or virtual base class B that cannot be copied/moved because 8862 // overload resolution, as applied to B's corresponding special member, 8863 // results in an ambiguity or a function that is deleted or inaccessible 8864 // from the defaulted special member 8865 // C++11 [class.dtor]p5: 8866 // -- any direct or virtual base class [...] has a type with a destructor 8867 // that is deleted or inaccessible 8868 if (!(CSM == Sema::CXXDefaultConstructor && 8869 Field && Field->hasInClassInitializer()) && 8870 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 8871 false)) 8872 return true; 8873 8874 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 8875 // -- any direct or virtual base class or non-static data member has a 8876 // type with a destructor that is deleted or inaccessible 8877 if (IsConstructor) { 8878 Sema::SpecialMemberOverloadResult SMOR = 8879 S.LookupSpecialMember(Class, Sema::CXXDestructor, 8880 false, false, false, false, false); 8881 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 8882 return true; 8883 } 8884 8885 return false; 8886 } 8887 8888 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 8889 FieldDecl *FD, QualType FieldType) { 8890 // The defaulted special functions are defined as deleted if this is a variant 8891 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 8892 // type under ARC. 8893 if (!FieldType.hasNonTrivialObjCLifetime()) 8894 return false; 8895 8896 // Don't make the defaulted default constructor defined as deleted if the 8897 // member has an in-class initializer. 8898 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 8899 return false; 8900 8901 if (Diagnose) { 8902 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 8903 S.Diag(FD->getLocation(), 8904 diag::note_deleted_special_member_class_subobject) 8905 << getEffectiveCSM() << ParentClass << /*IsField*/true 8906 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 8907 } 8908 8909 return true; 8910 } 8911 8912 /// Check whether we should delete a special member function due to the class 8913 /// having a particular direct or virtual base class. 8914 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 8915 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 8916 // If program is correct, BaseClass cannot be null, but if it is, the error 8917 // must be reported elsewhere. 8918 if (!BaseClass) 8919 return false; 8920 // If we have an inheriting constructor, check whether we're calling an 8921 // inherited constructor instead of a default constructor. 8922 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 8923 if (auto *BaseCtor = SMOR.getMethod()) { 8924 // Note that we do not check access along this path; other than that, 8925 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 8926 // FIXME: Check that the base has a usable destructor! Sink this into 8927 // shouldDeleteForClassSubobject. 8928 if (BaseCtor->isDeleted() && Diagnose) { 8929 S.Diag(Base->getBeginLoc(), 8930 diag::note_deleted_special_member_class_subobject) 8931 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8932 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 8933 << /*IsObjCPtr*/false; 8934 S.NoteDeletedFunction(BaseCtor); 8935 } 8936 return BaseCtor->isDeleted(); 8937 } 8938 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 8939 } 8940 8941 /// Check whether we should delete a special member function due to the class 8942 /// having a particular non-static data member. 8943 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 8944 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 8945 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 8946 8947 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 8948 return true; 8949 8950 if (CSM == Sema::CXXDefaultConstructor) { 8951 // For a default constructor, all references must be initialized in-class 8952 // and, if a union, it must have a non-const member. 8953 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 8954 if (Diagnose) 8955 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8956 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 8957 return true; 8958 } 8959 // C++11 [class.ctor]p5: any non-variant non-static data member of 8960 // const-qualified type (or array thereof) with no 8961 // brace-or-equal-initializer does not have a user-provided default 8962 // constructor. 8963 if (!inUnion() && FieldType.isConstQualified() && 8964 !FD->hasInClassInitializer() && 8965 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 8966 if (Diagnose) 8967 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8968 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 8969 return true; 8970 } 8971 8972 if (inUnion() && !FieldType.isConstQualified()) 8973 AllFieldsAreConst = false; 8974 } else if (CSM == Sema::CXXCopyConstructor) { 8975 // For a copy constructor, data members must not be of rvalue reference 8976 // type. 8977 if (FieldType->isRValueReferenceType()) { 8978 if (Diagnose) 8979 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 8980 << MD->getParent() << FD << FieldType; 8981 return true; 8982 } 8983 } else if (IsAssignment) { 8984 // For an assignment operator, data members must not be of reference type. 8985 if (FieldType->isReferenceType()) { 8986 if (Diagnose) 8987 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 8988 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 8989 return true; 8990 } 8991 if (!FieldRecord && FieldType.isConstQualified()) { 8992 // C++11 [class.copy]p23: 8993 // -- a non-static data member of const non-class type (or array thereof) 8994 if (Diagnose) 8995 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 8996 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 8997 return true; 8998 } 8999 } 9000 9001 if (FieldRecord) { 9002 // Some additional restrictions exist on the variant members. 9003 if (!inUnion() && FieldRecord->isUnion() && 9004 FieldRecord->isAnonymousStructOrUnion()) { 9005 bool AllVariantFieldsAreConst = true; 9006 9007 // FIXME: Handle anonymous unions declared within anonymous unions. 9008 for (auto *UI : FieldRecord->fields()) { 9009 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 9010 9011 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 9012 return true; 9013 9014 if (!UnionFieldType.isConstQualified()) 9015 AllVariantFieldsAreConst = false; 9016 9017 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 9018 if (UnionFieldRecord && 9019 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 9020 UnionFieldType.getCVRQualifiers())) 9021 return true; 9022 } 9023 9024 // At least one member in each anonymous union must be non-const 9025 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 9026 !FieldRecord->field_empty()) { 9027 if (Diagnose) 9028 S.Diag(FieldRecord->getLocation(), 9029 diag::note_deleted_default_ctor_all_const) 9030 << !!ICI << MD->getParent() << /*anonymous union*/1; 9031 return true; 9032 } 9033 9034 // Don't check the implicit member of the anonymous union type. 9035 // This is technically non-conformant, but sanity demands it. 9036 return false; 9037 } 9038 9039 if (shouldDeleteForClassSubobject(FieldRecord, FD, 9040 FieldType.getCVRQualifiers())) 9041 return true; 9042 } 9043 9044 return false; 9045 } 9046 9047 /// C++11 [class.ctor] p5: 9048 /// A defaulted default constructor for a class X is defined as deleted if 9049 /// X is a union and all of its variant members are of const-qualified type. 9050 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 9051 // This is a silly definition, because it gives an empty union a deleted 9052 // default constructor. Don't do that. 9053 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 9054 bool AnyFields = false; 9055 for (auto *F : MD->getParent()->fields()) 9056 if ((AnyFields = !F->isUnnamedBitfield())) 9057 break; 9058 if (!AnyFields) 9059 return false; 9060 if (Diagnose) 9061 S.Diag(MD->getParent()->getLocation(), 9062 diag::note_deleted_default_ctor_all_const) 9063 << !!ICI << MD->getParent() << /*not anonymous union*/0; 9064 return true; 9065 } 9066 return false; 9067 } 9068 9069 /// Determine whether a defaulted special member function should be defined as 9070 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 9071 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 9072 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 9073 InheritedConstructorInfo *ICI, 9074 bool Diagnose) { 9075 if (MD->isInvalidDecl()) 9076 return false; 9077 CXXRecordDecl *RD = MD->getParent(); 9078 assert(!RD->isDependentType() && "do deletion after instantiation"); 9079 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 9080 return false; 9081 9082 // C++11 [expr.lambda.prim]p19: 9083 // The closure type associated with a lambda-expression has a 9084 // deleted (8.4.3) default constructor and a deleted copy 9085 // assignment operator. 9086 // C++2a adds back these operators if the lambda has no lambda-capture. 9087 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 9088 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 9089 if (Diagnose) 9090 Diag(RD->getLocation(), diag::note_lambda_decl); 9091 return true; 9092 } 9093 9094 // For an anonymous struct or union, the copy and assignment special members 9095 // will never be used, so skip the check. For an anonymous union declared at 9096 // namespace scope, the constructor and destructor are used. 9097 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 9098 RD->isAnonymousStructOrUnion()) 9099 return false; 9100 9101 // C++11 [class.copy]p7, p18: 9102 // If the class definition declares a move constructor or move assignment 9103 // operator, an implicitly declared copy constructor or copy assignment 9104 // operator is defined as deleted. 9105 if (MD->isImplicit() && 9106 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 9107 CXXMethodDecl *UserDeclaredMove = nullptr; 9108 9109 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 9110 // deletion of the corresponding copy operation, not both copy operations. 9111 // MSVC 2015 has adopted the standards conforming behavior. 9112 bool DeletesOnlyMatchingCopy = 9113 getLangOpts().MSVCCompat && 9114 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 9115 9116 if (RD->hasUserDeclaredMoveConstructor() && 9117 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 9118 if (!Diagnose) return true; 9119 9120 // Find any user-declared move constructor. 9121 for (auto *I : RD->ctors()) { 9122 if (I->isMoveConstructor()) { 9123 UserDeclaredMove = I; 9124 break; 9125 } 9126 } 9127 assert(UserDeclaredMove); 9128 } else if (RD->hasUserDeclaredMoveAssignment() && 9129 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 9130 if (!Diagnose) return true; 9131 9132 // Find any user-declared move assignment operator. 9133 for (auto *I : RD->methods()) { 9134 if (I->isMoveAssignmentOperator()) { 9135 UserDeclaredMove = I; 9136 break; 9137 } 9138 } 9139 assert(UserDeclaredMove); 9140 } 9141 9142 if (UserDeclaredMove) { 9143 Diag(UserDeclaredMove->getLocation(), 9144 diag::note_deleted_copy_user_declared_move) 9145 << (CSM == CXXCopyAssignment) << RD 9146 << UserDeclaredMove->isMoveAssignmentOperator(); 9147 return true; 9148 } 9149 } 9150 9151 // Do access control from the special member function 9152 ContextRAII MethodContext(*this, MD); 9153 9154 // C++11 [class.dtor]p5: 9155 // -- for a virtual destructor, lookup of the non-array deallocation function 9156 // results in an ambiguity or in a function that is deleted or inaccessible 9157 if (CSM == CXXDestructor && MD->isVirtual()) { 9158 FunctionDecl *OperatorDelete = nullptr; 9159 DeclarationName Name = 9160 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 9161 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 9162 OperatorDelete, /*Diagnose*/false)) { 9163 if (Diagnose) 9164 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 9165 return true; 9166 } 9167 } 9168 9169 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 9170 9171 // Per DR1611, do not consider virtual bases of constructors of abstract 9172 // classes, since we are not going to construct them. 9173 // Per DR1658, do not consider virtual bases of destructors of abstract 9174 // classes either. 9175 // Per DR2180, for assignment operators we only assign (and thus only 9176 // consider) direct bases. 9177 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 9178 : SMI.VisitPotentiallyConstructedBases)) 9179 return true; 9180 9181 if (SMI.shouldDeleteForAllConstMembers()) 9182 return true; 9183 9184 if (getLangOpts().CUDA) { 9185 // We should delete the special member in CUDA mode if target inference 9186 // failed. 9187 // For inherited constructors (non-null ICI), CSM may be passed so that MD 9188 // is treated as certain special member, which may not reflect what special 9189 // member MD really is. However inferCUDATargetForImplicitSpecialMember 9190 // expects CSM to match MD, therefore recalculate CSM. 9191 assert(ICI || CSM == getSpecialMember(MD)); 9192 auto RealCSM = CSM; 9193 if (ICI) 9194 RealCSM = getSpecialMember(MD); 9195 9196 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 9197 SMI.ConstArg, Diagnose); 9198 } 9199 9200 return false; 9201 } 9202 9203 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 9204 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 9205 assert(DFK && "not a defaultable function"); 9206 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted"); 9207 9208 if (DFK.isSpecialMember()) { 9209 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 9210 nullptr, /*Diagnose=*/true); 9211 } else { 9212 DefaultedComparisonAnalyzer( 9213 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 9214 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 9215 .visit(); 9216 } 9217 } 9218 9219 /// Perform lookup for a special member of the specified kind, and determine 9220 /// whether it is trivial. If the triviality can be determined without the 9221 /// lookup, skip it. This is intended for use when determining whether a 9222 /// special member of a containing object is trivial, and thus does not ever 9223 /// perform overload resolution for default constructors. 9224 /// 9225 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 9226 /// member that was most likely to be intended to be trivial, if any. 9227 /// 9228 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 9229 /// determine whether the special member is trivial. 9230 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 9231 Sema::CXXSpecialMember CSM, unsigned Quals, 9232 bool ConstRHS, 9233 Sema::TrivialABIHandling TAH, 9234 CXXMethodDecl **Selected) { 9235 if (Selected) 9236 *Selected = nullptr; 9237 9238 switch (CSM) { 9239 case Sema::CXXInvalid: 9240 llvm_unreachable("not a special member"); 9241 9242 case Sema::CXXDefaultConstructor: 9243 // C++11 [class.ctor]p5: 9244 // A default constructor is trivial if: 9245 // - all the [direct subobjects] have trivial default constructors 9246 // 9247 // Note, no overload resolution is performed in this case. 9248 if (RD->hasTrivialDefaultConstructor()) 9249 return true; 9250 9251 if (Selected) { 9252 // If there's a default constructor which could have been trivial, dig it 9253 // out. Otherwise, if there's any user-provided default constructor, point 9254 // to that as an example of why there's not a trivial one. 9255 CXXConstructorDecl *DefCtor = nullptr; 9256 if (RD->needsImplicitDefaultConstructor()) 9257 S.DeclareImplicitDefaultConstructor(RD); 9258 for (auto *CI : RD->ctors()) { 9259 if (!CI->isDefaultConstructor()) 9260 continue; 9261 DefCtor = CI; 9262 if (!DefCtor->isUserProvided()) 9263 break; 9264 } 9265 9266 *Selected = DefCtor; 9267 } 9268 9269 return false; 9270 9271 case Sema::CXXDestructor: 9272 // C++11 [class.dtor]p5: 9273 // A destructor is trivial if: 9274 // - all the direct [subobjects] have trivial destructors 9275 if (RD->hasTrivialDestructor() || 9276 (TAH == Sema::TAH_ConsiderTrivialABI && 9277 RD->hasTrivialDestructorForCall())) 9278 return true; 9279 9280 if (Selected) { 9281 if (RD->needsImplicitDestructor()) 9282 S.DeclareImplicitDestructor(RD); 9283 *Selected = RD->getDestructor(); 9284 } 9285 9286 return false; 9287 9288 case Sema::CXXCopyConstructor: 9289 // C++11 [class.copy]p12: 9290 // A copy constructor is trivial if: 9291 // - the constructor selected to copy each direct [subobject] is trivial 9292 if (RD->hasTrivialCopyConstructor() || 9293 (TAH == Sema::TAH_ConsiderTrivialABI && 9294 RD->hasTrivialCopyConstructorForCall())) { 9295 if (Quals == Qualifiers::Const) 9296 // We must either select the trivial copy constructor or reach an 9297 // ambiguity; no need to actually perform overload resolution. 9298 return true; 9299 } else if (!Selected) { 9300 return false; 9301 } 9302 // In C++98, we are not supposed to perform overload resolution here, but we 9303 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 9304 // cases like B as having a non-trivial copy constructor: 9305 // struct A { template<typename T> A(T&); }; 9306 // struct B { mutable A a; }; 9307 goto NeedOverloadResolution; 9308 9309 case Sema::CXXCopyAssignment: 9310 // C++11 [class.copy]p25: 9311 // A copy assignment operator is trivial if: 9312 // - the assignment operator selected to copy each direct [subobject] is 9313 // trivial 9314 if (RD->hasTrivialCopyAssignment()) { 9315 if (Quals == Qualifiers::Const) 9316 return true; 9317 } else if (!Selected) { 9318 return false; 9319 } 9320 // In C++98, we are not supposed to perform overload resolution here, but we 9321 // treat that as a language defect. 9322 goto NeedOverloadResolution; 9323 9324 case Sema::CXXMoveConstructor: 9325 case Sema::CXXMoveAssignment: 9326 NeedOverloadResolution: 9327 Sema::SpecialMemberOverloadResult SMOR = 9328 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 9329 9330 // The standard doesn't describe how to behave if the lookup is ambiguous. 9331 // We treat it as not making the member non-trivial, just like the standard 9332 // mandates for the default constructor. This should rarely matter, because 9333 // the member will also be deleted. 9334 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9335 return true; 9336 9337 if (!SMOR.getMethod()) { 9338 assert(SMOR.getKind() == 9339 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 9340 return false; 9341 } 9342 9343 // We deliberately don't check if we found a deleted special member. We're 9344 // not supposed to! 9345 if (Selected) 9346 *Selected = SMOR.getMethod(); 9347 9348 if (TAH == Sema::TAH_ConsiderTrivialABI && 9349 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 9350 return SMOR.getMethod()->isTrivialForCall(); 9351 return SMOR.getMethod()->isTrivial(); 9352 } 9353 9354 llvm_unreachable("unknown special method kind"); 9355 } 9356 9357 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 9358 for (auto *CI : RD->ctors()) 9359 if (!CI->isImplicit()) 9360 return CI; 9361 9362 // Look for constructor templates. 9363 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 9364 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 9365 if (CXXConstructorDecl *CD = 9366 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 9367 return CD; 9368 } 9369 9370 return nullptr; 9371 } 9372 9373 /// The kind of subobject we are checking for triviality. The values of this 9374 /// enumeration are used in diagnostics. 9375 enum TrivialSubobjectKind { 9376 /// The subobject is a base class. 9377 TSK_BaseClass, 9378 /// The subobject is a non-static data member. 9379 TSK_Field, 9380 /// The object is actually the complete object. 9381 TSK_CompleteObject 9382 }; 9383 9384 /// Check whether the special member selected for a given type would be trivial. 9385 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9386 QualType SubType, bool ConstRHS, 9387 Sema::CXXSpecialMember CSM, 9388 TrivialSubobjectKind Kind, 9389 Sema::TrivialABIHandling TAH, bool Diagnose) { 9390 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9391 if (!SubRD) 9392 return true; 9393 9394 CXXMethodDecl *Selected; 9395 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9396 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9397 return true; 9398 9399 if (Diagnose) { 9400 if (ConstRHS) 9401 SubType.addConst(); 9402 9403 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9404 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9405 << Kind << SubType.getUnqualifiedType(); 9406 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9407 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9408 } else if (!Selected) 9409 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9410 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9411 else if (Selected->isUserProvided()) { 9412 if (Kind == TSK_CompleteObject) 9413 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9414 << Kind << SubType.getUnqualifiedType() << CSM; 9415 else { 9416 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9417 << Kind << SubType.getUnqualifiedType() << CSM; 9418 S.Diag(Selected->getLocation(), diag::note_declared_at); 9419 } 9420 } else { 9421 if (Kind != TSK_CompleteObject) 9422 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9423 << Kind << SubType.getUnqualifiedType() << CSM; 9424 9425 // Explain why the defaulted or deleted special member isn't trivial. 9426 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9427 Diagnose); 9428 } 9429 } 9430 9431 return false; 9432 } 9433 9434 /// Check whether the members of a class type allow a special member to be 9435 /// trivial. 9436 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9437 Sema::CXXSpecialMember CSM, 9438 bool ConstArg, 9439 Sema::TrivialABIHandling TAH, 9440 bool Diagnose) { 9441 for (const auto *FI : RD->fields()) { 9442 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9443 continue; 9444 9445 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9446 9447 // Pretend anonymous struct or union members are members of this class. 9448 if (FI->isAnonymousStructOrUnion()) { 9449 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9450 CSM, ConstArg, TAH, Diagnose)) 9451 return false; 9452 continue; 9453 } 9454 9455 // C++11 [class.ctor]p5: 9456 // A default constructor is trivial if [...] 9457 // -- no non-static data member of its class has a 9458 // brace-or-equal-initializer 9459 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9460 if (Diagnose) 9461 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init) 9462 << FI; 9463 return false; 9464 } 9465 9466 // Objective C ARC 4.3.5: 9467 // [...] nontrivally ownership-qualified types are [...] not trivially 9468 // default constructible, copy constructible, move constructible, copy 9469 // assignable, move assignable, or destructible [...] 9470 if (FieldType.hasNonTrivialObjCLifetime()) { 9471 if (Diagnose) 9472 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9473 << RD << FieldType.getObjCLifetime(); 9474 return false; 9475 } 9476 9477 bool ConstRHS = ConstArg && !FI->isMutable(); 9478 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9479 CSM, TSK_Field, TAH, Diagnose)) 9480 return false; 9481 } 9482 9483 return true; 9484 } 9485 9486 /// Diagnose why the specified class does not have a trivial special member of 9487 /// the given kind. 9488 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9489 QualType Ty = Context.getRecordType(RD); 9490 9491 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9492 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9493 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9494 /*Diagnose*/true); 9495 } 9496 9497 /// Determine whether a defaulted or deleted special member function is trivial, 9498 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9499 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9500 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9501 TrivialABIHandling TAH, bool Diagnose) { 9502 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 9503 9504 CXXRecordDecl *RD = MD->getParent(); 9505 9506 bool ConstArg = false; 9507 9508 // C++11 [class.copy]p12, p25: [DR1593] 9509 // A [special member] is trivial if [...] its parameter-type-list is 9510 // equivalent to the parameter-type-list of an implicit declaration [...] 9511 switch (CSM) { 9512 case CXXDefaultConstructor: 9513 case CXXDestructor: 9514 // Trivial default constructors and destructors cannot have parameters. 9515 break; 9516 9517 case CXXCopyConstructor: 9518 case CXXCopyAssignment: { 9519 // Trivial copy operations always have const, non-volatile parameter types. 9520 ConstArg = true; 9521 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9522 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9523 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 9524 if (Diagnose) 9525 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9526 << Param0->getSourceRange() << Param0->getType() 9527 << Context.getLValueReferenceType( 9528 Context.getRecordType(RD).withConst()); 9529 return false; 9530 } 9531 break; 9532 } 9533 9534 case CXXMoveConstructor: 9535 case CXXMoveAssignment: { 9536 // Trivial move operations always have non-cv-qualified parameters. 9537 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9538 const RValueReferenceType *RT = 9539 Param0->getType()->getAs<RValueReferenceType>(); 9540 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9541 if (Diagnose) 9542 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9543 << Param0->getSourceRange() << Param0->getType() 9544 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9545 return false; 9546 } 9547 break; 9548 } 9549 9550 case CXXInvalid: 9551 llvm_unreachable("not a special member"); 9552 } 9553 9554 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9555 if (Diagnose) 9556 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9557 diag::note_nontrivial_default_arg) 9558 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9559 return false; 9560 } 9561 if (MD->isVariadic()) { 9562 if (Diagnose) 9563 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9564 return false; 9565 } 9566 9567 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9568 // A copy/move [constructor or assignment operator] is trivial if 9569 // -- the [member] selected to copy/move each direct base class subobject 9570 // is trivial 9571 // 9572 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9573 // A [default constructor or destructor] is trivial if 9574 // -- all the direct base classes have trivial [default constructors or 9575 // destructors] 9576 for (const auto &BI : RD->bases()) 9577 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9578 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9579 return false; 9580 9581 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9582 // A copy/move [constructor or assignment operator] for a class X is 9583 // trivial if 9584 // -- for each non-static data member of X that is of class type (or array 9585 // thereof), the constructor selected to copy/move that member is 9586 // trivial 9587 // 9588 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9589 // A [default constructor or destructor] is trivial if 9590 // -- for all of the non-static data members of its class that are of class 9591 // type (or array thereof), each such class has a trivial [default 9592 // constructor or destructor] 9593 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9594 return false; 9595 9596 // C++11 [class.dtor]p5: 9597 // A destructor is trivial if [...] 9598 // -- the destructor is not virtual 9599 if (CSM == CXXDestructor && MD->isVirtual()) { 9600 if (Diagnose) 9601 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9602 return false; 9603 } 9604 9605 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9606 // A [special member] for class X is trivial if [...] 9607 // -- class X has no virtual functions and no virtual base classes 9608 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9609 if (!Diagnose) 9610 return false; 9611 9612 if (RD->getNumVBases()) { 9613 // Check for virtual bases. We already know that the corresponding 9614 // member in all bases is trivial, so vbases must all be direct. 9615 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9616 assert(BS.isVirtual()); 9617 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9618 return false; 9619 } 9620 9621 // Must have a virtual method. 9622 for (const auto *MI : RD->methods()) { 9623 if (MI->isVirtual()) { 9624 SourceLocation MLoc = MI->getBeginLoc(); 9625 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9626 return false; 9627 } 9628 } 9629 9630 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 9631 } 9632 9633 // Looks like it's trivial! 9634 return true; 9635 } 9636 9637 namespace { 9638 struct FindHiddenVirtualMethod { 9639 Sema *S; 9640 CXXMethodDecl *Method; 9641 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9642 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9643 9644 private: 9645 /// Check whether any most overridden method from MD in Methods 9646 static bool CheckMostOverridenMethods( 9647 const CXXMethodDecl *MD, 9648 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9649 if (MD->size_overridden_methods() == 0) 9650 return Methods.count(MD->getCanonicalDecl()); 9651 for (const CXXMethodDecl *O : MD->overridden_methods()) 9652 if (CheckMostOverridenMethods(O, Methods)) 9653 return true; 9654 return false; 9655 } 9656 9657 public: 9658 /// Member lookup function that determines whether a given C++ 9659 /// method overloads virtual methods in a base class without overriding any, 9660 /// to be used with CXXRecordDecl::lookupInBases(). 9661 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9662 RecordDecl *BaseRecord = 9663 Specifier->getType()->castAs<RecordType>()->getDecl(); 9664 9665 DeclarationName Name = Method->getDeclName(); 9666 assert(Name.getNameKind() == DeclarationName::Identifier); 9667 9668 bool foundSameNameMethod = false; 9669 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9670 for (Path.Decls = BaseRecord->lookup(Name).begin(); 9671 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) { 9672 NamedDecl *D = *Path.Decls; 9673 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9674 MD = MD->getCanonicalDecl(); 9675 foundSameNameMethod = true; 9676 // Interested only in hidden virtual methods. 9677 if (!MD->isVirtual()) 9678 continue; 9679 // If the method we are checking overrides a method from its base 9680 // don't warn about the other overloaded methods. Clang deviates from 9681 // GCC by only diagnosing overloads of inherited virtual functions that 9682 // do not override any other virtual functions in the base. GCC's 9683 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9684 // function from a base class. These cases may be better served by a 9685 // warning (not specific to virtual functions) on call sites when the 9686 // call would select a different function from the base class, were it 9687 // visible. 9688 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9689 if (!S->IsOverload(Method, MD, false)) 9690 return true; 9691 // Collect the overload only if its hidden. 9692 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9693 overloadedMethods.push_back(MD); 9694 } 9695 } 9696 9697 if (foundSameNameMethod) 9698 OverloadedMethods.append(overloadedMethods.begin(), 9699 overloadedMethods.end()); 9700 return foundSameNameMethod; 9701 } 9702 }; 9703 } // end anonymous namespace 9704 9705 /// Add the most overriden methods from MD to Methods 9706 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9707 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9708 if (MD->size_overridden_methods() == 0) 9709 Methods.insert(MD->getCanonicalDecl()); 9710 else 9711 for (const CXXMethodDecl *O : MD->overridden_methods()) 9712 AddMostOverridenMethods(O, Methods); 9713 } 9714 9715 /// Check if a method overloads virtual methods in a base class without 9716 /// overriding any. 9717 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9718 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9719 if (!MD->getDeclName().isIdentifier()) 9720 return; 9721 9722 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9723 /*bool RecordPaths=*/false, 9724 /*bool DetectVirtual=*/false); 9725 FindHiddenVirtualMethod FHVM; 9726 FHVM.Method = MD; 9727 FHVM.S = this; 9728 9729 // Keep the base methods that were overridden or introduced in the subclass 9730 // by 'using' in a set. A base method not in this set is hidden. 9731 CXXRecordDecl *DC = MD->getParent(); 9732 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9733 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9734 NamedDecl *ND = *I; 9735 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9736 ND = shad->getTargetDecl(); 9737 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9738 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9739 } 9740 9741 if (DC->lookupInBases(FHVM, Paths)) 9742 OverloadedMethods = FHVM.OverloadedMethods; 9743 } 9744 9745 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 9746 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9747 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 9748 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 9749 PartialDiagnostic PD = PDiag( 9750 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 9751 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 9752 Diag(overloadedMD->getLocation(), PD); 9753 } 9754 } 9755 9756 /// Diagnose methods which overload virtual methods in a base class 9757 /// without overriding any. 9758 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 9759 if (MD->isInvalidDecl()) 9760 return; 9761 9762 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 9763 return; 9764 9765 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9766 FindHiddenVirtualMethods(MD, OverloadedMethods); 9767 if (!OverloadedMethods.empty()) { 9768 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 9769 << MD << (OverloadedMethods.size() > 1); 9770 9771 NoteHiddenVirtualMethods(MD, OverloadedMethods); 9772 } 9773 } 9774 9775 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 9776 auto PrintDiagAndRemoveAttr = [&](unsigned N) { 9777 // No diagnostics if this is a template instantiation. 9778 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) { 9779 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9780 diag::ext_cannot_use_trivial_abi) << &RD; 9781 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9782 diag::note_cannot_use_trivial_abi_reason) << &RD << N; 9783 } 9784 RD.dropAttr<TrivialABIAttr>(); 9785 }; 9786 9787 // Ill-formed if the copy and move constructors are deleted. 9788 auto HasNonDeletedCopyOrMoveConstructor = [&]() { 9789 // If the type is dependent, then assume it might have 9790 // implicit copy or move ctor because we won't know yet at this point. 9791 if (RD.isDependentType()) 9792 return true; 9793 if (RD.needsImplicitCopyConstructor() && 9794 !RD.defaultedCopyConstructorIsDeleted()) 9795 return true; 9796 if (RD.needsImplicitMoveConstructor() && 9797 !RD.defaultedMoveConstructorIsDeleted()) 9798 return true; 9799 for (const CXXConstructorDecl *CD : RD.ctors()) 9800 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted()) 9801 return true; 9802 return false; 9803 }; 9804 9805 if (!HasNonDeletedCopyOrMoveConstructor()) { 9806 PrintDiagAndRemoveAttr(0); 9807 return; 9808 } 9809 9810 // Ill-formed if the struct has virtual functions. 9811 if (RD.isPolymorphic()) { 9812 PrintDiagAndRemoveAttr(1); 9813 return; 9814 } 9815 9816 for (const auto &B : RD.bases()) { 9817 // Ill-formed if the base class is non-trivial for the purpose of calls or a 9818 // virtual base. 9819 if (!B.getType()->isDependentType() && 9820 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) { 9821 PrintDiagAndRemoveAttr(2); 9822 return; 9823 } 9824 9825 if (B.isVirtual()) { 9826 PrintDiagAndRemoveAttr(3); 9827 return; 9828 } 9829 } 9830 9831 for (const auto *FD : RD.fields()) { 9832 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 9833 // non-trivial for the purpose of calls. 9834 QualType FT = FD->getType(); 9835 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 9836 PrintDiagAndRemoveAttr(4); 9837 return; 9838 } 9839 9840 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 9841 if (!RT->isDependentType() && 9842 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 9843 PrintDiagAndRemoveAttr(5); 9844 return; 9845 } 9846 } 9847 } 9848 9849 void Sema::ActOnFinishCXXMemberSpecification( 9850 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 9851 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 9852 if (!TagDecl) 9853 return; 9854 9855 AdjustDeclIfTemplate(TagDecl); 9856 9857 for (const ParsedAttr &AL : AttrList) { 9858 if (AL.getKind() != ParsedAttr::AT_Visibility) 9859 continue; 9860 AL.setInvalid(); 9861 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 9862 } 9863 9864 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 9865 // strict aliasing violation! 9866 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 9867 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 9868 9869 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 9870 } 9871 9872 /// Find the equality comparison functions that should be implicitly declared 9873 /// in a given class definition, per C++2a [class.compare.default]p3. 9874 static void findImplicitlyDeclaredEqualityComparisons( 9875 ASTContext &Ctx, CXXRecordDecl *RD, 9876 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 9877 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 9878 if (!RD->lookup(EqEq).empty()) 9879 // Member operator== explicitly declared: no implicit operator==s. 9880 return; 9881 9882 // Traverse friends looking for an '==' or a '<=>'. 9883 for (FriendDecl *Friend : RD->friends()) { 9884 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 9885 if (!FD) continue; 9886 9887 if (FD->getOverloadedOperator() == OO_EqualEqual) { 9888 // Friend operator== explicitly declared: no implicit operator==s. 9889 Spaceships.clear(); 9890 return; 9891 } 9892 9893 if (FD->getOverloadedOperator() == OO_Spaceship && 9894 FD->isExplicitlyDefaulted()) 9895 Spaceships.push_back(FD); 9896 } 9897 9898 // Look for members named 'operator<=>'. 9899 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 9900 for (NamedDecl *ND : RD->lookup(Cmp)) { 9901 // Note that we could find a non-function here (either a function template 9902 // or a using-declaration). Neither case results in an implicit 9903 // 'operator=='. 9904 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 9905 if (FD->isExplicitlyDefaulted()) 9906 Spaceships.push_back(FD); 9907 } 9908 } 9909 9910 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 9911 /// special functions, such as the default constructor, copy 9912 /// constructor, or destructor, to the given C++ class (C++ 9913 /// [special]p1). This routine can only be executed just before the 9914 /// definition of the class is complete. 9915 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 9916 // Don't add implicit special members to templated classes. 9917 // FIXME: This means unqualified lookups for 'operator=' within a class 9918 // template don't work properly. 9919 if (!ClassDecl->isDependentType()) { 9920 if (ClassDecl->needsImplicitDefaultConstructor()) { 9921 ++getASTContext().NumImplicitDefaultConstructors; 9922 9923 if (ClassDecl->hasInheritedConstructor()) 9924 DeclareImplicitDefaultConstructor(ClassDecl); 9925 } 9926 9927 if (ClassDecl->needsImplicitCopyConstructor()) { 9928 ++getASTContext().NumImplicitCopyConstructors; 9929 9930 // If the properties or semantics of the copy constructor couldn't be 9931 // determined while the class was being declared, force a declaration 9932 // of it now. 9933 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 9934 ClassDecl->hasInheritedConstructor()) 9935 DeclareImplicitCopyConstructor(ClassDecl); 9936 // For the MS ABI we need to know whether the copy ctor is deleted. A 9937 // prerequisite for deleting the implicit copy ctor is that the class has 9938 // a move ctor or move assignment that is either user-declared or whose 9939 // semantics are inherited from a subobject. FIXME: We should provide a 9940 // more direct way for CodeGen to ask whether the constructor was deleted. 9941 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 9942 (ClassDecl->hasUserDeclaredMoveConstructor() || 9943 ClassDecl->needsOverloadResolutionForMoveConstructor() || 9944 ClassDecl->hasUserDeclaredMoveAssignment() || 9945 ClassDecl->needsOverloadResolutionForMoveAssignment())) 9946 DeclareImplicitCopyConstructor(ClassDecl); 9947 } 9948 9949 if (getLangOpts().CPlusPlus11 && 9950 ClassDecl->needsImplicitMoveConstructor()) { 9951 ++getASTContext().NumImplicitMoveConstructors; 9952 9953 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 9954 ClassDecl->hasInheritedConstructor()) 9955 DeclareImplicitMoveConstructor(ClassDecl); 9956 } 9957 9958 if (ClassDecl->needsImplicitCopyAssignment()) { 9959 ++getASTContext().NumImplicitCopyAssignmentOperators; 9960 9961 // If we have a dynamic class, then the copy assignment operator may be 9962 // virtual, so we have to declare it immediately. This ensures that, e.g., 9963 // it shows up in the right place in the vtable and that we diagnose 9964 // problems with the implicit exception specification. 9965 if (ClassDecl->isDynamicClass() || 9966 ClassDecl->needsOverloadResolutionForCopyAssignment() || 9967 ClassDecl->hasInheritedAssignment()) 9968 DeclareImplicitCopyAssignment(ClassDecl); 9969 } 9970 9971 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 9972 ++getASTContext().NumImplicitMoveAssignmentOperators; 9973 9974 // Likewise for the move assignment operator. 9975 if (ClassDecl->isDynamicClass() || 9976 ClassDecl->needsOverloadResolutionForMoveAssignment() || 9977 ClassDecl->hasInheritedAssignment()) 9978 DeclareImplicitMoveAssignment(ClassDecl); 9979 } 9980 9981 if (ClassDecl->needsImplicitDestructor()) { 9982 ++getASTContext().NumImplicitDestructors; 9983 9984 // If we have a dynamic class, then the destructor may be virtual, so we 9985 // have to declare the destructor immediately. This ensures that, e.g., it 9986 // shows up in the right place in the vtable and that we diagnose problems 9987 // with the implicit exception specification. 9988 if (ClassDecl->isDynamicClass() || 9989 ClassDecl->needsOverloadResolutionForDestructor()) 9990 DeclareImplicitDestructor(ClassDecl); 9991 } 9992 } 9993 9994 // C++2a [class.compare.default]p3: 9995 // If the member-specification does not explicitly declare any member or 9996 // friend named operator==, an == operator function is declared implicitly 9997 // for each defaulted three-way comparison operator function defined in 9998 // the member-specification 9999 // FIXME: Consider doing this lazily. 10000 // We do this during the initial parse for a class template, not during 10001 // instantiation, so that we can handle unqualified lookups for 'operator==' 10002 // when parsing the template. 10003 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) { 10004 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships; 10005 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 10006 DefaultedSpaceships); 10007 for (auto *FD : DefaultedSpaceships) 10008 DeclareImplicitEqualityComparison(ClassDecl, FD); 10009 } 10010 } 10011 10012 unsigned 10013 Sema::ActOnReenterTemplateScope(Decl *D, 10014 llvm::function_ref<Scope *()> EnterScope) { 10015 if (!D) 10016 return 0; 10017 AdjustDeclIfTemplate(D); 10018 10019 // In order to get name lookup right, reenter template scopes in order from 10020 // outermost to innermost. 10021 SmallVector<TemplateParameterList *, 4> ParameterLists; 10022 DeclContext *LookupDC = dyn_cast<DeclContext>(D); 10023 10024 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 10025 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 10026 ParameterLists.push_back(DD->getTemplateParameterList(i)); 10027 10028 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10029 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 10030 ParameterLists.push_back(FTD->getTemplateParameters()); 10031 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 10032 LookupDC = VD->getDeclContext(); 10033 10034 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate()) 10035 ParameterLists.push_back(VTD->getTemplateParameters()); 10036 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) 10037 ParameterLists.push_back(PSD->getTemplateParameters()); 10038 } 10039 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 10040 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 10041 ParameterLists.push_back(TD->getTemplateParameterList(i)); 10042 10043 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 10044 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 10045 ParameterLists.push_back(CTD->getTemplateParameters()); 10046 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 10047 ParameterLists.push_back(PSD->getTemplateParameters()); 10048 } 10049 } 10050 // FIXME: Alias declarations and concepts. 10051 10052 unsigned Count = 0; 10053 Scope *InnermostTemplateScope = nullptr; 10054 for (TemplateParameterList *Params : ParameterLists) { 10055 // Ignore explicit specializations; they don't contribute to the template 10056 // depth. 10057 if (Params->size() == 0) 10058 continue; 10059 10060 InnermostTemplateScope = EnterScope(); 10061 for (NamedDecl *Param : *Params) { 10062 if (Param->getDeclName()) { 10063 InnermostTemplateScope->AddDecl(Param); 10064 IdResolver.AddDecl(Param); 10065 } 10066 } 10067 ++Count; 10068 } 10069 10070 // Associate the new template scopes with the corresponding entities. 10071 if (InnermostTemplateScope) { 10072 assert(LookupDC && "no enclosing DeclContext for template lookup"); 10073 EnterTemplatedContext(InnermostTemplateScope, LookupDC); 10074 } 10075 10076 return Count; 10077 } 10078 10079 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10080 if (!RecordD) return; 10081 AdjustDeclIfTemplate(RecordD); 10082 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 10083 PushDeclContext(S, Record); 10084 } 10085 10086 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10087 if (!RecordD) return; 10088 PopDeclContext(); 10089 } 10090 10091 /// This is used to implement the constant expression evaluation part of the 10092 /// attribute enable_if extension. There is nothing in standard C++ which would 10093 /// require reentering parameters. 10094 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 10095 if (!Param) 10096 return; 10097 10098 S->AddDecl(Param); 10099 if (Param->getDeclName()) 10100 IdResolver.AddDecl(Param); 10101 } 10102 10103 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 10104 /// parsing a top-level (non-nested) C++ class, and we are now 10105 /// parsing those parts of the given Method declaration that could 10106 /// not be parsed earlier (C++ [class.mem]p2), such as default 10107 /// arguments. This action should enter the scope of the given 10108 /// Method declaration as if we had just parsed the qualified method 10109 /// name. However, it should not bring the parameters into scope; 10110 /// that will be performed by ActOnDelayedCXXMethodParameter. 10111 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10112 } 10113 10114 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 10115 /// C++ method declaration. We're (re-)introducing the given 10116 /// function parameter into scope for use in parsing later parts of 10117 /// the method declaration. For example, we could see an 10118 /// ActOnParamDefaultArgument event for this parameter. 10119 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 10120 if (!ParamD) 10121 return; 10122 10123 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 10124 10125 S->AddDecl(Param); 10126 if (Param->getDeclName()) 10127 IdResolver.AddDecl(Param); 10128 } 10129 10130 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 10131 /// processing the delayed method declaration for Method. The method 10132 /// declaration is now considered finished. There may be a separate 10133 /// ActOnStartOfFunctionDef action later (not necessarily 10134 /// immediately!) for this method, if it was also defined inside the 10135 /// class body. 10136 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10137 if (!MethodD) 10138 return; 10139 10140 AdjustDeclIfTemplate(MethodD); 10141 10142 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 10143 10144 // Now that we have our default arguments, check the constructor 10145 // again. It could produce additional diagnostics or affect whether 10146 // the class has implicitly-declared destructors, among other 10147 // things. 10148 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 10149 CheckConstructor(Constructor); 10150 10151 // Check the default arguments, which we may have added. 10152 if (!Method->isInvalidDecl()) 10153 CheckCXXDefaultArguments(Method); 10154 } 10155 10156 // Emit the given diagnostic for each non-address-space qualifier. 10157 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 10158 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 10159 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10160 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 10161 bool DiagOccured = false; 10162 FTI.MethodQualifiers->forEachQualifier( 10163 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 10164 SourceLocation SL) { 10165 // This diagnostic should be emitted on any qualifier except an addr 10166 // space qualifier. However, forEachQualifier currently doesn't visit 10167 // addr space qualifiers, so there's no way to write this condition 10168 // right now; we just diagnose on everything. 10169 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 10170 DiagOccured = true; 10171 }); 10172 if (DiagOccured) 10173 D.setInvalidType(); 10174 } 10175 } 10176 10177 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 10178 /// the well-formedness of the constructor declarator @p D with type @p 10179 /// R. If there are any errors in the declarator, this routine will 10180 /// emit diagnostics and set the invalid bit to true. In any case, the type 10181 /// will be updated to reflect a well-formed type for the constructor and 10182 /// returned. 10183 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 10184 StorageClass &SC) { 10185 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 10186 10187 // C++ [class.ctor]p3: 10188 // A constructor shall not be virtual (10.3) or static (9.4). A 10189 // constructor can be invoked for a const, volatile or const 10190 // volatile object. A constructor shall not be declared const, 10191 // volatile, or const volatile (9.3.2). 10192 if (isVirtual) { 10193 if (!D.isInvalidType()) 10194 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10195 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 10196 << SourceRange(D.getIdentifierLoc()); 10197 D.setInvalidType(); 10198 } 10199 if (SC == SC_Static) { 10200 if (!D.isInvalidType()) 10201 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10202 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10203 << SourceRange(D.getIdentifierLoc()); 10204 D.setInvalidType(); 10205 SC = SC_None; 10206 } 10207 10208 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10209 diagnoseIgnoredQualifiers( 10210 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 10211 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 10212 D.getDeclSpec().getRestrictSpecLoc(), 10213 D.getDeclSpec().getAtomicSpecLoc()); 10214 D.setInvalidType(); 10215 } 10216 10217 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 10218 10219 // C++0x [class.ctor]p4: 10220 // A constructor shall not be declared with a ref-qualifier. 10221 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10222 if (FTI.hasRefQualifier()) { 10223 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 10224 << FTI.RefQualifierIsLValueRef 10225 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10226 D.setInvalidType(); 10227 } 10228 10229 // Rebuild the function type "R" without any type qualifiers (in 10230 // case any of the errors above fired) and with "void" as the 10231 // return type, since constructors don't have return types. 10232 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10233 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 10234 return R; 10235 10236 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10237 EPI.TypeQuals = Qualifiers(); 10238 EPI.RefQualifier = RQ_None; 10239 10240 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 10241 } 10242 10243 /// CheckConstructor - Checks a fully-formed constructor for 10244 /// well-formedness, issuing any diagnostics required. Returns true if 10245 /// the constructor declarator is invalid. 10246 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 10247 CXXRecordDecl *ClassDecl 10248 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 10249 if (!ClassDecl) 10250 return Constructor->setInvalidDecl(); 10251 10252 // C++ [class.copy]p3: 10253 // A declaration of a constructor for a class X is ill-formed if 10254 // its first parameter is of type (optionally cv-qualified) X and 10255 // either there are no other parameters or else all other 10256 // parameters have default arguments. 10257 if (!Constructor->isInvalidDecl() && 10258 Constructor->hasOneParamOrDefaultArgs() && 10259 Constructor->getTemplateSpecializationKind() != 10260 TSK_ImplicitInstantiation) { 10261 QualType ParamType = Constructor->getParamDecl(0)->getType(); 10262 QualType ClassTy = Context.getTagDeclType(ClassDecl); 10263 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 10264 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 10265 const char *ConstRef 10266 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 10267 : " const &"; 10268 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 10269 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 10270 10271 // FIXME: Rather that making the constructor invalid, we should endeavor 10272 // to fix the type. 10273 Constructor->setInvalidDecl(); 10274 } 10275 } 10276 } 10277 10278 /// CheckDestructor - Checks a fully-formed destructor definition for 10279 /// well-formedness, issuing any diagnostics required. Returns true 10280 /// on error. 10281 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 10282 CXXRecordDecl *RD = Destructor->getParent(); 10283 10284 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 10285 SourceLocation Loc; 10286 10287 if (!Destructor->isImplicit()) 10288 Loc = Destructor->getLocation(); 10289 else 10290 Loc = RD->getLocation(); 10291 10292 // If we have a virtual destructor, look up the deallocation function 10293 if (FunctionDecl *OperatorDelete = 10294 FindDeallocationFunctionForDestructor(Loc, RD)) { 10295 Expr *ThisArg = nullptr; 10296 10297 // If the notional 'delete this' expression requires a non-trivial 10298 // conversion from 'this' to the type of a destroying operator delete's 10299 // first parameter, perform that conversion now. 10300 if (OperatorDelete->isDestroyingOperatorDelete()) { 10301 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 10302 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 10303 // C++ [class.dtor]p13: 10304 // ... as if for the expression 'delete this' appearing in a 10305 // non-virtual destructor of the destructor's class. 10306 ContextRAII SwitchContext(*this, Destructor); 10307 ExprResult This = 10308 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 10309 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 10310 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 10311 if (This.isInvalid()) { 10312 // FIXME: Register this as a context note so that it comes out 10313 // in the right order. 10314 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 10315 return true; 10316 } 10317 ThisArg = This.get(); 10318 } 10319 } 10320 10321 DiagnoseUseOfDecl(OperatorDelete, Loc); 10322 MarkFunctionReferenced(Loc, OperatorDelete); 10323 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 10324 } 10325 } 10326 10327 return false; 10328 } 10329 10330 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 10331 /// the well-formednes of the destructor declarator @p D with type @p 10332 /// R. If there are any errors in the declarator, this routine will 10333 /// emit diagnostics and set the declarator to invalid. Even if this happens, 10334 /// will be updated to reflect a well-formed type for the destructor and 10335 /// returned. 10336 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 10337 StorageClass& SC) { 10338 // C++ [class.dtor]p1: 10339 // [...] A typedef-name that names a class is a class-name 10340 // (7.1.3); however, a typedef-name that names a class shall not 10341 // be used as the identifier in the declarator for a destructor 10342 // declaration. 10343 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 10344 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 10345 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10346 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 10347 else if (const TemplateSpecializationType *TST = 10348 DeclaratorType->getAs<TemplateSpecializationType>()) 10349 if (TST->isTypeAlias()) 10350 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10351 << DeclaratorType << 1; 10352 10353 // C++ [class.dtor]p2: 10354 // A destructor is used to destroy objects of its class type. A 10355 // destructor takes no parameters, and no return type can be 10356 // specified for it (not even void). The address of a destructor 10357 // shall not be taken. A destructor shall not be static. A 10358 // destructor can be invoked for a const, volatile or const 10359 // volatile object. A destructor shall not be declared const, 10360 // volatile or const volatile (9.3.2). 10361 if (SC == SC_Static) { 10362 if (!D.isInvalidType()) 10363 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 10364 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10365 << SourceRange(D.getIdentifierLoc()) 10366 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10367 10368 SC = SC_None; 10369 } 10370 if (!D.isInvalidType()) { 10371 // Destructors don't have return types, but the parser will 10372 // happily parse something like: 10373 // 10374 // class X { 10375 // float ~X(); 10376 // }; 10377 // 10378 // The return type will be eliminated later. 10379 if (D.getDeclSpec().hasTypeSpecifier()) 10380 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 10381 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 10382 << SourceRange(D.getIdentifierLoc()); 10383 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10384 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 10385 SourceLocation(), 10386 D.getDeclSpec().getConstSpecLoc(), 10387 D.getDeclSpec().getVolatileSpecLoc(), 10388 D.getDeclSpec().getRestrictSpecLoc(), 10389 D.getDeclSpec().getAtomicSpecLoc()); 10390 D.setInvalidType(); 10391 } 10392 } 10393 10394 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 10395 10396 // C++0x [class.dtor]p2: 10397 // A destructor shall not be declared with a ref-qualifier. 10398 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10399 if (FTI.hasRefQualifier()) { 10400 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 10401 << FTI.RefQualifierIsLValueRef 10402 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10403 D.setInvalidType(); 10404 } 10405 10406 // Make sure we don't have any parameters. 10407 if (FTIHasNonVoidParameters(FTI)) { 10408 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 10409 10410 // Delete the parameters. 10411 FTI.freeParams(); 10412 D.setInvalidType(); 10413 } 10414 10415 // Make sure the destructor isn't variadic. 10416 if (FTI.isVariadic) { 10417 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10418 D.setInvalidType(); 10419 } 10420 10421 // Rebuild the function type "R" without any type qualifiers or 10422 // parameters (in case any of the errors above fired) and with 10423 // "void" as the return type, since destructors don't have return 10424 // types. 10425 if (!D.isInvalidType()) 10426 return R; 10427 10428 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10429 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10430 EPI.Variadic = false; 10431 EPI.TypeQuals = Qualifiers(); 10432 EPI.RefQualifier = RQ_None; 10433 return Context.getFunctionType(Context.VoidTy, None, EPI); 10434 } 10435 10436 static void extendLeft(SourceRange &R, SourceRange Before) { 10437 if (Before.isInvalid()) 10438 return; 10439 R.setBegin(Before.getBegin()); 10440 if (R.getEnd().isInvalid()) 10441 R.setEnd(Before.getEnd()); 10442 } 10443 10444 static void extendRight(SourceRange &R, SourceRange After) { 10445 if (After.isInvalid()) 10446 return; 10447 if (R.getBegin().isInvalid()) 10448 R.setBegin(After.getBegin()); 10449 R.setEnd(After.getEnd()); 10450 } 10451 10452 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10453 /// well-formednes of the conversion function declarator @p D with 10454 /// type @p R. If there are any errors in the declarator, this routine 10455 /// will emit diagnostics and return true. Otherwise, it will return 10456 /// false. Either way, the type @p R will be updated to reflect a 10457 /// well-formed type for the conversion operator. 10458 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10459 StorageClass& SC) { 10460 // C++ [class.conv.fct]p1: 10461 // Neither parameter types nor return type can be specified. The 10462 // type of a conversion function (8.3.5) is "function taking no 10463 // parameter returning conversion-type-id." 10464 if (SC == SC_Static) { 10465 if (!D.isInvalidType()) 10466 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10467 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10468 << D.getName().getSourceRange(); 10469 D.setInvalidType(); 10470 SC = SC_None; 10471 } 10472 10473 TypeSourceInfo *ConvTSI = nullptr; 10474 QualType ConvType = 10475 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10476 10477 const DeclSpec &DS = D.getDeclSpec(); 10478 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10479 // Conversion functions don't have return types, but the parser will 10480 // happily parse something like: 10481 // 10482 // class X { 10483 // float operator bool(); 10484 // }; 10485 // 10486 // The return type will be changed later anyway. 10487 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10488 << SourceRange(DS.getTypeSpecTypeLoc()) 10489 << SourceRange(D.getIdentifierLoc()); 10490 D.setInvalidType(); 10491 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10492 // It's also plausible that the user writes type qualifiers in the wrong 10493 // place, such as: 10494 // struct S { const operator int(); }; 10495 // FIXME: we could provide a fixit to move the qualifiers onto the 10496 // conversion type. 10497 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10498 << SourceRange(D.getIdentifierLoc()) << 0; 10499 D.setInvalidType(); 10500 } 10501 10502 const auto *Proto = R->castAs<FunctionProtoType>(); 10503 10504 // Make sure we don't have any parameters. 10505 if (Proto->getNumParams() > 0) { 10506 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10507 10508 // Delete the parameters. 10509 D.getFunctionTypeInfo().freeParams(); 10510 D.setInvalidType(); 10511 } else if (Proto->isVariadic()) { 10512 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10513 D.setInvalidType(); 10514 } 10515 10516 // Diagnose "&operator bool()" and other such nonsense. This 10517 // is actually a gcc extension which we don't support. 10518 if (Proto->getReturnType() != ConvType) { 10519 bool NeedsTypedef = false; 10520 SourceRange Before, After; 10521 10522 // Walk the chunks and extract information on them for our diagnostic. 10523 bool PastFunctionChunk = false; 10524 for (auto &Chunk : D.type_objects()) { 10525 switch (Chunk.Kind) { 10526 case DeclaratorChunk::Function: 10527 if (!PastFunctionChunk) { 10528 if (Chunk.Fun.HasTrailingReturnType) { 10529 TypeSourceInfo *TRT = nullptr; 10530 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10531 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10532 } 10533 PastFunctionChunk = true; 10534 break; 10535 } 10536 LLVM_FALLTHROUGH; 10537 case DeclaratorChunk::Array: 10538 NeedsTypedef = true; 10539 extendRight(After, Chunk.getSourceRange()); 10540 break; 10541 10542 case DeclaratorChunk::Pointer: 10543 case DeclaratorChunk::BlockPointer: 10544 case DeclaratorChunk::Reference: 10545 case DeclaratorChunk::MemberPointer: 10546 case DeclaratorChunk::Pipe: 10547 extendLeft(Before, Chunk.getSourceRange()); 10548 break; 10549 10550 case DeclaratorChunk::Paren: 10551 extendLeft(Before, Chunk.Loc); 10552 extendRight(After, Chunk.EndLoc); 10553 break; 10554 } 10555 } 10556 10557 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10558 After.isValid() ? After.getBegin() : 10559 D.getIdentifierLoc(); 10560 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10561 DB << Before << After; 10562 10563 if (!NeedsTypedef) { 10564 DB << /*don't need a typedef*/0; 10565 10566 // If we can provide a correct fix-it hint, do so. 10567 if (After.isInvalid() && ConvTSI) { 10568 SourceLocation InsertLoc = 10569 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10570 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10571 << FixItHint::CreateInsertionFromRange( 10572 InsertLoc, CharSourceRange::getTokenRange(Before)) 10573 << FixItHint::CreateRemoval(Before); 10574 } 10575 } else if (!Proto->getReturnType()->isDependentType()) { 10576 DB << /*typedef*/1 << Proto->getReturnType(); 10577 } else if (getLangOpts().CPlusPlus11) { 10578 DB << /*alias template*/2 << Proto->getReturnType(); 10579 } else { 10580 DB << /*might not be fixable*/3; 10581 } 10582 10583 // Recover by incorporating the other type chunks into the result type. 10584 // Note, this does *not* change the name of the function. This is compatible 10585 // with the GCC extension: 10586 // struct S { &operator int(); } s; 10587 // int &r = s.operator int(); // ok in GCC 10588 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10589 ConvType = Proto->getReturnType(); 10590 } 10591 10592 // C++ [class.conv.fct]p4: 10593 // The conversion-type-id shall not represent a function type nor 10594 // an array type. 10595 if (ConvType->isArrayType()) { 10596 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10597 ConvType = Context.getPointerType(ConvType); 10598 D.setInvalidType(); 10599 } else if (ConvType->isFunctionType()) { 10600 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10601 ConvType = Context.getPointerType(ConvType); 10602 D.setInvalidType(); 10603 } 10604 10605 // Rebuild the function type "R" without any parameters (in case any 10606 // of the errors above fired) and with the conversion type as the 10607 // return type. 10608 if (D.isInvalidType()) 10609 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 10610 10611 // C++0x explicit conversion operators. 10612 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20) 10613 Diag(DS.getExplicitSpecLoc(), 10614 getLangOpts().CPlusPlus11 10615 ? diag::warn_cxx98_compat_explicit_conversion_functions 10616 : diag::ext_explicit_conversion_functions) 10617 << SourceRange(DS.getExplicitSpecRange()); 10618 } 10619 10620 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 10621 /// the declaration of the given C++ conversion function. This routine 10622 /// is responsible for recording the conversion function in the C++ 10623 /// class, if possible. 10624 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 10625 assert(Conversion && "Expected to receive a conversion function declaration"); 10626 10627 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 10628 10629 // Make sure we aren't redeclaring the conversion function. 10630 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 10631 // C++ [class.conv.fct]p1: 10632 // [...] A conversion function is never used to convert a 10633 // (possibly cv-qualified) object to the (possibly cv-qualified) 10634 // same object type (or a reference to it), to a (possibly 10635 // cv-qualified) base class of that type (or a reference to it), 10636 // or to (possibly cv-qualified) void. 10637 QualType ClassType 10638 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10639 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 10640 ConvType = ConvTypeRef->getPointeeType(); 10641 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 10642 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 10643 /* Suppress diagnostics for instantiations. */; 10644 else if (Conversion->size_overridden_methods() != 0) 10645 /* Suppress diagnostics for overriding virtual function in a base class. */; 10646 else if (ConvType->isRecordType()) { 10647 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 10648 if (ConvType == ClassType) 10649 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 10650 << ClassType; 10651 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 10652 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 10653 << ClassType << ConvType; 10654 } else if (ConvType->isVoidType()) { 10655 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 10656 << ClassType << ConvType; 10657 } 10658 10659 if (FunctionTemplateDecl *ConversionTemplate 10660 = Conversion->getDescribedFunctionTemplate()) 10661 return ConversionTemplate; 10662 10663 return Conversion; 10664 } 10665 10666 namespace { 10667 /// Utility class to accumulate and print a diagnostic listing the invalid 10668 /// specifier(s) on a declaration. 10669 struct BadSpecifierDiagnoser { 10670 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10671 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10672 ~BadSpecifierDiagnoser() { 10673 Diagnostic << Specifiers; 10674 } 10675 10676 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10677 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10678 } 10679 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10680 return check(SpecLoc, 10681 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10682 } 10683 void check(SourceLocation SpecLoc, const char *Spec) { 10684 if (SpecLoc.isInvalid()) return; 10685 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10686 if (!Specifiers.empty()) Specifiers += " "; 10687 Specifiers += Spec; 10688 } 10689 10690 Sema &S; 10691 Sema::SemaDiagnosticBuilder Diagnostic; 10692 std::string Specifiers; 10693 }; 10694 } 10695 10696 /// Check the validity of a declarator that we parsed for a deduction-guide. 10697 /// These aren't actually declarators in the grammar, so we need to check that 10698 /// the user didn't specify any pieces that are not part of the deduction-guide 10699 /// grammar. 10700 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10701 StorageClass &SC) { 10702 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10703 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10704 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 10705 10706 // C++ [temp.deduct.guide]p3: 10707 // A deduction-gide shall be declared in the same scope as the 10708 // corresponding class template. 10709 if (!CurContext->getRedeclContext()->Equals( 10710 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10711 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10712 << GuidedTemplateDecl; 10713 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10714 } 10715 10716 auto &DS = D.getMutableDeclSpec(); 10717 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10718 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10719 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10720 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10721 BadSpecifierDiagnoser Diagnoser( 10722 *this, D.getIdentifierLoc(), 10723 diag::err_deduction_guide_invalid_specifier); 10724 10725 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10726 DS.ClearStorageClassSpecs(); 10727 SC = SC_None; 10728 10729 // 'explicit' is permitted. 10730 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10731 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10732 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10733 DS.ClearConstexprSpec(); 10734 10735 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10736 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10737 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10738 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10739 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10740 DS.ClearTypeQualifiers(); 10741 10742 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 10743 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 10744 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 10745 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 10746 DS.ClearTypeSpecType(); 10747 } 10748 10749 if (D.isInvalidType()) 10750 return; 10751 10752 // Check the declarator is simple enough. 10753 bool FoundFunction = false; 10754 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 10755 if (Chunk.Kind == DeclaratorChunk::Paren) 10756 continue; 10757 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 10758 Diag(D.getDeclSpec().getBeginLoc(), 10759 diag::err_deduction_guide_with_complex_decl) 10760 << D.getSourceRange(); 10761 break; 10762 } 10763 if (!Chunk.Fun.hasTrailingReturnType()) { 10764 Diag(D.getName().getBeginLoc(), 10765 diag::err_deduction_guide_no_trailing_return_type); 10766 break; 10767 } 10768 10769 // Check that the return type is written as a specialization of 10770 // the template specified as the deduction-guide's name. 10771 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 10772 TypeSourceInfo *TSI = nullptr; 10773 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 10774 assert(TSI && "deduction guide has valid type but invalid return type?"); 10775 bool AcceptableReturnType = false; 10776 bool MightInstantiateToSpecialization = false; 10777 if (auto RetTST = 10778 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 10779 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 10780 bool TemplateMatches = 10781 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 10782 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 10783 AcceptableReturnType = true; 10784 else { 10785 // This could still instantiate to the right type, unless we know it 10786 // names the wrong class template. 10787 auto *TD = SpecifiedName.getAsTemplateDecl(); 10788 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 10789 !TemplateMatches); 10790 } 10791 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 10792 MightInstantiateToSpecialization = true; 10793 } 10794 10795 if (!AcceptableReturnType) { 10796 Diag(TSI->getTypeLoc().getBeginLoc(), 10797 diag::err_deduction_guide_bad_trailing_return_type) 10798 << GuidedTemplate << TSI->getType() 10799 << MightInstantiateToSpecialization 10800 << TSI->getTypeLoc().getSourceRange(); 10801 } 10802 10803 // Keep going to check that we don't have any inner declarator pieces (we 10804 // could still have a function returning a pointer to a function). 10805 FoundFunction = true; 10806 } 10807 10808 if (D.isFunctionDefinition()) 10809 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 10810 } 10811 10812 //===----------------------------------------------------------------------===// 10813 // Namespace Handling 10814 //===----------------------------------------------------------------------===// 10815 10816 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 10817 /// reopened. 10818 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 10819 SourceLocation Loc, 10820 IdentifierInfo *II, bool *IsInline, 10821 NamespaceDecl *PrevNS) { 10822 assert(*IsInline != PrevNS->isInline()); 10823 10824 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 10825 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 10826 // inline namespaces, with the intention of bringing names into namespace std. 10827 // 10828 // We support this just well enough to get that case working; this is not 10829 // sufficient to support reopening namespaces as inline in general. 10830 if (*IsInline && II && II->getName().startswith("__atomic") && 10831 S.getSourceManager().isInSystemHeader(Loc)) { 10832 // Mark all prior declarations of the namespace as inline. 10833 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 10834 NS = NS->getPreviousDecl()) 10835 NS->setInline(*IsInline); 10836 // Patch up the lookup table for the containing namespace. This isn't really 10837 // correct, but it's good enough for this particular case. 10838 for (auto *I : PrevNS->decls()) 10839 if (auto *ND = dyn_cast<NamedDecl>(I)) 10840 PrevNS->getParent()->makeDeclVisibleInContext(ND); 10841 return; 10842 } 10843 10844 if (PrevNS->isInline()) 10845 // The user probably just forgot the 'inline', so suggest that it 10846 // be added back. 10847 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 10848 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 10849 else 10850 S.Diag(Loc, diag::err_inline_namespace_mismatch); 10851 10852 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 10853 *IsInline = PrevNS->isInline(); 10854 } 10855 10856 /// ActOnStartNamespaceDef - This is called at the start of a namespace 10857 /// definition. 10858 Decl *Sema::ActOnStartNamespaceDef( 10859 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 10860 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 10861 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 10862 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 10863 // For anonymous namespace, take the location of the left brace. 10864 SourceLocation Loc = II ? IdentLoc : LBrace; 10865 bool IsInline = InlineLoc.isValid(); 10866 bool IsInvalid = false; 10867 bool IsStd = false; 10868 bool AddToKnown = false; 10869 Scope *DeclRegionScope = NamespcScope->getParent(); 10870 10871 NamespaceDecl *PrevNS = nullptr; 10872 if (II) { 10873 // C++ [namespace.def]p2: 10874 // The identifier in an original-namespace-definition shall not 10875 // have been previously defined in the declarative region in 10876 // which the original-namespace-definition appears. The 10877 // identifier in an original-namespace-definition is the name of 10878 // the namespace. Subsequently in that declarative region, it is 10879 // treated as an original-namespace-name. 10880 // 10881 // Since namespace names are unique in their scope, and we don't 10882 // look through using directives, just look for any ordinary names 10883 // as if by qualified name lookup. 10884 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 10885 ForExternalRedeclaration); 10886 LookupQualifiedName(R, CurContext->getRedeclContext()); 10887 NamedDecl *PrevDecl = 10888 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 10889 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 10890 10891 if (PrevNS) { 10892 // This is an extended namespace definition. 10893 if (IsInline != PrevNS->isInline()) 10894 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 10895 &IsInline, PrevNS); 10896 } else if (PrevDecl) { 10897 // This is an invalid name redefinition. 10898 Diag(Loc, diag::err_redefinition_different_kind) 10899 << II; 10900 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10901 IsInvalid = true; 10902 // Continue on to push Namespc as current DeclContext and return it. 10903 } else if (II->isStr("std") && 10904 CurContext->getRedeclContext()->isTranslationUnit()) { 10905 // This is the first "real" definition of the namespace "std", so update 10906 // our cache of the "std" namespace to point at this definition. 10907 PrevNS = getStdNamespace(); 10908 IsStd = true; 10909 AddToKnown = !IsInline; 10910 } else { 10911 // We've seen this namespace for the first time. 10912 AddToKnown = !IsInline; 10913 } 10914 } else { 10915 // Anonymous namespaces. 10916 10917 // Determine whether the parent already has an anonymous namespace. 10918 DeclContext *Parent = CurContext->getRedeclContext(); 10919 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10920 PrevNS = TU->getAnonymousNamespace(); 10921 } else { 10922 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 10923 PrevNS = ND->getAnonymousNamespace(); 10924 } 10925 10926 if (PrevNS && IsInline != PrevNS->isInline()) 10927 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 10928 &IsInline, PrevNS); 10929 } 10930 10931 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 10932 StartLoc, Loc, II, PrevNS); 10933 if (IsInvalid) 10934 Namespc->setInvalidDecl(); 10935 10936 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 10937 AddPragmaAttributes(DeclRegionScope, Namespc); 10938 10939 // FIXME: Should we be merging attributes? 10940 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 10941 PushNamespaceVisibilityAttr(Attr, Loc); 10942 10943 if (IsStd) 10944 StdNamespace = Namespc; 10945 if (AddToKnown) 10946 KnownNamespaces[Namespc] = false; 10947 10948 if (II) { 10949 PushOnScopeChains(Namespc, DeclRegionScope); 10950 } else { 10951 // Link the anonymous namespace into its parent. 10952 DeclContext *Parent = CurContext->getRedeclContext(); 10953 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10954 TU->setAnonymousNamespace(Namespc); 10955 } else { 10956 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 10957 } 10958 10959 CurContext->addDecl(Namespc); 10960 10961 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 10962 // behaves as if it were replaced by 10963 // namespace unique { /* empty body */ } 10964 // using namespace unique; 10965 // namespace unique { namespace-body } 10966 // where all occurrences of 'unique' in a translation unit are 10967 // replaced by the same identifier and this identifier differs 10968 // from all other identifiers in the entire program. 10969 10970 // We just create the namespace with an empty name and then add an 10971 // implicit using declaration, just like the standard suggests. 10972 // 10973 // CodeGen enforces the "universally unique" aspect by giving all 10974 // declarations semantically contained within an anonymous 10975 // namespace internal linkage. 10976 10977 if (!PrevNS) { 10978 UD = UsingDirectiveDecl::Create(Context, Parent, 10979 /* 'using' */ LBrace, 10980 /* 'namespace' */ SourceLocation(), 10981 /* qualifier */ NestedNameSpecifierLoc(), 10982 /* identifier */ SourceLocation(), 10983 Namespc, 10984 /* Ancestor */ Parent); 10985 UD->setImplicit(); 10986 Parent->addDecl(UD); 10987 } 10988 } 10989 10990 ActOnDocumentableDecl(Namespc); 10991 10992 // Although we could have an invalid decl (i.e. the namespace name is a 10993 // redefinition), push it as current DeclContext and try to continue parsing. 10994 // FIXME: We should be able to push Namespc here, so that the each DeclContext 10995 // for the namespace has the declarations that showed up in that particular 10996 // namespace definition. 10997 PushDeclContext(NamespcScope, Namespc); 10998 return Namespc; 10999 } 11000 11001 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 11002 /// is a namespace alias, returns the namespace it points to. 11003 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 11004 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 11005 return AD->getNamespace(); 11006 return dyn_cast_or_null<NamespaceDecl>(D); 11007 } 11008 11009 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 11010 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 11011 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 11012 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 11013 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 11014 Namespc->setRBraceLoc(RBrace); 11015 PopDeclContext(); 11016 if (Namespc->hasAttr<VisibilityAttr>()) 11017 PopPragmaVisibility(true, RBrace); 11018 // If this namespace contains an export-declaration, export it now. 11019 if (DeferredExportedNamespaces.erase(Namespc)) 11020 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 11021 } 11022 11023 CXXRecordDecl *Sema::getStdBadAlloc() const { 11024 return cast_or_null<CXXRecordDecl>( 11025 StdBadAlloc.get(Context.getExternalSource())); 11026 } 11027 11028 EnumDecl *Sema::getStdAlignValT() const { 11029 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 11030 } 11031 11032 NamespaceDecl *Sema::getStdNamespace() const { 11033 return cast_or_null<NamespaceDecl>( 11034 StdNamespace.get(Context.getExternalSource())); 11035 } 11036 11037 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 11038 if (!StdExperimentalNamespaceCache) { 11039 if (auto Std = getStdNamespace()) { 11040 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 11041 SourceLocation(), LookupNamespaceName); 11042 if (!LookupQualifiedName(Result, Std) || 11043 !(StdExperimentalNamespaceCache = 11044 Result.getAsSingle<NamespaceDecl>())) 11045 Result.suppressDiagnostics(); 11046 } 11047 } 11048 return StdExperimentalNamespaceCache; 11049 } 11050 11051 namespace { 11052 11053 enum UnsupportedSTLSelect { 11054 USS_InvalidMember, 11055 USS_MissingMember, 11056 USS_NonTrivial, 11057 USS_Other 11058 }; 11059 11060 struct InvalidSTLDiagnoser { 11061 Sema &S; 11062 SourceLocation Loc; 11063 QualType TyForDiags; 11064 11065 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 11066 const VarDecl *VD = nullptr) { 11067 { 11068 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 11069 << TyForDiags << ((int)Sel); 11070 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 11071 assert(!Name.empty()); 11072 D << Name; 11073 } 11074 } 11075 if (Sel == USS_InvalidMember) { 11076 S.Diag(VD->getLocation(), diag::note_var_declared_here) 11077 << VD << VD->getSourceRange(); 11078 } 11079 return QualType(); 11080 } 11081 }; 11082 } // namespace 11083 11084 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 11085 SourceLocation Loc, 11086 ComparisonCategoryUsage Usage) { 11087 assert(getLangOpts().CPlusPlus && 11088 "Looking for comparison category type outside of C++."); 11089 11090 // Use an elaborated type for diagnostics which has a name containing the 11091 // prepended 'std' namespace but not any inline namespace names. 11092 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 11093 auto *NNS = 11094 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 11095 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 11096 }; 11097 11098 // Check if we've already successfully checked the comparison category type 11099 // before. If so, skip checking it again. 11100 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 11101 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 11102 // The only thing we need to check is that the type has a reachable 11103 // definition in the current context. 11104 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11105 return QualType(); 11106 11107 return Info->getType(); 11108 } 11109 11110 // If lookup failed 11111 if (!Info) { 11112 std::string NameForDiags = "std::"; 11113 NameForDiags += ComparisonCategories::getCategoryString(Kind); 11114 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 11115 << NameForDiags << (int)Usage; 11116 return QualType(); 11117 } 11118 11119 assert(Info->Kind == Kind); 11120 assert(Info->Record); 11121 11122 // Update the Record decl in case we encountered a forward declaration on our 11123 // first pass. FIXME: This is a bit of a hack. 11124 if (Info->Record->hasDefinition()) 11125 Info->Record = Info->Record->getDefinition(); 11126 11127 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11128 return QualType(); 11129 11130 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 11131 11132 if (!Info->Record->isTriviallyCopyable()) 11133 return UnsupportedSTLError(USS_NonTrivial); 11134 11135 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 11136 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 11137 // Tolerate empty base classes. 11138 if (Base->isEmpty()) 11139 continue; 11140 // Reject STL implementations which have at least one non-empty base. 11141 return UnsupportedSTLError(); 11142 } 11143 11144 // Check that the STL has implemented the types using a single integer field. 11145 // This expectation allows better codegen for builtin operators. We require: 11146 // (1) The class has exactly one field. 11147 // (2) The field is an integral or enumeration type. 11148 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 11149 if (std::distance(FIt, FEnd) != 1 || 11150 !FIt->getType()->isIntegralOrEnumerationType()) { 11151 return UnsupportedSTLError(); 11152 } 11153 11154 // Build each of the require values and store them in Info. 11155 for (ComparisonCategoryResult CCR : 11156 ComparisonCategories::getPossibleResultsForType(Kind)) { 11157 StringRef MemName = ComparisonCategories::getResultString(CCR); 11158 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 11159 11160 if (!ValInfo) 11161 return UnsupportedSTLError(USS_MissingMember, MemName); 11162 11163 VarDecl *VD = ValInfo->VD; 11164 assert(VD && "should not be null!"); 11165 11166 // Attempt to diagnose reasons why the STL definition of this type 11167 // might be foobar, including it failing to be a constant expression. 11168 // TODO Handle more ways the lookup or result can be invalid. 11169 if (!VD->isStaticDataMember() || 11170 !VD->isUsableInConstantExpressions(Context)) 11171 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 11172 11173 // Attempt to evaluate the var decl as a constant expression and extract 11174 // the value of its first field as a ICE. If this fails, the STL 11175 // implementation is not supported. 11176 if (!ValInfo->hasValidIntValue()) 11177 return UnsupportedSTLError(); 11178 11179 MarkVariableReferenced(Loc, VD); 11180 } 11181 11182 // We've successfully built the required types and expressions. Update 11183 // the cache and return the newly cached value. 11184 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 11185 return Info->getType(); 11186 } 11187 11188 /// Retrieve the special "std" namespace, which may require us to 11189 /// implicitly define the namespace. 11190 NamespaceDecl *Sema::getOrCreateStdNamespace() { 11191 if (!StdNamespace) { 11192 // The "std" namespace has not yet been defined, so build one implicitly. 11193 StdNamespace = NamespaceDecl::Create(Context, 11194 Context.getTranslationUnitDecl(), 11195 /*Inline=*/false, 11196 SourceLocation(), SourceLocation(), 11197 &PP.getIdentifierTable().get("std"), 11198 /*PrevDecl=*/nullptr); 11199 getStdNamespace()->setImplicit(true); 11200 } 11201 11202 return getStdNamespace(); 11203 } 11204 11205 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 11206 assert(getLangOpts().CPlusPlus && 11207 "Looking for std::initializer_list outside of C++."); 11208 11209 // We're looking for implicit instantiations of 11210 // template <typename E> class std::initializer_list. 11211 11212 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 11213 return false; 11214 11215 ClassTemplateDecl *Template = nullptr; 11216 const TemplateArgument *Arguments = nullptr; 11217 11218 if (const RecordType *RT = Ty->getAs<RecordType>()) { 11219 11220 ClassTemplateSpecializationDecl *Specialization = 11221 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 11222 if (!Specialization) 11223 return false; 11224 11225 Template = Specialization->getSpecializedTemplate(); 11226 Arguments = Specialization->getTemplateArgs().data(); 11227 } else if (const TemplateSpecializationType *TST = 11228 Ty->getAs<TemplateSpecializationType>()) { 11229 Template = dyn_cast_or_null<ClassTemplateDecl>( 11230 TST->getTemplateName().getAsTemplateDecl()); 11231 Arguments = TST->getArgs(); 11232 } 11233 if (!Template) 11234 return false; 11235 11236 if (!StdInitializerList) { 11237 // Haven't recognized std::initializer_list yet, maybe this is it. 11238 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 11239 if (TemplateClass->getIdentifier() != 11240 &PP.getIdentifierTable().get("initializer_list") || 11241 !getStdNamespace()->InEnclosingNamespaceSetOf( 11242 TemplateClass->getDeclContext())) 11243 return false; 11244 // This is a template called std::initializer_list, but is it the right 11245 // template? 11246 TemplateParameterList *Params = Template->getTemplateParameters(); 11247 if (Params->getMinRequiredArguments() != 1) 11248 return false; 11249 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 11250 return false; 11251 11252 // It's the right template. 11253 StdInitializerList = Template; 11254 } 11255 11256 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 11257 return false; 11258 11259 // This is an instance of std::initializer_list. Find the argument type. 11260 if (Element) 11261 *Element = Arguments[0].getAsType(); 11262 return true; 11263 } 11264 11265 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 11266 NamespaceDecl *Std = S.getStdNamespace(); 11267 if (!Std) { 11268 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11269 return nullptr; 11270 } 11271 11272 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 11273 Loc, Sema::LookupOrdinaryName); 11274 if (!S.LookupQualifiedName(Result, Std)) { 11275 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11276 return nullptr; 11277 } 11278 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 11279 if (!Template) { 11280 Result.suppressDiagnostics(); 11281 // We found something weird. Complain about the first thing we found. 11282 NamedDecl *Found = *Result.begin(); 11283 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 11284 return nullptr; 11285 } 11286 11287 // We found some template called std::initializer_list. Now verify that it's 11288 // correct. 11289 TemplateParameterList *Params = Template->getTemplateParameters(); 11290 if (Params->getMinRequiredArguments() != 1 || 11291 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 11292 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 11293 return nullptr; 11294 } 11295 11296 return Template; 11297 } 11298 11299 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 11300 if (!StdInitializerList) { 11301 StdInitializerList = LookupStdInitializerList(*this, Loc); 11302 if (!StdInitializerList) 11303 return QualType(); 11304 } 11305 11306 TemplateArgumentListInfo Args(Loc, Loc); 11307 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 11308 Context.getTrivialTypeSourceInfo(Element, 11309 Loc))); 11310 return Context.getCanonicalType( 11311 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 11312 } 11313 11314 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 11315 // C++ [dcl.init.list]p2: 11316 // A constructor is an initializer-list constructor if its first parameter 11317 // is of type std::initializer_list<E> or reference to possibly cv-qualified 11318 // std::initializer_list<E> for some type E, and either there are no other 11319 // parameters or else all other parameters have default arguments. 11320 if (!Ctor->hasOneParamOrDefaultArgs()) 11321 return false; 11322 11323 QualType ArgType = Ctor->getParamDecl(0)->getType(); 11324 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 11325 ArgType = RT->getPointeeType().getUnqualifiedType(); 11326 11327 return isStdInitializerList(ArgType, nullptr); 11328 } 11329 11330 /// Determine whether a using statement is in a context where it will be 11331 /// apply in all contexts. 11332 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 11333 switch (CurContext->getDeclKind()) { 11334 case Decl::TranslationUnit: 11335 return true; 11336 case Decl::LinkageSpec: 11337 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 11338 default: 11339 return false; 11340 } 11341 } 11342 11343 namespace { 11344 11345 // Callback to only accept typo corrections that are namespaces. 11346 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 11347 public: 11348 bool ValidateCandidate(const TypoCorrection &candidate) override { 11349 if (NamedDecl *ND = candidate.getCorrectionDecl()) 11350 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 11351 return false; 11352 } 11353 11354 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11355 return std::make_unique<NamespaceValidatorCCC>(*this); 11356 } 11357 }; 11358 11359 } 11360 11361 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 11362 CXXScopeSpec &SS, 11363 SourceLocation IdentLoc, 11364 IdentifierInfo *Ident) { 11365 R.clear(); 11366 NamespaceValidatorCCC CCC{}; 11367 if (TypoCorrection Corrected = 11368 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 11369 Sema::CTK_ErrorRecovery)) { 11370 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 11371 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 11372 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 11373 Ident->getName().equals(CorrectedStr); 11374 S.diagnoseTypo(Corrected, 11375 S.PDiag(diag::err_using_directive_member_suggest) 11376 << Ident << DC << DroppedSpecifier << SS.getRange(), 11377 S.PDiag(diag::note_namespace_defined_here)); 11378 } else { 11379 S.diagnoseTypo(Corrected, 11380 S.PDiag(diag::err_using_directive_suggest) << Ident, 11381 S.PDiag(diag::note_namespace_defined_here)); 11382 } 11383 R.addDecl(Corrected.getFoundDecl()); 11384 return true; 11385 } 11386 return false; 11387 } 11388 11389 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 11390 SourceLocation NamespcLoc, CXXScopeSpec &SS, 11391 SourceLocation IdentLoc, 11392 IdentifierInfo *NamespcName, 11393 const ParsedAttributesView &AttrList) { 11394 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11395 assert(NamespcName && "Invalid NamespcName."); 11396 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 11397 11398 // This can only happen along a recovery path. 11399 while (S->isTemplateParamScope()) 11400 S = S->getParent(); 11401 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11402 11403 UsingDirectiveDecl *UDir = nullptr; 11404 NestedNameSpecifier *Qualifier = nullptr; 11405 if (SS.isSet()) 11406 Qualifier = SS.getScopeRep(); 11407 11408 // Lookup namespace name. 11409 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 11410 LookupParsedName(R, S, &SS); 11411 if (R.isAmbiguous()) 11412 return nullptr; 11413 11414 if (R.empty()) { 11415 R.clear(); 11416 // Allow "using namespace std;" or "using namespace ::std;" even if 11417 // "std" hasn't been defined yet, for GCC compatibility. 11418 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11419 NamespcName->isStr("std")) { 11420 Diag(IdentLoc, diag::ext_using_undefined_std); 11421 R.addDecl(getOrCreateStdNamespace()); 11422 R.resolveKind(); 11423 } 11424 // Otherwise, attempt typo correction. 11425 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11426 } 11427 11428 if (!R.empty()) { 11429 NamedDecl *Named = R.getRepresentativeDecl(); 11430 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11431 assert(NS && "expected namespace decl"); 11432 11433 // The use of a nested name specifier may trigger deprecation warnings. 11434 DiagnoseUseOfDecl(Named, IdentLoc); 11435 11436 // C++ [namespace.udir]p1: 11437 // A using-directive specifies that the names in the nominated 11438 // namespace can be used in the scope in which the 11439 // using-directive appears after the using-directive. During 11440 // unqualified name lookup (3.4.1), the names appear as if they 11441 // were declared in the nearest enclosing namespace which 11442 // contains both the using-directive and the nominated 11443 // namespace. [Note: in this context, "contains" means "contains 11444 // directly or indirectly". ] 11445 11446 // Find enclosing context containing both using-directive and 11447 // nominated namespace. 11448 DeclContext *CommonAncestor = NS; 11449 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11450 CommonAncestor = CommonAncestor->getParent(); 11451 11452 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11453 SS.getWithLocInContext(Context), 11454 IdentLoc, Named, CommonAncestor); 11455 11456 if (IsUsingDirectiveInToplevelContext(CurContext) && 11457 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11458 Diag(IdentLoc, diag::warn_using_directive_in_header); 11459 } 11460 11461 PushUsingDirective(S, UDir); 11462 } else { 11463 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11464 } 11465 11466 if (UDir) 11467 ProcessDeclAttributeList(S, UDir, AttrList); 11468 11469 return UDir; 11470 } 11471 11472 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11473 // If the scope has an associated entity and the using directive is at 11474 // namespace or translation unit scope, add the UsingDirectiveDecl into 11475 // its lookup structure so qualified name lookup can find it. 11476 DeclContext *Ctx = S->getEntity(); 11477 if (Ctx && !Ctx->isFunctionOrMethod()) 11478 Ctx->addDecl(UDir); 11479 else 11480 // Otherwise, it is at block scope. The using-directives will affect lookup 11481 // only to the end of the scope. 11482 S->PushUsingDirective(UDir); 11483 } 11484 11485 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11486 SourceLocation UsingLoc, 11487 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11488 UnqualifiedId &Name, 11489 SourceLocation EllipsisLoc, 11490 const ParsedAttributesView &AttrList) { 11491 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11492 11493 if (SS.isEmpty()) { 11494 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11495 return nullptr; 11496 } 11497 11498 switch (Name.getKind()) { 11499 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11500 case UnqualifiedIdKind::IK_Identifier: 11501 case UnqualifiedIdKind::IK_OperatorFunctionId: 11502 case UnqualifiedIdKind::IK_LiteralOperatorId: 11503 case UnqualifiedIdKind::IK_ConversionFunctionId: 11504 break; 11505 11506 case UnqualifiedIdKind::IK_ConstructorName: 11507 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11508 // C++11 inheriting constructors. 11509 Diag(Name.getBeginLoc(), 11510 getLangOpts().CPlusPlus11 11511 ? diag::warn_cxx98_compat_using_decl_constructor 11512 : diag::err_using_decl_constructor) 11513 << SS.getRange(); 11514 11515 if (getLangOpts().CPlusPlus11) break; 11516 11517 return nullptr; 11518 11519 case UnqualifiedIdKind::IK_DestructorName: 11520 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11521 return nullptr; 11522 11523 case UnqualifiedIdKind::IK_TemplateId: 11524 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11525 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11526 return nullptr; 11527 11528 case UnqualifiedIdKind::IK_DeductionGuideName: 11529 llvm_unreachable("cannot parse qualified deduction guide name"); 11530 } 11531 11532 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11533 DeclarationName TargetName = TargetNameInfo.getName(); 11534 if (!TargetName) 11535 return nullptr; 11536 11537 // Warn about access declarations. 11538 if (UsingLoc.isInvalid()) { 11539 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11540 ? diag::err_access_decl 11541 : diag::warn_access_decl_deprecated) 11542 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11543 } 11544 11545 if (EllipsisLoc.isInvalid()) { 11546 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11547 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11548 return nullptr; 11549 } else { 11550 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11551 !TargetNameInfo.containsUnexpandedParameterPack()) { 11552 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11553 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11554 EllipsisLoc = SourceLocation(); 11555 } 11556 } 11557 11558 NamedDecl *UD = 11559 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 11560 SS, TargetNameInfo, EllipsisLoc, AttrList, 11561 /*IsInstantiation*/false); 11562 if (UD) 11563 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11564 11565 return UD; 11566 } 11567 11568 /// Determine whether a using declaration considers the given 11569 /// declarations as "equivalent", e.g., if they are redeclarations of 11570 /// the same entity or are both typedefs of the same type. 11571 static bool 11572 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11573 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11574 return true; 11575 11576 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11577 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11578 return Context.hasSameType(TD1->getUnderlyingType(), 11579 TD2->getUnderlyingType()); 11580 11581 return false; 11582 } 11583 11584 11585 /// Determines whether to create a using shadow decl for a particular 11586 /// decl, given the set of decls existing prior to this using lookup. 11587 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 11588 const LookupResult &Previous, 11589 UsingShadowDecl *&PrevShadow) { 11590 // Diagnose finding a decl which is not from a base class of the 11591 // current class. We do this now because there are cases where this 11592 // function will silently decide not to build a shadow decl, which 11593 // will pre-empt further diagnostics. 11594 // 11595 // We don't need to do this in C++11 because we do the check once on 11596 // the qualifier. 11597 // 11598 // FIXME: diagnose the following if we care enough: 11599 // struct A { int foo; }; 11600 // struct B : A { using A::foo; }; 11601 // template <class T> struct C : A {}; 11602 // template <class T> struct D : C<T> { using B::foo; } // <--- 11603 // This is invalid (during instantiation) in C++03 because B::foo 11604 // resolves to the using decl in B, which is not a base class of D<T>. 11605 // We can't diagnose it immediately because C<T> is an unknown 11606 // specialization. The UsingShadowDecl in D<T> then points directly 11607 // to A::foo, which will look well-formed when we instantiate. 11608 // The right solution is to not collapse the shadow-decl chain. 11609 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 11610 DeclContext *OrigDC = Orig->getDeclContext(); 11611 11612 // Handle enums and anonymous structs. 11613 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 11614 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 11615 while (OrigRec->isAnonymousStructOrUnion()) 11616 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 11617 11618 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 11619 if (OrigDC == CurContext) { 11620 Diag(Using->getLocation(), 11621 diag::err_using_decl_nested_name_specifier_is_current_class) 11622 << Using->getQualifierLoc().getSourceRange(); 11623 Diag(Orig->getLocation(), diag::note_using_decl_target); 11624 Using->setInvalidDecl(); 11625 return true; 11626 } 11627 11628 Diag(Using->getQualifierLoc().getBeginLoc(), 11629 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11630 << Using->getQualifier() 11631 << cast<CXXRecordDecl>(CurContext) 11632 << Using->getQualifierLoc().getSourceRange(); 11633 Diag(Orig->getLocation(), diag::note_using_decl_target); 11634 Using->setInvalidDecl(); 11635 return true; 11636 } 11637 } 11638 11639 if (Previous.empty()) return false; 11640 11641 NamedDecl *Target = Orig; 11642 if (isa<UsingShadowDecl>(Target)) 11643 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11644 11645 // If the target happens to be one of the previous declarations, we 11646 // don't have a conflict. 11647 // 11648 // FIXME: but we might be increasing its access, in which case we 11649 // should redeclare it. 11650 NamedDecl *NonTag = nullptr, *Tag = nullptr; 11651 bool FoundEquivalentDecl = false; 11652 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 11653 I != E; ++I) { 11654 NamedDecl *D = (*I)->getUnderlyingDecl(); 11655 // We can have UsingDecls in our Previous results because we use the same 11656 // LookupResult for checking whether the UsingDecl itself is a valid 11657 // redeclaration. 11658 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 11659 continue; 11660 11661 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 11662 // C++ [class.mem]p19: 11663 // If T is the name of a class, then [every named member other than 11664 // a non-static data member] shall have a name different from T 11665 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11666 !isa<IndirectFieldDecl>(Target) && 11667 !isa<UnresolvedUsingValueDecl>(Target) && 11668 DiagnoseClassNameShadow( 11669 CurContext, 11670 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 11671 return true; 11672 } 11673 11674 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11675 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11676 PrevShadow = Shadow; 11677 FoundEquivalentDecl = true; 11678 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11679 // We don't conflict with an existing using shadow decl of an equivalent 11680 // declaration, but we're not a redeclaration of it. 11681 FoundEquivalentDecl = true; 11682 } 11683 11684 if (isVisible(D)) 11685 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11686 } 11687 11688 if (FoundEquivalentDecl) 11689 return false; 11690 11691 if (FunctionDecl *FD = Target->getAsFunction()) { 11692 NamedDecl *OldDecl = nullptr; 11693 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11694 /*IsForUsingDecl*/ true)) { 11695 case Ovl_Overload: 11696 return false; 11697 11698 case Ovl_NonFunction: 11699 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11700 break; 11701 11702 // We found a decl with the exact signature. 11703 case Ovl_Match: 11704 // If we're in a record, we want to hide the target, so we 11705 // return true (without a diagnostic) to tell the caller not to 11706 // build a shadow decl. 11707 if (CurContext->isRecord()) 11708 return true; 11709 11710 // If we're not in a record, this is an error. 11711 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11712 break; 11713 } 11714 11715 Diag(Target->getLocation(), diag::note_using_decl_target); 11716 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 11717 Using->setInvalidDecl(); 11718 return true; 11719 } 11720 11721 // Target is not a function. 11722 11723 if (isa<TagDecl>(Target)) { 11724 // No conflict between a tag and a non-tag. 11725 if (!Tag) return false; 11726 11727 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11728 Diag(Target->getLocation(), diag::note_using_decl_target); 11729 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 11730 Using->setInvalidDecl(); 11731 return true; 11732 } 11733 11734 // No conflict between a tag and a non-tag. 11735 if (!NonTag) return false; 11736 11737 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11738 Diag(Target->getLocation(), diag::note_using_decl_target); 11739 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 11740 Using->setInvalidDecl(); 11741 return true; 11742 } 11743 11744 /// Determine whether a direct base class is a virtual base class. 11745 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 11746 if (!Derived->getNumVBases()) 11747 return false; 11748 for (auto &B : Derived->bases()) 11749 if (B.getType()->getAsCXXRecordDecl() == Base) 11750 return B.isVirtual(); 11751 llvm_unreachable("not a direct base class"); 11752 } 11753 11754 /// Builds a shadow declaration corresponding to a 'using' declaration. 11755 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 11756 UsingDecl *UD, 11757 NamedDecl *Orig, 11758 UsingShadowDecl *PrevDecl) { 11759 // If we resolved to another shadow declaration, just coalesce them. 11760 NamedDecl *Target = Orig; 11761 if (isa<UsingShadowDecl>(Target)) { 11762 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11763 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 11764 } 11765 11766 NamedDecl *NonTemplateTarget = Target; 11767 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 11768 NonTemplateTarget = TargetTD->getTemplatedDecl(); 11769 11770 UsingShadowDecl *Shadow; 11771 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 11772 bool IsVirtualBase = 11773 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 11774 UD->getQualifier()->getAsRecordDecl()); 11775 Shadow = ConstructorUsingShadowDecl::Create( 11776 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 11777 } else { 11778 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 11779 Target); 11780 } 11781 UD->addShadowDecl(Shadow); 11782 11783 Shadow->setAccess(UD->getAccess()); 11784 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 11785 Shadow->setInvalidDecl(); 11786 11787 Shadow->setPreviousDecl(PrevDecl); 11788 11789 if (S) 11790 PushOnScopeChains(Shadow, S); 11791 else 11792 CurContext->addDecl(Shadow); 11793 11794 11795 return Shadow; 11796 } 11797 11798 /// Hides a using shadow declaration. This is required by the current 11799 /// using-decl implementation when a resolvable using declaration in a 11800 /// class is followed by a declaration which would hide or override 11801 /// one or more of the using decl's targets; for example: 11802 /// 11803 /// struct Base { void foo(int); }; 11804 /// struct Derived : Base { 11805 /// using Base::foo; 11806 /// void foo(int); 11807 /// }; 11808 /// 11809 /// The governing language is C++03 [namespace.udecl]p12: 11810 /// 11811 /// When a using-declaration brings names from a base class into a 11812 /// derived class scope, member functions in the derived class 11813 /// override and/or hide member functions with the same name and 11814 /// parameter types in a base class (rather than conflicting). 11815 /// 11816 /// There are two ways to implement this: 11817 /// (1) optimistically create shadow decls when they're not hidden 11818 /// by existing declarations, or 11819 /// (2) don't create any shadow decls (or at least don't make them 11820 /// visible) until we've fully parsed/instantiated the class. 11821 /// The problem with (1) is that we might have to retroactively remove 11822 /// a shadow decl, which requires several O(n) operations because the 11823 /// decl structures are (very reasonably) not designed for removal. 11824 /// (2) avoids this but is very fiddly and phase-dependent. 11825 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 11826 if (Shadow->getDeclName().getNameKind() == 11827 DeclarationName::CXXConversionFunctionName) 11828 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 11829 11830 // Remove it from the DeclContext... 11831 Shadow->getDeclContext()->removeDecl(Shadow); 11832 11833 // ...and the scope, if applicable... 11834 if (S) { 11835 S->RemoveDecl(Shadow); 11836 IdResolver.RemoveDecl(Shadow); 11837 } 11838 11839 // ...and the using decl. 11840 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 11841 11842 // TODO: complain somehow if Shadow was used. It shouldn't 11843 // be possible for this to happen, because...? 11844 } 11845 11846 /// Find the base specifier for a base class with the given type. 11847 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 11848 QualType DesiredBase, 11849 bool &AnyDependentBases) { 11850 // Check whether the named type is a direct base class. 11851 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 11852 .getUnqualifiedType(); 11853 for (auto &Base : Derived->bases()) { 11854 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 11855 if (CanonicalDesiredBase == BaseType) 11856 return &Base; 11857 if (BaseType->isDependentType()) 11858 AnyDependentBases = true; 11859 } 11860 return nullptr; 11861 } 11862 11863 namespace { 11864 class UsingValidatorCCC final : public CorrectionCandidateCallback { 11865 public: 11866 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 11867 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 11868 : HasTypenameKeyword(HasTypenameKeyword), 11869 IsInstantiation(IsInstantiation), OldNNS(NNS), 11870 RequireMemberOf(RequireMemberOf) {} 11871 11872 bool ValidateCandidate(const TypoCorrection &Candidate) override { 11873 NamedDecl *ND = Candidate.getCorrectionDecl(); 11874 11875 // Keywords are not valid here. 11876 if (!ND || isa<NamespaceDecl>(ND)) 11877 return false; 11878 11879 // Completely unqualified names are invalid for a 'using' declaration. 11880 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 11881 return false; 11882 11883 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 11884 // reject. 11885 11886 if (RequireMemberOf) { 11887 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11888 if (FoundRecord && FoundRecord->isInjectedClassName()) { 11889 // No-one ever wants a using-declaration to name an injected-class-name 11890 // of a base class, unless they're declaring an inheriting constructor. 11891 ASTContext &Ctx = ND->getASTContext(); 11892 if (!Ctx.getLangOpts().CPlusPlus11) 11893 return false; 11894 QualType FoundType = Ctx.getRecordType(FoundRecord); 11895 11896 // Check that the injected-class-name is named as a member of its own 11897 // type; we don't want to suggest 'using Derived::Base;', since that 11898 // means something else. 11899 NestedNameSpecifier *Specifier = 11900 Candidate.WillReplaceSpecifier() 11901 ? Candidate.getCorrectionSpecifier() 11902 : OldNNS; 11903 if (!Specifier->getAsType() || 11904 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 11905 return false; 11906 11907 // Check that this inheriting constructor declaration actually names a 11908 // direct base class of the current class. 11909 bool AnyDependentBases = false; 11910 if (!findDirectBaseWithType(RequireMemberOf, 11911 Ctx.getRecordType(FoundRecord), 11912 AnyDependentBases) && 11913 !AnyDependentBases) 11914 return false; 11915 } else { 11916 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 11917 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 11918 return false; 11919 11920 // FIXME: Check that the base class member is accessible? 11921 } 11922 } else { 11923 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11924 if (FoundRecord && FoundRecord->isInjectedClassName()) 11925 return false; 11926 } 11927 11928 if (isa<TypeDecl>(ND)) 11929 return HasTypenameKeyword || !IsInstantiation; 11930 11931 return !HasTypenameKeyword; 11932 } 11933 11934 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11935 return std::make_unique<UsingValidatorCCC>(*this); 11936 } 11937 11938 private: 11939 bool HasTypenameKeyword; 11940 bool IsInstantiation; 11941 NestedNameSpecifier *OldNNS; 11942 CXXRecordDecl *RequireMemberOf; 11943 }; 11944 } // end anonymous namespace 11945 11946 /// Builds a using declaration. 11947 /// 11948 /// \param IsInstantiation - Whether this call arises from an 11949 /// instantiation of an unresolved using declaration. We treat 11950 /// the lookup differently for these declarations. 11951 NamedDecl *Sema::BuildUsingDeclaration( 11952 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 11953 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 11954 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 11955 const ParsedAttributesView &AttrList, bool IsInstantiation) { 11956 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11957 SourceLocation IdentLoc = NameInfo.getLoc(); 11958 assert(IdentLoc.isValid() && "Invalid TargetName location."); 11959 11960 // FIXME: We ignore attributes for now. 11961 11962 // For an inheriting constructor declaration, the name of the using 11963 // declaration is the name of a constructor in this class, not in the 11964 // base class. 11965 DeclarationNameInfo UsingName = NameInfo; 11966 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 11967 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 11968 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 11969 Context.getCanonicalType(Context.getRecordType(RD)))); 11970 11971 // Do the redeclaration lookup in the current scope. 11972 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 11973 ForVisibleRedeclaration); 11974 Previous.setHideTags(false); 11975 if (S) { 11976 LookupName(Previous, S); 11977 11978 // It is really dumb that we have to do this. 11979 LookupResult::Filter F = Previous.makeFilter(); 11980 while (F.hasNext()) { 11981 NamedDecl *D = F.next(); 11982 if (!isDeclInScope(D, CurContext, S)) 11983 F.erase(); 11984 // If we found a local extern declaration that's not ordinarily visible, 11985 // and this declaration is being added to a non-block scope, ignore it. 11986 // We're only checking for scope conflicts here, not also for violations 11987 // of the linkage rules. 11988 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 11989 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 11990 F.erase(); 11991 } 11992 F.done(); 11993 } else { 11994 assert(IsInstantiation && "no scope in non-instantiation"); 11995 if (CurContext->isRecord()) 11996 LookupQualifiedName(Previous, CurContext); 11997 else { 11998 // No redeclaration check is needed here; in non-member contexts we 11999 // diagnosed all possible conflicts with other using-declarations when 12000 // building the template: 12001 // 12002 // For a dependent non-type using declaration, the only valid case is 12003 // if we instantiate to a single enumerator. We check for conflicts 12004 // between shadow declarations we introduce, and we check in the template 12005 // definition for conflicts between a non-type using declaration and any 12006 // other declaration, which together covers all cases. 12007 // 12008 // A dependent typename using declaration will never successfully 12009 // instantiate, since it will always name a class member, so we reject 12010 // that in the template definition. 12011 } 12012 } 12013 12014 // Check for invalid redeclarations. 12015 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 12016 SS, IdentLoc, Previous)) 12017 return nullptr; 12018 12019 // Check for bad qualifiers. 12020 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 12021 IdentLoc)) 12022 return nullptr; 12023 12024 DeclContext *LookupContext = computeDeclContext(SS); 12025 NamedDecl *D; 12026 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12027 if (!LookupContext || EllipsisLoc.isValid()) { 12028 if (HasTypenameKeyword) { 12029 // FIXME: not all declaration name kinds are legal here 12030 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 12031 UsingLoc, TypenameLoc, 12032 QualifierLoc, 12033 IdentLoc, NameInfo.getName(), 12034 EllipsisLoc); 12035 } else { 12036 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 12037 QualifierLoc, NameInfo, EllipsisLoc); 12038 } 12039 D->setAccess(AS); 12040 CurContext->addDecl(D); 12041 return D; 12042 } 12043 12044 auto Build = [&](bool Invalid) { 12045 UsingDecl *UD = 12046 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 12047 UsingName, HasTypenameKeyword); 12048 UD->setAccess(AS); 12049 CurContext->addDecl(UD); 12050 UD->setInvalidDecl(Invalid); 12051 return UD; 12052 }; 12053 auto BuildInvalid = [&]{ return Build(true); }; 12054 auto BuildValid = [&]{ return Build(false); }; 12055 12056 if (RequireCompleteDeclContext(SS, LookupContext)) 12057 return BuildInvalid(); 12058 12059 // Look up the target name. 12060 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12061 12062 // Unlike most lookups, we don't always want to hide tag 12063 // declarations: tag names are visible through the using declaration 12064 // even if hidden by ordinary names, *except* in a dependent context 12065 // where it's important for the sanity of two-phase lookup. 12066 if (!IsInstantiation) 12067 R.setHideTags(false); 12068 12069 // For the purposes of this lookup, we have a base object type 12070 // equal to that of the current context. 12071 if (CurContext->isRecord()) { 12072 R.setBaseObjectType( 12073 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 12074 } 12075 12076 LookupQualifiedName(R, LookupContext); 12077 12078 // Try to correct typos if possible. If constructor name lookup finds no 12079 // results, that means the named class has no explicit constructors, and we 12080 // suppressed declaring implicit ones (probably because it's dependent or 12081 // invalid). 12082 if (R.empty() && 12083 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 12084 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 12085 // it will believe that glibc provides a ::gets in cases where it does not, 12086 // and will try to pull it into namespace std with a using-declaration. 12087 // Just ignore the using-declaration in that case. 12088 auto *II = NameInfo.getName().getAsIdentifierInfo(); 12089 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 12090 CurContext->isStdNamespace() && 12091 isa<TranslationUnitDecl>(LookupContext) && 12092 getSourceManager().isInSystemHeader(UsingLoc)) 12093 return nullptr; 12094 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 12095 dyn_cast<CXXRecordDecl>(CurContext)); 12096 if (TypoCorrection Corrected = 12097 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 12098 CTK_ErrorRecovery)) { 12099 // We reject candidates where DroppedSpecifier == true, hence the 12100 // literal '0' below. 12101 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 12102 << NameInfo.getName() << LookupContext << 0 12103 << SS.getRange()); 12104 12105 // If we picked a correction with no attached Decl we can't do anything 12106 // useful with it, bail out. 12107 NamedDecl *ND = Corrected.getCorrectionDecl(); 12108 if (!ND) 12109 return BuildInvalid(); 12110 12111 // If we corrected to an inheriting constructor, handle it as one. 12112 auto *RD = dyn_cast<CXXRecordDecl>(ND); 12113 if (RD && RD->isInjectedClassName()) { 12114 // The parent of the injected class name is the class itself. 12115 RD = cast<CXXRecordDecl>(RD->getParent()); 12116 12117 // Fix up the information we'll use to build the using declaration. 12118 if (Corrected.WillReplaceSpecifier()) { 12119 NestedNameSpecifierLocBuilder Builder; 12120 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 12121 QualifierLoc.getSourceRange()); 12122 QualifierLoc = Builder.getWithLocInContext(Context); 12123 } 12124 12125 // In this case, the name we introduce is the name of a derived class 12126 // constructor. 12127 auto *CurClass = cast<CXXRecordDecl>(CurContext); 12128 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12129 Context.getCanonicalType(Context.getRecordType(CurClass)))); 12130 UsingName.setNamedTypeInfo(nullptr); 12131 for (auto *Ctor : LookupConstructors(RD)) 12132 R.addDecl(Ctor); 12133 R.resolveKind(); 12134 } else { 12135 // FIXME: Pick up all the declarations if we found an overloaded 12136 // function. 12137 UsingName.setName(ND->getDeclName()); 12138 R.addDecl(ND); 12139 } 12140 } else { 12141 Diag(IdentLoc, diag::err_no_member) 12142 << NameInfo.getName() << LookupContext << SS.getRange(); 12143 return BuildInvalid(); 12144 } 12145 } 12146 12147 if (R.isAmbiguous()) 12148 return BuildInvalid(); 12149 12150 if (HasTypenameKeyword) { 12151 // If we asked for a typename and got a non-type decl, error out. 12152 if (!R.getAsSingle<TypeDecl>()) { 12153 Diag(IdentLoc, diag::err_using_typename_non_type); 12154 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12155 Diag((*I)->getUnderlyingDecl()->getLocation(), 12156 diag::note_using_decl_target); 12157 return BuildInvalid(); 12158 } 12159 } else { 12160 // If we asked for a non-typename and we got a type, error out, 12161 // but only if this is an instantiation of an unresolved using 12162 // decl. Otherwise just silently find the type name. 12163 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 12164 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 12165 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 12166 return BuildInvalid(); 12167 } 12168 } 12169 12170 // C++14 [namespace.udecl]p6: 12171 // A using-declaration shall not name a namespace. 12172 if (R.getAsSingle<NamespaceDecl>()) { 12173 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 12174 << SS.getRange(); 12175 return BuildInvalid(); 12176 } 12177 12178 // C++14 [namespace.udecl]p7: 12179 // A using-declaration shall not name a scoped enumerator. 12180 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 12181 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 12182 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 12183 << SS.getRange(); 12184 return BuildInvalid(); 12185 } 12186 } 12187 12188 UsingDecl *UD = BuildValid(); 12189 12190 // Some additional rules apply to inheriting constructors. 12191 if (UsingName.getName().getNameKind() == 12192 DeclarationName::CXXConstructorName) { 12193 // Suppress access diagnostics; the access check is instead performed at the 12194 // point of use for an inheriting constructor. 12195 R.suppressDiagnostics(); 12196 if (CheckInheritingConstructorUsingDecl(UD)) 12197 return UD; 12198 } 12199 12200 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 12201 UsingShadowDecl *PrevDecl = nullptr; 12202 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 12203 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 12204 } 12205 12206 return UD; 12207 } 12208 12209 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 12210 ArrayRef<NamedDecl *> Expansions) { 12211 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 12212 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 12213 isa<UsingPackDecl>(InstantiatedFrom)); 12214 12215 auto *UPD = 12216 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 12217 UPD->setAccess(InstantiatedFrom->getAccess()); 12218 CurContext->addDecl(UPD); 12219 return UPD; 12220 } 12221 12222 /// Additional checks for a using declaration referring to a constructor name. 12223 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 12224 assert(!UD->hasTypename() && "expecting a constructor name"); 12225 12226 const Type *SourceType = UD->getQualifier()->getAsType(); 12227 assert(SourceType && 12228 "Using decl naming constructor doesn't have type in scope spec."); 12229 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 12230 12231 // Check whether the named type is a direct base class. 12232 bool AnyDependentBases = false; 12233 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 12234 AnyDependentBases); 12235 if (!Base && !AnyDependentBases) { 12236 Diag(UD->getUsingLoc(), 12237 diag::err_using_decl_constructor_not_in_direct_base) 12238 << UD->getNameInfo().getSourceRange() 12239 << QualType(SourceType, 0) << TargetClass; 12240 UD->setInvalidDecl(); 12241 return true; 12242 } 12243 12244 if (Base) 12245 Base->setInheritConstructors(); 12246 12247 return false; 12248 } 12249 12250 /// Checks that the given using declaration is not an invalid 12251 /// redeclaration. Note that this is checking only for the using decl 12252 /// itself, not for any ill-formedness among the UsingShadowDecls. 12253 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 12254 bool HasTypenameKeyword, 12255 const CXXScopeSpec &SS, 12256 SourceLocation NameLoc, 12257 const LookupResult &Prev) { 12258 NestedNameSpecifier *Qual = SS.getScopeRep(); 12259 12260 // C++03 [namespace.udecl]p8: 12261 // C++0x [namespace.udecl]p10: 12262 // A using-declaration is a declaration and can therefore be used 12263 // repeatedly where (and only where) multiple declarations are 12264 // allowed. 12265 // 12266 // That's in non-member contexts. 12267 if (!CurContext->getRedeclContext()->isRecord()) { 12268 // A dependent qualifier outside a class can only ever resolve to an 12269 // enumeration type. Therefore it conflicts with any other non-type 12270 // declaration in the same scope. 12271 // FIXME: How should we check for dependent type-type conflicts at block 12272 // scope? 12273 if (Qual->isDependent() && !HasTypenameKeyword) { 12274 for (auto *D : Prev) { 12275 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 12276 bool OldCouldBeEnumerator = 12277 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 12278 Diag(NameLoc, 12279 OldCouldBeEnumerator ? diag::err_redefinition 12280 : diag::err_redefinition_different_kind) 12281 << Prev.getLookupName(); 12282 Diag(D->getLocation(), diag::note_previous_definition); 12283 return true; 12284 } 12285 } 12286 } 12287 return false; 12288 } 12289 12290 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 12291 NamedDecl *D = *I; 12292 12293 bool DTypename; 12294 NestedNameSpecifier *DQual; 12295 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 12296 DTypename = UD->hasTypename(); 12297 DQual = UD->getQualifier(); 12298 } else if (UnresolvedUsingValueDecl *UD 12299 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 12300 DTypename = false; 12301 DQual = UD->getQualifier(); 12302 } else if (UnresolvedUsingTypenameDecl *UD 12303 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 12304 DTypename = true; 12305 DQual = UD->getQualifier(); 12306 } else continue; 12307 12308 // using decls differ if one says 'typename' and the other doesn't. 12309 // FIXME: non-dependent using decls? 12310 if (HasTypenameKeyword != DTypename) continue; 12311 12312 // using decls differ if they name different scopes (but note that 12313 // template instantiation can cause this check to trigger when it 12314 // didn't before instantiation). 12315 if (Context.getCanonicalNestedNameSpecifier(Qual) != 12316 Context.getCanonicalNestedNameSpecifier(DQual)) 12317 continue; 12318 12319 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 12320 Diag(D->getLocation(), diag::note_using_decl) << 1; 12321 return true; 12322 } 12323 12324 return false; 12325 } 12326 12327 12328 /// Checks that the given nested-name qualifier used in a using decl 12329 /// in the current context is appropriately related to the current 12330 /// scope. If an error is found, diagnoses it and returns true. 12331 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 12332 bool HasTypename, 12333 const CXXScopeSpec &SS, 12334 const DeclarationNameInfo &NameInfo, 12335 SourceLocation NameLoc) { 12336 DeclContext *NamedContext = computeDeclContext(SS); 12337 12338 if (!CurContext->isRecord()) { 12339 // C++03 [namespace.udecl]p3: 12340 // C++0x [namespace.udecl]p8: 12341 // A using-declaration for a class member shall be a member-declaration. 12342 12343 // If we weren't able to compute a valid scope, it might validly be a 12344 // dependent class scope or a dependent enumeration unscoped scope. If 12345 // we have a 'typename' keyword, the scope must resolve to a class type. 12346 if ((HasTypename && !NamedContext) || 12347 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 12348 auto *RD = NamedContext 12349 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 12350 : nullptr; 12351 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 12352 RD = nullptr; 12353 12354 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 12355 << SS.getRange(); 12356 12357 // If we have a complete, non-dependent source type, try to suggest a 12358 // way to get the same effect. 12359 if (!RD) 12360 return true; 12361 12362 // Find what this using-declaration was referring to. 12363 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12364 R.setHideTags(false); 12365 R.suppressDiagnostics(); 12366 LookupQualifiedName(R, RD); 12367 12368 if (R.getAsSingle<TypeDecl>()) { 12369 if (getLangOpts().CPlusPlus11) { 12370 // Convert 'using X::Y;' to 'using Y = X::Y;'. 12371 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 12372 << 0 // alias declaration 12373 << FixItHint::CreateInsertion(SS.getBeginLoc(), 12374 NameInfo.getName().getAsString() + 12375 " = "); 12376 } else { 12377 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 12378 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 12379 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 12380 << 1 // typedef declaration 12381 << FixItHint::CreateReplacement(UsingLoc, "typedef") 12382 << FixItHint::CreateInsertion( 12383 InsertLoc, " " + NameInfo.getName().getAsString()); 12384 } 12385 } else if (R.getAsSingle<VarDecl>()) { 12386 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12387 // repeating the type of the static data member here. 12388 FixItHint FixIt; 12389 if (getLangOpts().CPlusPlus11) { 12390 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12391 FixIt = FixItHint::CreateReplacement( 12392 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 12393 } 12394 12395 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12396 << 2 // reference declaration 12397 << FixIt; 12398 } else if (R.getAsSingle<EnumConstantDecl>()) { 12399 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12400 // repeating the type of the enumeration here, and we can't do so if 12401 // the type is anonymous. 12402 FixItHint FixIt; 12403 if (getLangOpts().CPlusPlus11) { 12404 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12405 FixIt = FixItHint::CreateReplacement( 12406 UsingLoc, 12407 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 12408 } 12409 12410 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12411 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 12412 << FixIt; 12413 } 12414 return true; 12415 } 12416 12417 // Otherwise, this might be valid. 12418 return false; 12419 } 12420 12421 // The current scope is a record. 12422 12423 // If the named context is dependent, we can't decide much. 12424 if (!NamedContext) { 12425 // FIXME: in C++0x, we can diagnose if we can prove that the 12426 // nested-name-specifier does not refer to a base class, which is 12427 // still possible in some cases. 12428 12429 // Otherwise we have to conservatively report that things might be 12430 // okay. 12431 return false; 12432 } 12433 12434 if (!NamedContext->isRecord()) { 12435 // Ideally this would point at the last name in the specifier, 12436 // but we don't have that level of source info. 12437 Diag(SS.getRange().getBegin(), 12438 diag::err_using_decl_nested_name_specifier_is_not_class) 12439 << SS.getScopeRep() << SS.getRange(); 12440 return true; 12441 } 12442 12443 if (!NamedContext->isDependentContext() && 12444 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 12445 return true; 12446 12447 if (getLangOpts().CPlusPlus11) { 12448 // C++11 [namespace.udecl]p3: 12449 // In a using-declaration used as a member-declaration, the 12450 // nested-name-specifier shall name a base class of the class 12451 // being defined. 12452 12453 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 12454 cast<CXXRecordDecl>(NamedContext))) { 12455 if (CurContext == NamedContext) { 12456 Diag(NameLoc, 12457 diag::err_using_decl_nested_name_specifier_is_current_class) 12458 << SS.getRange(); 12459 return true; 12460 } 12461 12462 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 12463 Diag(SS.getRange().getBegin(), 12464 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12465 << SS.getScopeRep() 12466 << cast<CXXRecordDecl>(CurContext) 12467 << SS.getRange(); 12468 } 12469 return true; 12470 } 12471 12472 return false; 12473 } 12474 12475 // C++03 [namespace.udecl]p4: 12476 // A using-declaration used as a member-declaration shall refer 12477 // to a member of a base class of the class being defined [etc.]. 12478 12479 // Salient point: SS doesn't have to name a base class as long as 12480 // lookup only finds members from base classes. Therefore we can 12481 // diagnose here only if we can prove that that can't happen, 12482 // i.e. if the class hierarchies provably don't intersect. 12483 12484 // TODO: it would be nice if "definitely valid" results were cached 12485 // in the UsingDecl and UsingShadowDecl so that these checks didn't 12486 // need to be repeated. 12487 12488 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 12489 auto Collect = [&Bases](const CXXRecordDecl *Base) { 12490 Bases.insert(Base); 12491 return true; 12492 }; 12493 12494 // Collect all bases. Return false if we find a dependent base. 12495 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 12496 return false; 12497 12498 // Returns true if the base is dependent or is one of the accumulated base 12499 // classes. 12500 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 12501 return !Bases.count(Base); 12502 }; 12503 12504 // Return false if the class has a dependent base or if it or one 12505 // of its bases is present in the base set of the current context. 12506 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 12507 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 12508 return false; 12509 12510 Diag(SS.getRange().getBegin(), 12511 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12512 << SS.getScopeRep() 12513 << cast<CXXRecordDecl>(CurContext) 12514 << SS.getRange(); 12515 12516 return true; 12517 } 12518 12519 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 12520 MultiTemplateParamsArg TemplateParamLists, 12521 SourceLocation UsingLoc, UnqualifiedId &Name, 12522 const ParsedAttributesView &AttrList, 12523 TypeResult Type, Decl *DeclFromDeclSpec) { 12524 // Skip up to the relevant declaration scope. 12525 while (S->isTemplateParamScope()) 12526 S = S->getParent(); 12527 assert((S->getFlags() & Scope::DeclScope) && 12528 "got alias-declaration outside of declaration scope"); 12529 12530 if (Type.isInvalid()) 12531 return nullptr; 12532 12533 bool Invalid = false; 12534 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 12535 TypeSourceInfo *TInfo = nullptr; 12536 GetTypeFromParser(Type.get(), &TInfo); 12537 12538 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 12539 return nullptr; 12540 12541 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 12542 UPPC_DeclarationType)) { 12543 Invalid = true; 12544 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12545 TInfo->getTypeLoc().getBeginLoc()); 12546 } 12547 12548 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12549 TemplateParamLists.size() 12550 ? forRedeclarationInCurContext() 12551 : ForVisibleRedeclaration); 12552 LookupName(Previous, S); 12553 12554 // Warn about shadowing the name of a template parameter. 12555 if (Previous.isSingleResult() && 12556 Previous.getFoundDecl()->isTemplateParameter()) { 12557 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 12558 Previous.clear(); 12559 } 12560 12561 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 12562 "name in alias declaration must be an identifier"); 12563 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 12564 Name.StartLocation, 12565 Name.Identifier, TInfo); 12566 12567 NewTD->setAccess(AS); 12568 12569 if (Invalid) 12570 NewTD->setInvalidDecl(); 12571 12572 ProcessDeclAttributeList(S, NewTD, AttrList); 12573 AddPragmaAttributes(S, NewTD); 12574 12575 CheckTypedefForVariablyModifiedType(S, NewTD); 12576 Invalid |= NewTD->isInvalidDecl(); 12577 12578 bool Redeclaration = false; 12579 12580 NamedDecl *NewND; 12581 if (TemplateParamLists.size()) { 12582 TypeAliasTemplateDecl *OldDecl = nullptr; 12583 TemplateParameterList *OldTemplateParams = nullptr; 12584 12585 if (TemplateParamLists.size() != 1) { 12586 Diag(UsingLoc, diag::err_alias_template_extra_headers) 12587 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 12588 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 12589 } 12590 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 12591 12592 // Check that we can declare a template here. 12593 if (CheckTemplateDeclScope(S, TemplateParams)) 12594 return nullptr; 12595 12596 // Only consider previous declarations in the same scope. 12597 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 12598 /*ExplicitInstantiationOrSpecialization*/false); 12599 if (!Previous.empty()) { 12600 Redeclaration = true; 12601 12602 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 12603 if (!OldDecl && !Invalid) { 12604 Diag(UsingLoc, diag::err_redefinition_different_kind) 12605 << Name.Identifier; 12606 12607 NamedDecl *OldD = Previous.getRepresentativeDecl(); 12608 if (OldD->getLocation().isValid()) 12609 Diag(OldD->getLocation(), diag::note_previous_definition); 12610 12611 Invalid = true; 12612 } 12613 12614 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 12615 if (TemplateParameterListsAreEqual(TemplateParams, 12616 OldDecl->getTemplateParameters(), 12617 /*Complain=*/true, 12618 TPL_TemplateMatch)) 12619 OldTemplateParams = 12620 OldDecl->getMostRecentDecl()->getTemplateParameters(); 12621 else 12622 Invalid = true; 12623 12624 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 12625 if (!Invalid && 12626 !Context.hasSameType(OldTD->getUnderlyingType(), 12627 NewTD->getUnderlyingType())) { 12628 // FIXME: The C++0x standard does not clearly say this is ill-formed, 12629 // but we can't reasonably accept it. 12630 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 12631 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 12632 if (OldTD->getLocation().isValid()) 12633 Diag(OldTD->getLocation(), diag::note_previous_definition); 12634 Invalid = true; 12635 } 12636 } 12637 } 12638 12639 // Merge any previous default template arguments into our parameters, 12640 // and check the parameter list. 12641 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 12642 TPC_TypeAliasTemplate)) 12643 return nullptr; 12644 12645 TypeAliasTemplateDecl *NewDecl = 12646 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 12647 Name.Identifier, TemplateParams, 12648 NewTD); 12649 NewTD->setDescribedAliasTemplate(NewDecl); 12650 12651 NewDecl->setAccess(AS); 12652 12653 if (Invalid) 12654 NewDecl->setInvalidDecl(); 12655 else if (OldDecl) { 12656 NewDecl->setPreviousDecl(OldDecl); 12657 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 12658 } 12659 12660 NewND = NewDecl; 12661 } else { 12662 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 12663 setTagNameForLinkagePurposes(TD, NewTD); 12664 handleTagNumbering(TD, S); 12665 } 12666 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 12667 NewND = NewTD; 12668 } 12669 12670 PushOnScopeChains(NewND, S); 12671 ActOnDocumentableDecl(NewND); 12672 return NewND; 12673 } 12674 12675 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 12676 SourceLocation AliasLoc, 12677 IdentifierInfo *Alias, CXXScopeSpec &SS, 12678 SourceLocation IdentLoc, 12679 IdentifierInfo *Ident) { 12680 12681 // Lookup the namespace name. 12682 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 12683 LookupParsedName(R, S, &SS); 12684 12685 if (R.isAmbiguous()) 12686 return nullptr; 12687 12688 if (R.empty()) { 12689 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 12690 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 12691 return nullptr; 12692 } 12693 } 12694 assert(!R.isAmbiguous() && !R.empty()); 12695 NamedDecl *ND = R.getRepresentativeDecl(); 12696 12697 // Check if we have a previous declaration with the same name. 12698 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 12699 ForVisibleRedeclaration); 12700 LookupName(PrevR, S); 12701 12702 // Check we're not shadowing a template parameter. 12703 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 12704 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 12705 PrevR.clear(); 12706 } 12707 12708 // Filter out any other lookup result from an enclosing scope. 12709 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 12710 /*AllowInlineNamespace*/false); 12711 12712 // Find the previous declaration and check that we can redeclare it. 12713 NamespaceAliasDecl *Prev = nullptr; 12714 if (PrevR.isSingleResult()) { 12715 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 12716 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 12717 // We already have an alias with the same name that points to the same 12718 // namespace; check that it matches. 12719 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 12720 Prev = AD; 12721 } else if (isVisible(PrevDecl)) { 12722 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 12723 << Alias; 12724 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 12725 << AD->getNamespace(); 12726 return nullptr; 12727 } 12728 } else if (isVisible(PrevDecl)) { 12729 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 12730 ? diag::err_redefinition 12731 : diag::err_redefinition_different_kind; 12732 Diag(AliasLoc, DiagID) << Alias; 12733 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12734 return nullptr; 12735 } 12736 } 12737 12738 // The use of a nested name specifier may trigger deprecation warnings. 12739 DiagnoseUseOfDecl(ND, IdentLoc); 12740 12741 NamespaceAliasDecl *AliasDecl = 12742 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 12743 Alias, SS.getWithLocInContext(Context), 12744 IdentLoc, ND); 12745 if (Prev) 12746 AliasDecl->setPreviousDecl(Prev); 12747 12748 PushOnScopeChains(AliasDecl, S); 12749 return AliasDecl; 12750 } 12751 12752 namespace { 12753 struct SpecialMemberExceptionSpecInfo 12754 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 12755 SourceLocation Loc; 12756 Sema::ImplicitExceptionSpecification ExceptSpec; 12757 12758 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 12759 Sema::CXXSpecialMember CSM, 12760 Sema::InheritedConstructorInfo *ICI, 12761 SourceLocation Loc) 12762 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 12763 12764 bool visitBase(CXXBaseSpecifier *Base); 12765 bool visitField(FieldDecl *FD); 12766 12767 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 12768 unsigned Quals); 12769 12770 void visitSubobjectCall(Subobject Subobj, 12771 Sema::SpecialMemberOverloadResult SMOR); 12772 }; 12773 } 12774 12775 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 12776 auto *RT = Base->getType()->getAs<RecordType>(); 12777 if (!RT) 12778 return false; 12779 12780 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 12781 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 12782 if (auto *BaseCtor = SMOR.getMethod()) { 12783 visitSubobjectCall(Base, BaseCtor); 12784 return false; 12785 } 12786 12787 visitClassSubobject(BaseClass, Base, 0); 12788 return false; 12789 } 12790 12791 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 12792 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 12793 Expr *E = FD->getInClassInitializer(); 12794 if (!E) 12795 // FIXME: It's a little wasteful to build and throw away a 12796 // CXXDefaultInitExpr here. 12797 // FIXME: We should have a single context note pointing at Loc, and 12798 // this location should be MD->getLocation() instead, since that's 12799 // the location where we actually use the default init expression. 12800 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 12801 if (E) 12802 ExceptSpec.CalledExpr(E); 12803 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 12804 ->getAs<RecordType>()) { 12805 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 12806 FD->getType().getCVRQualifiers()); 12807 } 12808 return false; 12809 } 12810 12811 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 12812 Subobject Subobj, 12813 unsigned Quals) { 12814 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 12815 bool IsMutable = Field && Field->isMutable(); 12816 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 12817 } 12818 12819 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 12820 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 12821 // Note, if lookup fails, it doesn't matter what exception specification we 12822 // choose because the special member will be deleted. 12823 if (CXXMethodDecl *MD = SMOR.getMethod()) 12824 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 12825 } 12826 12827 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 12828 llvm::APSInt Result; 12829 ExprResult Converted = CheckConvertedConstantExpression( 12830 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 12831 ExplicitSpec.setExpr(Converted.get()); 12832 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 12833 ExplicitSpec.setKind(Result.getBoolValue() 12834 ? ExplicitSpecKind::ResolvedTrue 12835 : ExplicitSpecKind::ResolvedFalse); 12836 return true; 12837 } 12838 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 12839 return false; 12840 } 12841 12842 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 12843 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 12844 if (!ExplicitExpr->isTypeDependent()) 12845 tryResolveExplicitSpecifier(ES); 12846 return ES; 12847 } 12848 12849 static Sema::ImplicitExceptionSpecification 12850 ComputeDefaultedSpecialMemberExceptionSpec( 12851 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 12852 Sema::InheritedConstructorInfo *ICI) { 12853 ComputingExceptionSpec CES(S, MD, Loc); 12854 12855 CXXRecordDecl *ClassDecl = MD->getParent(); 12856 12857 // C++ [except.spec]p14: 12858 // An implicitly declared special member function (Clause 12) shall have an 12859 // exception-specification. [...] 12860 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 12861 if (ClassDecl->isInvalidDecl()) 12862 return Info.ExceptSpec; 12863 12864 // FIXME: If this diagnostic fires, we're probably missing a check for 12865 // attempting to resolve an exception specification before it's known 12866 // at a higher level. 12867 if (S.RequireCompleteType(MD->getLocation(), 12868 S.Context.getRecordType(ClassDecl), 12869 diag::err_exception_spec_incomplete_type)) 12870 return Info.ExceptSpec; 12871 12872 // C++1z [except.spec]p7: 12873 // [Look for exceptions thrown by] a constructor selected [...] to 12874 // initialize a potentially constructed subobject, 12875 // C++1z [except.spec]p8: 12876 // The exception specification for an implicitly-declared destructor, or a 12877 // destructor without a noexcept-specifier, is potentially-throwing if and 12878 // only if any of the destructors for any of its potentially constructed 12879 // subojects is potentially throwing. 12880 // FIXME: We respect the first rule but ignore the "potentially constructed" 12881 // in the second rule to resolve a core issue (no number yet) that would have 12882 // us reject: 12883 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 12884 // struct B : A {}; 12885 // struct C : B { void f(); }; 12886 // ... due to giving B::~B() a non-throwing exception specification. 12887 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 12888 : Info.VisitAllBases); 12889 12890 return Info.ExceptSpec; 12891 } 12892 12893 namespace { 12894 /// RAII object to register a special member as being currently declared. 12895 struct DeclaringSpecialMember { 12896 Sema &S; 12897 Sema::SpecialMemberDecl D; 12898 Sema::ContextRAII SavedContext; 12899 bool WasAlreadyBeingDeclared; 12900 12901 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 12902 : S(S), D(RD, CSM), SavedContext(S, RD) { 12903 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 12904 if (WasAlreadyBeingDeclared) 12905 // This almost never happens, but if it does, ensure that our cache 12906 // doesn't contain a stale result. 12907 S.SpecialMemberCache.clear(); 12908 else { 12909 // Register a note to be produced if we encounter an error while 12910 // declaring the special member. 12911 Sema::CodeSynthesisContext Ctx; 12912 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 12913 // FIXME: We don't have a location to use here. Using the class's 12914 // location maintains the fiction that we declare all special members 12915 // with the class, but (1) it's not clear that lying about that helps our 12916 // users understand what's going on, and (2) there may be outer contexts 12917 // on the stack (some of which are relevant) and printing them exposes 12918 // our lies. 12919 Ctx.PointOfInstantiation = RD->getLocation(); 12920 Ctx.Entity = RD; 12921 Ctx.SpecialMember = CSM; 12922 S.pushCodeSynthesisContext(Ctx); 12923 } 12924 } 12925 ~DeclaringSpecialMember() { 12926 if (!WasAlreadyBeingDeclared) { 12927 S.SpecialMembersBeingDeclared.erase(D); 12928 S.popCodeSynthesisContext(); 12929 } 12930 } 12931 12932 /// Are we already trying to declare this special member? 12933 bool isAlreadyBeingDeclared() const { 12934 return WasAlreadyBeingDeclared; 12935 } 12936 }; 12937 } 12938 12939 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 12940 // Look up any existing declarations, but don't trigger declaration of all 12941 // implicit special members with this name. 12942 DeclarationName Name = FD->getDeclName(); 12943 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 12944 ForExternalRedeclaration); 12945 for (auto *D : FD->getParent()->lookup(Name)) 12946 if (auto *Acceptable = R.getAcceptableDecl(D)) 12947 R.addDecl(Acceptable); 12948 R.resolveKind(); 12949 R.suppressDiagnostics(); 12950 12951 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 12952 } 12953 12954 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 12955 QualType ResultTy, 12956 ArrayRef<QualType> Args) { 12957 // Build an exception specification pointing back at this constructor. 12958 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 12959 12960 LangAS AS = getDefaultCXXMethodAddrSpace(); 12961 if (AS != LangAS::Default) { 12962 EPI.TypeQuals.addAddressSpace(AS); 12963 } 12964 12965 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 12966 SpecialMem->setType(QT); 12967 } 12968 12969 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 12970 CXXRecordDecl *ClassDecl) { 12971 // C++ [class.ctor]p5: 12972 // A default constructor for a class X is a constructor of class X 12973 // that can be called without an argument. If there is no 12974 // user-declared constructor for class X, a default constructor is 12975 // implicitly declared. An implicitly-declared default constructor 12976 // is an inline public member of its class. 12977 assert(ClassDecl->needsImplicitDefaultConstructor() && 12978 "Should not build implicit default constructor!"); 12979 12980 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 12981 if (DSM.isAlreadyBeingDeclared()) 12982 return nullptr; 12983 12984 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12985 CXXDefaultConstructor, 12986 false); 12987 12988 // Create the actual constructor declaration. 12989 CanQualType ClassType 12990 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 12991 SourceLocation ClassLoc = ClassDecl->getLocation(); 12992 DeclarationName Name 12993 = Context.DeclarationNames.getCXXConstructorName(ClassType); 12994 DeclarationNameInfo NameInfo(Name, ClassLoc); 12995 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 12996 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 12997 /*TInfo=*/nullptr, ExplicitSpecifier(), 12998 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12999 Constexpr ? ConstexprSpecKind::Constexpr 13000 : ConstexprSpecKind::Unspecified); 13001 DefaultCon->setAccess(AS_public); 13002 DefaultCon->setDefaulted(); 13003 13004 if (getLangOpts().CUDA) { 13005 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 13006 DefaultCon, 13007 /* ConstRHS */ false, 13008 /* Diagnose */ false); 13009 } 13010 13011 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 13012 13013 // We don't need to use SpecialMemberIsTrivial here; triviality for default 13014 // constructors is easy to compute. 13015 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 13016 13017 // Note that we have declared this constructor. 13018 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 13019 13020 Scope *S = getScopeForContext(ClassDecl); 13021 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 13022 13023 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 13024 SetDeclDeleted(DefaultCon, ClassLoc); 13025 13026 if (S) 13027 PushOnScopeChains(DefaultCon, S, false); 13028 ClassDecl->addDecl(DefaultCon); 13029 13030 return DefaultCon; 13031 } 13032 13033 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 13034 CXXConstructorDecl *Constructor) { 13035 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 13036 !Constructor->doesThisDeclarationHaveABody() && 13037 !Constructor->isDeleted()) && 13038 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 13039 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13040 return; 13041 13042 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13043 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 13044 13045 SynthesizedFunctionScope Scope(*this, Constructor); 13046 13047 // The exception specification is needed because we are defining the 13048 // function. 13049 ResolveExceptionSpec(CurrentLocation, 13050 Constructor->getType()->castAs<FunctionProtoType>()); 13051 MarkVTableUsed(CurrentLocation, ClassDecl); 13052 13053 // Add a context note for diagnostics produced after this point. 13054 Scope.addContextNote(CurrentLocation); 13055 13056 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 13057 Constructor->setInvalidDecl(); 13058 return; 13059 } 13060 13061 SourceLocation Loc = Constructor->getEndLoc().isValid() 13062 ? Constructor->getEndLoc() 13063 : Constructor->getLocation(); 13064 Constructor->setBody(new (Context) CompoundStmt(Loc)); 13065 Constructor->markUsed(Context); 13066 13067 if (ASTMutationListener *L = getASTMutationListener()) { 13068 L->CompletedImplicitDefinition(Constructor); 13069 } 13070 13071 DiagnoseUninitializedFields(*this, Constructor); 13072 } 13073 13074 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 13075 // Perform any delayed checks on exception specifications. 13076 CheckDelayedMemberExceptionSpecs(); 13077 } 13078 13079 /// Find or create the fake constructor we synthesize to model constructing an 13080 /// object of a derived class via a constructor of a base class. 13081 CXXConstructorDecl * 13082 Sema::findInheritingConstructor(SourceLocation Loc, 13083 CXXConstructorDecl *BaseCtor, 13084 ConstructorUsingShadowDecl *Shadow) { 13085 CXXRecordDecl *Derived = Shadow->getParent(); 13086 SourceLocation UsingLoc = Shadow->getLocation(); 13087 13088 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 13089 // For now we use the name of the base class constructor as a member of the 13090 // derived class to indicate a (fake) inherited constructor name. 13091 DeclarationName Name = BaseCtor->getDeclName(); 13092 13093 // Check to see if we already have a fake constructor for this inherited 13094 // constructor call. 13095 for (NamedDecl *Ctor : Derived->lookup(Name)) 13096 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 13097 ->getInheritedConstructor() 13098 .getConstructor(), 13099 BaseCtor)) 13100 return cast<CXXConstructorDecl>(Ctor); 13101 13102 DeclarationNameInfo NameInfo(Name, UsingLoc); 13103 TypeSourceInfo *TInfo = 13104 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 13105 FunctionProtoTypeLoc ProtoLoc = 13106 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 13107 13108 // Check the inherited constructor is valid and find the list of base classes 13109 // from which it was inherited. 13110 InheritedConstructorInfo ICI(*this, Loc, Shadow); 13111 13112 bool Constexpr = 13113 BaseCtor->isConstexpr() && 13114 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 13115 false, BaseCtor, &ICI); 13116 13117 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 13118 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 13119 BaseCtor->getExplicitSpecifier(), /*isInline=*/true, 13120 /*isImplicitlyDeclared=*/true, 13121 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified, 13122 InheritedConstructor(Shadow, BaseCtor), 13123 BaseCtor->getTrailingRequiresClause()); 13124 if (Shadow->isInvalidDecl()) 13125 DerivedCtor->setInvalidDecl(); 13126 13127 // Build an unevaluated exception specification for this fake constructor. 13128 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 13129 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13130 EPI.ExceptionSpec.Type = EST_Unevaluated; 13131 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 13132 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 13133 FPT->getParamTypes(), EPI)); 13134 13135 // Build the parameter declarations. 13136 SmallVector<ParmVarDecl *, 16> ParamDecls; 13137 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 13138 TypeSourceInfo *TInfo = 13139 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 13140 ParmVarDecl *PD = ParmVarDecl::Create( 13141 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 13142 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 13143 PD->setScopeInfo(0, I); 13144 PD->setImplicit(); 13145 // Ensure attributes are propagated onto parameters (this matters for 13146 // format, pass_object_size, ...). 13147 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 13148 ParamDecls.push_back(PD); 13149 ProtoLoc.setParam(I, PD); 13150 } 13151 13152 // Set up the new constructor. 13153 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 13154 DerivedCtor->setAccess(BaseCtor->getAccess()); 13155 DerivedCtor->setParams(ParamDecls); 13156 Derived->addDecl(DerivedCtor); 13157 13158 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 13159 SetDeclDeleted(DerivedCtor, UsingLoc); 13160 13161 return DerivedCtor; 13162 } 13163 13164 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 13165 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 13166 Ctor->getInheritedConstructor().getShadowDecl()); 13167 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 13168 /*Diagnose*/true); 13169 } 13170 13171 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 13172 CXXConstructorDecl *Constructor) { 13173 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13174 assert(Constructor->getInheritedConstructor() && 13175 !Constructor->doesThisDeclarationHaveABody() && 13176 !Constructor->isDeleted()); 13177 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13178 return; 13179 13180 // Initializations are performed "as if by a defaulted default constructor", 13181 // so enter the appropriate scope. 13182 SynthesizedFunctionScope Scope(*this, Constructor); 13183 13184 // The exception specification is needed because we are defining the 13185 // function. 13186 ResolveExceptionSpec(CurrentLocation, 13187 Constructor->getType()->castAs<FunctionProtoType>()); 13188 MarkVTableUsed(CurrentLocation, ClassDecl); 13189 13190 // Add a context note for diagnostics produced after this point. 13191 Scope.addContextNote(CurrentLocation); 13192 13193 ConstructorUsingShadowDecl *Shadow = 13194 Constructor->getInheritedConstructor().getShadowDecl(); 13195 CXXConstructorDecl *InheritedCtor = 13196 Constructor->getInheritedConstructor().getConstructor(); 13197 13198 // [class.inhctor.init]p1: 13199 // initialization proceeds as if a defaulted default constructor is used to 13200 // initialize the D object and each base class subobject from which the 13201 // constructor was inherited 13202 13203 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 13204 CXXRecordDecl *RD = Shadow->getParent(); 13205 SourceLocation InitLoc = Shadow->getLocation(); 13206 13207 // Build explicit initializers for all base classes from which the 13208 // constructor was inherited. 13209 SmallVector<CXXCtorInitializer*, 8> Inits; 13210 for (bool VBase : {false, true}) { 13211 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 13212 if (B.isVirtual() != VBase) 13213 continue; 13214 13215 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 13216 if (!BaseRD) 13217 continue; 13218 13219 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 13220 if (!BaseCtor.first) 13221 continue; 13222 13223 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 13224 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 13225 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 13226 13227 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 13228 Inits.push_back(new (Context) CXXCtorInitializer( 13229 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 13230 SourceLocation())); 13231 } 13232 } 13233 13234 // We now proceed as if for a defaulted default constructor, with the relevant 13235 // initializers replaced. 13236 13237 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 13238 Constructor->setInvalidDecl(); 13239 return; 13240 } 13241 13242 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 13243 Constructor->markUsed(Context); 13244 13245 if (ASTMutationListener *L = getASTMutationListener()) { 13246 L->CompletedImplicitDefinition(Constructor); 13247 } 13248 13249 DiagnoseUninitializedFields(*this, Constructor); 13250 } 13251 13252 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 13253 // C++ [class.dtor]p2: 13254 // If a class has no user-declared destructor, a destructor is 13255 // declared implicitly. An implicitly-declared destructor is an 13256 // inline public member of its class. 13257 assert(ClassDecl->needsImplicitDestructor()); 13258 13259 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 13260 if (DSM.isAlreadyBeingDeclared()) 13261 return nullptr; 13262 13263 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13264 CXXDestructor, 13265 false); 13266 13267 // Create the actual destructor declaration. 13268 CanQualType ClassType 13269 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13270 SourceLocation ClassLoc = ClassDecl->getLocation(); 13271 DeclarationName Name 13272 = Context.DeclarationNames.getCXXDestructorName(ClassType); 13273 DeclarationNameInfo NameInfo(Name, ClassLoc); 13274 CXXDestructorDecl *Destructor = 13275 CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 13276 QualType(), nullptr, /*isInline=*/true, 13277 /*isImplicitlyDeclared=*/true, 13278 Constexpr ? ConstexprSpecKind::Constexpr 13279 : ConstexprSpecKind::Unspecified); 13280 Destructor->setAccess(AS_public); 13281 Destructor->setDefaulted(); 13282 13283 if (getLangOpts().CUDA) { 13284 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 13285 Destructor, 13286 /* ConstRHS */ false, 13287 /* Diagnose */ false); 13288 } 13289 13290 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 13291 13292 // We don't need to use SpecialMemberIsTrivial here; triviality for 13293 // destructors is easy to compute. 13294 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 13295 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 13296 ClassDecl->hasTrivialDestructorForCall()); 13297 13298 // Note that we have declared this destructor. 13299 ++getASTContext().NumImplicitDestructorsDeclared; 13300 13301 Scope *S = getScopeForContext(ClassDecl); 13302 CheckImplicitSpecialMemberDeclaration(S, Destructor); 13303 13304 // We can't check whether an implicit destructor is deleted before we complete 13305 // the definition of the class, because its validity depends on the alignment 13306 // of the class. We'll check this from ActOnFields once the class is complete. 13307 if (ClassDecl->isCompleteDefinition() && 13308 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 13309 SetDeclDeleted(Destructor, ClassLoc); 13310 13311 // Introduce this destructor into its scope. 13312 if (S) 13313 PushOnScopeChains(Destructor, S, false); 13314 ClassDecl->addDecl(Destructor); 13315 13316 return Destructor; 13317 } 13318 13319 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 13320 CXXDestructorDecl *Destructor) { 13321 assert((Destructor->isDefaulted() && 13322 !Destructor->doesThisDeclarationHaveABody() && 13323 !Destructor->isDeleted()) && 13324 "DefineImplicitDestructor - call it for implicit default dtor"); 13325 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 13326 return; 13327 13328 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13329 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 13330 13331 SynthesizedFunctionScope Scope(*this, Destructor); 13332 13333 // The exception specification is needed because we are defining the 13334 // function. 13335 ResolveExceptionSpec(CurrentLocation, 13336 Destructor->getType()->castAs<FunctionProtoType>()); 13337 MarkVTableUsed(CurrentLocation, ClassDecl); 13338 13339 // Add a context note for diagnostics produced after this point. 13340 Scope.addContextNote(CurrentLocation); 13341 13342 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13343 Destructor->getParent()); 13344 13345 if (CheckDestructor(Destructor)) { 13346 Destructor->setInvalidDecl(); 13347 return; 13348 } 13349 13350 SourceLocation Loc = Destructor->getEndLoc().isValid() 13351 ? Destructor->getEndLoc() 13352 : Destructor->getLocation(); 13353 Destructor->setBody(new (Context) CompoundStmt(Loc)); 13354 Destructor->markUsed(Context); 13355 13356 if (ASTMutationListener *L = getASTMutationListener()) { 13357 L->CompletedImplicitDefinition(Destructor); 13358 } 13359 } 13360 13361 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 13362 CXXDestructorDecl *Destructor) { 13363 if (Destructor->isInvalidDecl()) 13364 return; 13365 13366 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13367 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() && 13368 "implicit complete dtors unneeded outside MS ABI"); 13369 assert(ClassDecl->getNumVBases() > 0 && 13370 "complete dtor only exists for classes with vbases"); 13371 13372 SynthesizedFunctionScope Scope(*this, Destructor); 13373 13374 // Add a context note for diagnostics produced after this point. 13375 Scope.addContextNote(CurrentLocation); 13376 13377 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl); 13378 } 13379 13380 /// Perform any semantic analysis which needs to be delayed until all 13381 /// pending class member declarations have been parsed. 13382 void Sema::ActOnFinishCXXMemberDecls() { 13383 // If the context is an invalid C++ class, just suppress these checks. 13384 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 13385 if (Record->isInvalidDecl()) { 13386 DelayedOverridingExceptionSpecChecks.clear(); 13387 DelayedEquivalentExceptionSpecChecks.clear(); 13388 return; 13389 } 13390 checkForMultipleExportedDefaultConstructors(*this, Record); 13391 } 13392 } 13393 13394 void Sema::ActOnFinishCXXNonNestedClass() { 13395 referenceDLLExportedClassMethods(); 13396 13397 if (!DelayedDllExportMemberFunctions.empty()) { 13398 SmallVector<CXXMethodDecl*, 4> WorkList; 13399 std::swap(DelayedDllExportMemberFunctions, WorkList); 13400 for (CXXMethodDecl *M : WorkList) { 13401 DefineDefaultedFunction(*this, M, M->getLocation()); 13402 13403 // Pass the method to the consumer to get emitted. This is not necessary 13404 // for explicit instantiation definitions, as they will get emitted 13405 // anyway. 13406 if (M->getParent()->getTemplateSpecializationKind() != 13407 TSK_ExplicitInstantiationDefinition) 13408 ActOnFinishInlineFunctionDef(M); 13409 } 13410 } 13411 } 13412 13413 void Sema::referenceDLLExportedClassMethods() { 13414 if (!DelayedDllExportClasses.empty()) { 13415 // Calling ReferenceDllExportedMembers might cause the current function to 13416 // be called again, so use a local copy of DelayedDllExportClasses. 13417 SmallVector<CXXRecordDecl *, 4> WorkList; 13418 std::swap(DelayedDllExportClasses, WorkList); 13419 for (CXXRecordDecl *Class : WorkList) 13420 ReferenceDllExportedMembers(*this, Class); 13421 } 13422 } 13423 13424 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 13425 assert(getLangOpts().CPlusPlus11 && 13426 "adjusting dtor exception specs was introduced in c++11"); 13427 13428 if (Destructor->isDependentContext()) 13429 return; 13430 13431 // C++11 [class.dtor]p3: 13432 // A declaration of a destructor that does not have an exception- 13433 // specification is implicitly considered to have the same exception- 13434 // specification as an implicit declaration. 13435 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); 13436 if (DtorType->hasExceptionSpec()) 13437 return; 13438 13439 // Replace the destructor's type, building off the existing one. Fortunately, 13440 // the only thing of interest in the destructor type is its extended info. 13441 // The return and arguments are fixed. 13442 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 13443 EPI.ExceptionSpec.Type = EST_Unevaluated; 13444 EPI.ExceptionSpec.SourceDecl = Destructor; 13445 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 13446 13447 // FIXME: If the destructor has a body that could throw, and the newly created 13448 // spec doesn't allow exceptions, we should emit a warning, because this 13449 // change in behavior can break conforming C++03 programs at runtime. 13450 // However, we don't have a body or an exception specification yet, so it 13451 // needs to be done somewhere else. 13452 } 13453 13454 namespace { 13455 /// An abstract base class for all helper classes used in building the 13456 // copy/move operators. These classes serve as factory functions and help us 13457 // avoid using the same Expr* in the AST twice. 13458 class ExprBuilder { 13459 ExprBuilder(const ExprBuilder&) = delete; 13460 ExprBuilder &operator=(const ExprBuilder&) = delete; 13461 13462 protected: 13463 static Expr *assertNotNull(Expr *E) { 13464 assert(E && "Expression construction must not fail."); 13465 return E; 13466 } 13467 13468 public: 13469 ExprBuilder() {} 13470 virtual ~ExprBuilder() {} 13471 13472 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 13473 }; 13474 13475 class RefBuilder: public ExprBuilder { 13476 VarDecl *Var; 13477 QualType VarType; 13478 13479 public: 13480 Expr *build(Sema &S, SourceLocation Loc) const override { 13481 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 13482 } 13483 13484 RefBuilder(VarDecl *Var, QualType VarType) 13485 : Var(Var), VarType(VarType) {} 13486 }; 13487 13488 class ThisBuilder: public ExprBuilder { 13489 public: 13490 Expr *build(Sema &S, SourceLocation Loc) const override { 13491 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 13492 } 13493 }; 13494 13495 class CastBuilder: public ExprBuilder { 13496 const ExprBuilder &Builder; 13497 QualType Type; 13498 ExprValueKind Kind; 13499 const CXXCastPath &Path; 13500 13501 public: 13502 Expr *build(Sema &S, SourceLocation Loc) const override { 13503 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 13504 CK_UncheckedDerivedToBase, Kind, 13505 &Path).get()); 13506 } 13507 13508 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 13509 const CXXCastPath &Path) 13510 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 13511 }; 13512 13513 class DerefBuilder: public ExprBuilder { 13514 const ExprBuilder &Builder; 13515 13516 public: 13517 Expr *build(Sema &S, SourceLocation Loc) const override { 13518 return assertNotNull( 13519 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 13520 } 13521 13522 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13523 }; 13524 13525 class MemberBuilder: public ExprBuilder { 13526 const ExprBuilder &Builder; 13527 QualType Type; 13528 CXXScopeSpec SS; 13529 bool IsArrow; 13530 LookupResult &MemberLookup; 13531 13532 public: 13533 Expr *build(Sema &S, SourceLocation Loc) const override { 13534 return assertNotNull(S.BuildMemberReferenceExpr( 13535 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 13536 nullptr, MemberLookup, nullptr, nullptr).get()); 13537 } 13538 13539 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 13540 LookupResult &MemberLookup) 13541 : Builder(Builder), Type(Type), IsArrow(IsArrow), 13542 MemberLookup(MemberLookup) {} 13543 }; 13544 13545 class MoveCastBuilder: public ExprBuilder { 13546 const ExprBuilder &Builder; 13547 13548 public: 13549 Expr *build(Sema &S, SourceLocation Loc) const override { 13550 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 13551 } 13552 13553 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13554 }; 13555 13556 class LvalueConvBuilder: public ExprBuilder { 13557 const ExprBuilder &Builder; 13558 13559 public: 13560 Expr *build(Sema &S, SourceLocation Loc) const override { 13561 return assertNotNull( 13562 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 13563 } 13564 13565 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13566 }; 13567 13568 class SubscriptBuilder: public ExprBuilder { 13569 const ExprBuilder &Base; 13570 const ExprBuilder &Index; 13571 13572 public: 13573 Expr *build(Sema &S, SourceLocation Loc) const override { 13574 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 13575 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 13576 } 13577 13578 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 13579 : Base(Base), Index(Index) {} 13580 }; 13581 13582 } // end anonymous namespace 13583 13584 /// When generating a defaulted copy or move assignment operator, if a field 13585 /// should be copied with __builtin_memcpy rather than via explicit assignments, 13586 /// do so. This optimization only applies for arrays of scalars, and for arrays 13587 /// of class type where the selected copy/move-assignment operator is trivial. 13588 static StmtResult 13589 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 13590 const ExprBuilder &ToB, const ExprBuilder &FromB) { 13591 // Compute the size of the memory buffer to be copied. 13592 QualType SizeType = S.Context.getSizeType(); 13593 llvm::APInt Size(S.Context.getTypeSize(SizeType), 13594 S.Context.getTypeSizeInChars(T).getQuantity()); 13595 13596 // Take the address of the field references for "from" and "to". We 13597 // directly construct UnaryOperators here because semantic analysis 13598 // does not permit us to take the address of an xvalue. 13599 Expr *From = FromB.build(S, Loc); 13600 From = UnaryOperator::Create( 13601 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()), 13602 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13603 Expr *To = ToB.build(S, Loc); 13604 To = UnaryOperator::Create( 13605 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()), 13606 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13607 13608 const Type *E = T->getBaseElementTypeUnsafe(); 13609 bool NeedsCollectableMemCpy = 13610 E->isRecordType() && 13611 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 13612 13613 // Create a reference to the __builtin_objc_memmove_collectable function 13614 StringRef MemCpyName = NeedsCollectableMemCpy ? 13615 "__builtin_objc_memmove_collectable" : 13616 "__builtin_memcpy"; 13617 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 13618 Sema::LookupOrdinaryName); 13619 S.LookupName(R, S.TUScope, true); 13620 13621 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 13622 if (!MemCpy) 13623 // Something went horribly wrong earlier, and we will have complained 13624 // about it. 13625 return StmtError(); 13626 13627 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 13628 VK_RValue, Loc, nullptr); 13629 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 13630 13631 Expr *CallArgs[] = { 13632 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 13633 }; 13634 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 13635 Loc, CallArgs, Loc); 13636 13637 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 13638 return Call.getAs<Stmt>(); 13639 } 13640 13641 /// Builds a statement that copies/moves the given entity from \p From to 13642 /// \c To. 13643 /// 13644 /// This routine is used to copy/move the members of a class with an 13645 /// implicitly-declared copy/move assignment operator. When the entities being 13646 /// copied are arrays, this routine builds for loops to copy them. 13647 /// 13648 /// \param S The Sema object used for type-checking. 13649 /// 13650 /// \param Loc The location where the implicit copy/move is being generated. 13651 /// 13652 /// \param T The type of the expressions being copied/moved. Both expressions 13653 /// must have this type. 13654 /// 13655 /// \param To The expression we are copying/moving to. 13656 /// 13657 /// \param From The expression we are copying/moving from. 13658 /// 13659 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 13660 /// Otherwise, it's a non-static member subobject. 13661 /// 13662 /// \param Copying Whether we're copying or moving. 13663 /// 13664 /// \param Depth Internal parameter recording the depth of the recursion. 13665 /// 13666 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 13667 /// if a memcpy should be used instead. 13668 static StmtResult 13669 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 13670 const ExprBuilder &To, const ExprBuilder &From, 13671 bool CopyingBaseSubobject, bool Copying, 13672 unsigned Depth = 0) { 13673 // C++11 [class.copy]p28: 13674 // Each subobject is assigned in the manner appropriate to its type: 13675 // 13676 // - if the subobject is of class type, as if by a call to operator= with 13677 // the subobject as the object expression and the corresponding 13678 // subobject of x as a single function argument (as if by explicit 13679 // qualification; that is, ignoring any possible virtual overriding 13680 // functions in more derived classes); 13681 // 13682 // C++03 [class.copy]p13: 13683 // - if the subobject is of class type, the copy assignment operator for 13684 // the class is used (as if by explicit qualification; that is, 13685 // ignoring any possible virtual overriding functions in more derived 13686 // classes); 13687 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 13688 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 13689 13690 // Look for operator=. 13691 DeclarationName Name 13692 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13693 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 13694 S.LookupQualifiedName(OpLookup, ClassDecl, false); 13695 13696 // Prior to C++11, filter out any result that isn't a copy/move-assignment 13697 // operator. 13698 if (!S.getLangOpts().CPlusPlus11) { 13699 LookupResult::Filter F = OpLookup.makeFilter(); 13700 while (F.hasNext()) { 13701 NamedDecl *D = F.next(); 13702 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 13703 if (Method->isCopyAssignmentOperator() || 13704 (!Copying && Method->isMoveAssignmentOperator())) 13705 continue; 13706 13707 F.erase(); 13708 } 13709 F.done(); 13710 } 13711 13712 // Suppress the protected check (C++ [class.protected]) for each of the 13713 // assignment operators we found. This strange dance is required when 13714 // we're assigning via a base classes's copy-assignment operator. To 13715 // ensure that we're getting the right base class subobject (without 13716 // ambiguities), we need to cast "this" to that subobject type; to 13717 // ensure that we don't go through the virtual call mechanism, we need 13718 // to qualify the operator= name with the base class (see below). However, 13719 // this means that if the base class has a protected copy assignment 13720 // operator, the protected member access check will fail. So, we 13721 // rewrite "protected" access to "public" access in this case, since we 13722 // know by construction that we're calling from a derived class. 13723 if (CopyingBaseSubobject) { 13724 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 13725 L != LEnd; ++L) { 13726 if (L.getAccess() == AS_protected) 13727 L.setAccess(AS_public); 13728 } 13729 } 13730 13731 // Create the nested-name-specifier that will be used to qualify the 13732 // reference to operator=; this is required to suppress the virtual 13733 // call mechanism. 13734 CXXScopeSpec SS; 13735 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 13736 SS.MakeTrivial(S.Context, 13737 NestedNameSpecifier::Create(S.Context, nullptr, false, 13738 CanonicalT), 13739 Loc); 13740 13741 // Create the reference to operator=. 13742 ExprResult OpEqualRef 13743 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 13744 SS, /*TemplateKWLoc=*/SourceLocation(), 13745 /*FirstQualifierInScope=*/nullptr, 13746 OpLookup, 13747 /*TemplateArgs=*/nullptr, /*S*/nullptr, 13748 /*SuppressQualifierCheck=*/true); 13749 if (OpEqualRef.isInvalid()) 13750 return StmtError(); 13751 13752 // Build the call to the assignment operator. 13753 13754 Expr *FromInst = From.build(S, Loc); 13755 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 13756 OpEqualRef.getAs<Expr>(), 13757 Loc, FromInst, Loc); 13758 if (Call.isInvalid()) 13759 return StmtError(); 13760 13761 // If we built a call to a trivial 'operator=' while copying an array, 13762 // bail out. We'll replace the whole shebang with a memcpy. 13763 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 13764 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 13765 return StmtResult((Stmt*)nullptr); 13766 13767 // Convert to an expression-statement, and clean up any produced 13768 // temporaries. 13769 return S.ActOnExprStmt(Call); 13770 } 13771 13772 // - if the subobject is of scalar type, the built-in assignment 13773 // operator is used. 13774 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 13775 if (!ArrayTy) { 13776 ExprResult Assignment = S.CreateBuiltinBinOp( 13777 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 13778 if (Assignment.isInvalid()) 13779 return StmtError(); 13780 return S.ActOnExprStmt(Assignment); 13781 } 13782 13783 // - if the subobject is an array, each element is assigned, in the 13784 // manner appropriate to the element type; 13785 13786 // Construct a loop over the array bounds, e.g., 13787 // 13788 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 13789 // 13790 // that will copy each of the array elements. 13791 QualType SizeType = S.Context.getSizeType(); 13792 13793 // Create the iteration variable. 13794 IdentifierInfo *IterationVarName = nullptr; 13795 { 13796 SmallString<8> Str; 13797 llvm::raw_svector_ostream OS(Str); 13798 OS << "__i" << Depth; 13799 IterationVarName = &S.Context.Idents.get(OS.str()); 13800 } 13801 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 13802 IterationVarName, SizeType, 13803 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 13804 SC_None); 13805 13806 // Initialize the iteration variable to zero. 13807 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 13808 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 13809 13810 // Creates a reference to the iteration variable. 13811 RefBuilder IterationVarRef(IterationVar, SizeType); 13812 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 13813 13814 // Create the DeclStmt that holds the iteration variable. 13815 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 13816 13817 // Subscript the "from" and "to" expressions with the iteration variable. 13818 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 13819 MoveCastBuilder FromIndexMove(FromIndexCopy); 13820 const ExprBuilder *FromIndex; 13821 if (Copying) 13822 FromIndex = &FromIndexCopy; 13823 else 13824 FromIndex = &FromIndexMove; 13825 13826 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 13827 13828 // Build the copy/move for an individual element of the array. 13829 StmtResult Copy = 13830 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 13831 ToIndex, *FromIndex, CopyingBaseSubobject, 13832 Copying, Depth + 1); 13833 // Bail out if copying fails or if we determined that we should use memcpy. 13834 if (Copy.isInvalid() || !Copy.get()) 13835 return Copy; 13836 13837 // Create the comparison against the array bound. 13838 llvm::APInt Upper 13839 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 13840 Expr *Comparison = BinaryOperator::Create( 13841 S.Context, IterationVarRefRVal.build(S, Loc), 13842 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE, 13843 S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides()); 13844 13845 // Create the pre-increment of the iteration variable. We can determine 13846 // whether the increment will overflow based on the value of the array 13847 // bound. 13848 Expr *Increment = UnaryOperator::Create( 13849 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue, 13850 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides()); 13851 13852 // Construct the loop that copies all elements of this array. 13853 return S.ActOnForStmt( 13854 Loc, Loc, InitStmt, 13855 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 13856 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 13857 } 13858 13859 static StmtResult 13860 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 13861 const ExprBuilder &To, const ExprBuilder &From, 13862 bool CopyingBaseSubobject, bool Copying) { 13863 // Maybe we should use a memcpy? 13864 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 13865 T.isTriviallyCopyableType(S.Context)) 13866 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13867 13868 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 13869 CopyingBaseSubobject, 13870 Copying, 0)); 13871 13872 // If we ended up picking a trivial assignment operator for an array of a 13873 // non-trivially-copyable class type, just emit a memcpy. 13874 if (!Result.isInvalid() && !Result.get()) 13875 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13876 13877 return Result; 13878 } 13879 13880 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 13881 // Note: The following rules are largely analoguous to the copy 13882 // constructor rules. Note that virtual bases are not taken into account 13883 // for determining the argument type of the operator. Note also that 13884 // operators taking an object instead of a reference are allowed. 13885 assert(ClassDecl->needsImplicitCopyAssignment()); 13886 13887 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 13888 if (DSM.isAlreadyBeingDeclared()) 13889 return nullptr; 13890 13891 QualType ArgType = Context.getTypeDeclType(ClassDecl); 13892 LangAS AS = getDefaultCXXMethodAddrSpace(); 13893 if (AS != LangAS::Default) 13894 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 13895 QualType RetType = Context.getLValueReferenceType(ArgType); 13896 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 13897 if (Const) 13898 ArgType = ArgType.withConst(); 13899 13900 ArgType = Context.getLValueReferenceType(ArgType); 13901 13902 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13903 CXXCopyAssignment, 13904 Const); 13905 13906 // An implicitly-declared copy assignment operator is an inline public 13907 // member of its class. 13908 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13909 SourceLocation ClassLoc = ClassDecl->getLocation(); 13910 DeclarationNameInfo NameInfo(Name, ClassLoc); 13911 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 13912 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 13913 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 13914 /*isInline=*/true, 13915 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 13916 SourceLocation()); 13917 CopyAssignment->setAccess(AS_public); 13918 CopyAssignment->setDefaulted(); 13919 CopyAssignment->setImplicit(); 13920 13921 if (getLangOpts().CUDA) { 13922 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 13923 CopyAssignment, 13924 /* ConstRHS */ Const, 13925 /* Diagnose */ false); 13926 } 13927 13928 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 13929 13930 // Add the parameter to the operator. 13931 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 13932 ClassLoc, ClassLoc, 13933 /*Id=*/nullptr, ArgType, 13934 /*TInfo=*/nullptr, SC_None, 13935 nullptr); 13936 CopyAssignment->setParams(FromParam); 13937 13938 CopyAssignment->setTrivial( 13939 ClassDecl->needsOverloadResolutionForCopyAssignment() 13940 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 13941 : ClassDecl->hasTrivialCopyAssignment()); 13942 13943 // Note that we have added this copy-assignment operator. 13944 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 13945 13946 Scope *S = getScopeForContext(ClassDecl); 13947 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 13948 13949 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) { 13950 ClassDecl->setImplicitCopyAssignmentIsDeleted(); 13951 SetDeclDeleted(CopyAssignment, ClassLoc); 13952 } 13953 13954 if (S) 13955 PushOnScopeChains(CopyAssignment, S, false); 13956 ClassDecl->addDecl(CopyAssignment); 13957 13958 return CopyAssignment; 13959 } 13960 13961 /// Diagnose an implicit copy operation for a class which is odr-used, but 13962 /// which is deprecated because the class has a user-declared copy constructor, 13963 /// copy assignment operator, or destructor. 13964 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 13965 assert(CopyOp->isImplicit()); 13966 13967 CXXRecordDecl *RD = CopyOp->getParent(); 13968 CXXMethodDecl *UserDeclaredOperation = nullptr; 13969 13970 // In Microsoft mode, assignment operations don't affect constructors and 13971 // vice versa. 13972 if (RD->hasUserDeclaredDestructor()) { 13973 UserDeclaredOperation = RD->getDestructor(); 13974 } else if (!isa<CXXConstructorDecl>(CopyOp) && 13975 RD->hasUserDeclaredCopyConstructor() && 13976 !S.getLangOpts().MSVCCompat) { 13977 // Find any user-declared copy constructor. 13978 for (auto *I : RD->ctors()) { 13979 if (I->isCopyConstructor()) { 13980 UserDeclaredOperation = I; 13981 break; 13982 } 13983 } 13984 assert(UserDeclaredOperation); 13985 } else if (isa<CXXConstructorDecl>(CopyOp) && 13986 RD->hasUserDeclaredCopyAssignment() && 13987 !S.getLangOpts().MSVCCompat) { 13988 // Find any user-declared move assignment operator. 13989 for (auto *I : RD->methods()) { 13990 if (I->isCopyAssignmentOperator()) { 13991 UserDeclaredOperation = I; 13992 break; 13993 } 13994 } 13995 assert(UserDeclaredOperation); 13996 } 13997 13998 if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) { 13999 S.Diag(UserDeclaredOperation->getLocation(), 14000 isa<CXXDestructorDecl>(UserDeclaredOperation) 14001 ? diag::warn_deprecated_copy_dtor_operation 14002 : diag::warn_deprecated_copy_operation) 14003 << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp); 14004 } 14005 } 14006 14007 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 14008 CXXMethodDecl *CopyAssignOperator) { 14009 assert((CopyAssignOperator->isDefaulted() && 14010 CopyAssignOperator->isOverloadedOperator() && 14011 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 14012 !CopyAssignOperator->doesThisDeclarationHaveABody() && 14013 !CopyAssignOperator->isDeleted()) && 14014 "DefineImplicitCopyAssignment called for wrong function"); 14015 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 14016 return; 14017 14018 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 14019 if (ClassDecl->isInvalidDecl()) { 14020 CopyAssignOperator->setInvalidDecl(); 14021 return; 14022 } 14023 14024 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 14025 14026 // The exception specification is needed because we are defining the 14027 // function. 14028 ResolveExceptionSpec(CurrentLocation, 14029 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 14030 14031 // Add a context note for diagnostics produced after this point. 14032 Scope.addContextNote(CurrentLocation); 14033 14034 // C++11 [class.copy]p18: 14035 // The [definition of an implicitly declared copy assignment operator] is 14036 // deprecated if the class has a user-declared copy constructor or a 14037 // user-declared destructor. 14038 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 14039 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 14040 14041 // C++0x [class.copy]p30: 14042 // The implicitly-defined or explicitly-defaulted copy assignment operator 14043 // for a non-union class X performs memberwise copy assignment of its 14044 // subobjects. The direct base classes of X are assigned first, in the 14045 // order of their declaration in the base-specifier-list, and then the 14046 // immediate non-static data members of X are assigned, in the order in 14047 // which they were declared in the class definition. 14048 14049 // The statements that form the synthesized function body. 14050 SmallVector<Stmt*, 8> Statements; 14051 14052 // The parameter for the "other" object, which we are copying from. 14053 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 14054 Qualifiers OtherQuals = Other->getType().getQualifiers(); 14055 QualType OtherRefType = Other->getType(); 14056 if (const LValueReferenceType *OtherRef 14057 = OtherRefType->getAs<LValueReferenceType>()) { 14058 OtherRefType = OtherRef->getPointeeType(); 14059 OtherQuals = OtherRefType.getQualifiers(); 14060 } 14061 14062 // Our location for everything implicitly-generated. 14063 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 14064 ? CopyAssignOperator->getEndLoc() 14065 : CopyAssignOperator->getLocation(); 14066 14067 // Builds a DeclRefExpr for the "other" object. 14068 RefBuilder OtherRef(Other, OtherRefType); 14069 14070 // Builds the "this" pointer. 14071 ThisBuilder This; 14072 14073 // Assign base classes. 14074 bool Invalid = false; 14075 for (auto &Base : ClassDecl->bases()) { 14076 // Form the assignment: 14077 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 14078 QualType BaseType = Base.getType().getUnqualifiedType(); 14079 if (!BaseType->isRecordType()) { 14080 Invalid = true; 14081 continue; 14082 } 14083 14084 CXXCastPath BasePath; 14085 BasePath.push_back(&Base); 14086 14087 // Construct the "from" expression, which is an implicit cast to the 14088 // appropriately-qualified base type. 14089 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 14090 VK_LValue, BasePath); 14091 14092 // Dereference "this". 14093 DerefBuilder DerefThis(This); 14094 CastBuilder To(DerefThis, 14095 Context.getQualifiedType( 14096 BaseType, CopyAssignOperator->getMethodQualifiers()), 14097 VK_LValue, BasePath); 14098 14099 // Build the copy. 14100 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 14101 To, From, 14102 /*CopyingBaseSubobject=*/true, 14103 /*Copying=*/true); 14104 if (Copy.isInvalid()) { 14105 CopyAssignOperator->setInvalidDecl(); 14106 return; 14107 } 14108 14109 // Success! Record the copy. 14110 Statements.push_back(Copy.getAs<Expr>()); 14111 } 14112 14113 // Assign non-static members. 14114 for (auto *Field : ClassDecl->fields()) { 14115 // FIXME: We should form some kind of AST representation for the implied 14116 // memcpy in a union copy operation. 14117 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14118 continue; 14119 14120 if (Field->isInvalidDecl()) { 14121 Invalid = true; 14122 continue; 14123 } 14124 14125 // Check for members of reference type; we can't copy those. 14126 if (Field->getType()->isReferenceType()) { 14127 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14128 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14129 Diag(Field->getLocation(), diag::note_declared_at); 14130 Invalid = true; 14131 continue; 14132 } 14133 14134 // Check for members of const-qualified, non-class type. 14135 QualType BaseType = Context.getBaseElementType(Field->getType()); 14136 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14137 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14138 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14139 Diag(Field->getLocation(), diag::note_declared_at); 14140 Invalid = true; 14141 continue; 14142 } 14143 14144 // Suppress assigning zero-width bitfields. 14145 if (Field->isZeroLengthBitField(Context)) 14146 continue; 14147 14148 QualType FieldType = Field->getType().getNonReferenceType(); 14149 if (FieldType->isIncompleteArrayType()) { 14150 assert(ClassDecl->hasFlexibleArrayMember() && 14151 "Incomplete array type is not valid"); 14152 continue; 14153 } 14154 14155 // Build references to the field in the object we're copying from and to. 14156 CXXScopeSpec SS; // Intentionally empty 14157 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14158 LookupMemberName); 14159 MemberLookup.addDecl(Field); 14160 MemberLookup.resolveKind(); 14161 14162 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 14163 14164 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 14165 14166 // Build the copy of this field. 14167 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 14168 To, From, 14169 /*CopyingBaseSubobject=*/false, 14170 /*Copying=*/true); 14171 if (Copy.isInvalid()) { 14172 CopyAssignOperator->setInvalidDecl(); 14173 return; 14174 } 14175 14176 // Success! Record the copy. 14177 Statements.push_back(Copy.getAs<Stmt>()); 14178 } 14179 14180 if (!Invalid) { 14181 // Add a "return *this;" 14182 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14183 14184 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14185 if (Return.isInvalid()) 14186 Invalid = true; 14187 else 14188 Statements.push_back(Return.getAs<Stmt>()); 14189 } 14190 14191 if (Invalid) { 14192 CopyAssignOperator->setInvalidDecl(); 14193 return; 14194 } 14195 14196 StmtResult Body; 14197 { 14198 CompoundScopeRAII CompoundScope(*this); 14199 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14200 /*isStmtExpr=*/false); 14201 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14202 } 14203 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 14204 CopyAssignOperator->markUsed(Context); 14205 14206 if (ASTMutationListener *L = getASTMutationListener()) { 14207 L->CompletedImplicitDefinition(CopyAssignOperator); 14208 } 14209 } 14210 14211 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 14212 assert(ClassDecl->needsImplicitMoveAssignment()); 14213 14214 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 14215 if (DSM.isAlreadyBeingDeclared()) 14216 return nullptr; 14217 14218 // Note: The following rules are largely analoguous to the move 14219 // constructor rules. 14220 14221 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14222 LangAS AS = getDefaultCXXMethodAddrSpace(); 14223 if (AS != LangAS::Default) 14224 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14225 QualType RetType = Context.getLValueReferenceType(ArgType); 14226 ArgType = Context.getRValueReferenceType(ArgType); 14227 14228 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14229 CXXMoveAssignment, 14230 false); 14231 14232 // An implicitly-declared move assignment operator is an inline public 14233 // member of its class. 14234 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14235 SourceLocation ClassLoc = ClassDecl->getLocation(); 14236 DeclarationNameInfo NameInfo(Name, ClassLoc); 14237 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 14238 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14239 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14240 /*isInline=*/true, 14241 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14242 SourceLocation()); 14243 MoveAssignment->setAccess(AS_public); 14244 MoveAssignment->setDefaulted(); 14245 MoveAssignment->setImplicit(); 14246 14247 if (getLangOpts().CUDA) { 14248 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 14249 MoveAssignment, 14250 /* ConstRHS */ false, 14251 /* Diagnose */ false); 14252 } 14253 14254 // Build an exception specification pointing back at this member. 14255 FunctionProtoType::ExtProtoInfo EPI = 14256 getImplicitMethodEPI(*this, MoveAssignment); 14257 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 14258 14259 // Add the parameter to the operator. 14260 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 14261 ClassLoc, ClassLoc, 14262 /*Id=*/nullptr, ArgType, 14263 /*TInfo=*/nullptr, SC_None, 14264 nullptr); 14265 MoveAssignment->setParams(FromParam); 14266 14267 MoveAssignment->setTrivial( 14268 ClassDecl->needsOverloadResolutionForMoveAssignment() 14269 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 14270 : ClassDecl->hasTrivialMoveAssignment()); 14271 14272 // Note that we have added this copy-assignment operator. 14273 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 14274 14275 Scope *S = getScopeForContext(ClassDecl); 14276 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 14277 14278 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 14279 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 14280 SetDeclDeleted(MoveAssignment, ClassLoc); 14281 } 14282 14283 if (S) 14284 PushOnScopeChains(MoveAssignment, S, false); 14285 ClassDecl->addDecl(MoveAssignment); 14286 14287 return MoveAssignment; 14288 } 14289 14290 /// Check if we're implicitly defining a move assignment operator for a class 14291 /// with virtual bases. Such a move assignment might move-assign the virtual 14292 /// base multiple times. 14293 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 14294 SourceLocation CurrentLocation) { 14295 assert(!Class->isDependentContext() && "should not define dependent move"); 14296 14297 // Only a virtual base could get implicitly move-assigned multiple times. 14298 // Only a non-trivial move assignment can observe this. We only want to 14299 // diagnose if we implicitly define an assignment operator that assigns 14300 // two base classes, both of which move-assign the same virtual base. 14301 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 14302 Class->getNumBases() < 2) 14303 return; 14304 14305 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 14306 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 14307 VBaseMap VBases; 14308 14309 for (auto &BI : Class->bases()) { 14310 Worklist.push_back(&BI); 14311 while (!Worklist.empty()) { 14312 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 14313 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 14314 14315 // If the base has no non-trivial move assignment operators, 14316 // we don't care about moves from it. 14317 if (!Base->hasNonTrivialMoveAssignment()) 14318 continue; 14319 14320 // If there's nothing virtual here, skip it. 14321 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 14322 continue; 14323 14324 // If we're not actually going to call a move assignment for this base, 14325 // or the selected move assignment is trivial, skip it. 14326 Sema::SpecialMemberOverloadResult SMOR = 14327 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 14328 /*ConstArg*/false, /*VolatileArg*/false, 14329 /*RValueThis*/true, /*ConstThis*/false, 14330 /*VolatileThis*/false); 14331 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 14332 !SMOR.getMethod()->isMoveAssignmentOperator()) 14333 continue; 14334 14335 if (BaseSpec->isVirtual()) { 14336 // We're going to move-assign this virtual base, and its move 14337 // assignment operator is not trivial. If this can happen for 14338 // multiple distinct direct bases of Class, diagnose it. (If it 14339 // only happens in one base, we'll diagnose it when synthesizing 14340 // that base class's move assignment operator.) 14341 CXXBaseSpecifier *&Existing = 14342 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 14343 .first->second; 14344 if (Existing && Existing != &BI) { 14345 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 14346 << Class << Base; 14347 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 14348 << (Base->getCanonicalDecl() == 14349 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14350 << Base << Existing->getType() << Existing->getSourceRange(); 14351 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 14352 << (Base->getCanonicalDecl() == 14353 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14354 << Base << BI.getType() << BaseSpec->getSourceRange(); 14355 14356 // Only diagnose each vbase once. 14357 Existing = nullptr; 14358 } 14359 } else { 14360 // Only walk over bases that have defaulted move assignment operators. 14361 // We assume that any user-provided move assignment operator handles 14362 // the multiple-moves-of-vbase case itself somehow. 14363 if (!SMOR.getMethod()->isDefaulted()) 14364 continue; 14365 14366 // We're going to move the base classes of Base. Add them to the list. 14367 for (auto &BI : Base->bases()) 14368 Worklist.push_back(&BI); 14369 } 14370 } 14371 } 14372 } 14373 14374 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 14375 CXXMethodDecl *MoveAssignOperator) { 14376 assert((MoveAssignOperator->isDefaulted() && 14377 MoveAssignOperator->isOverloadedOperator() && 14378 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 14379 !MoveAssignOperator->doesThisDeclarationHaveABody() && 14380 !MoveAssignOperator->isDeleted()) && 14381 "DefineImplicitMoveAssignment called for wrong function"); 14382 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 14383 return; 14384 14385 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 14386 if (ClassDecl->isInvalidDecl()) { 14387 MoveAssignOperator->setInvalidDecl(); 14388 return; 14389 } 14390 14391 // C++0x [class.copy]p28: 14392 // The implicitly-defined or move assignment operator for a non-union class 14393 // X performs memberwise move assignment of its subobjects. The direct base 14394 // classes of X are assigned first, in the order of their declaration in the 14395 // base-specifier-list, and then the immediate non-static data members of X 14396 // are assigned, in the order in which they were declared in the class 14397 // definition. 14398 14399 // Issue a warning if our implicit move assignment operator will move 14400 // from a virtual base more than once. 14401 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 14402 14403 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 14404 14405 // The exception specification is needed because we are defining the 14406 // function. 14407 ResolveExceptionSpec(CurrentLocation, 14408 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 14409 14410 // Add a context note for diagnostics produced after this point. 14411 Scope.addContextNote(CurrentLocation); 14412 14413 // The statements that form the synthesized function body. 14414 SmallVector<Stmt*, 8> Statements; 14415 14416 // The parameter for the "other" object, which we are move from. 14417 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 14418 QualType OtherRefType = 14419 Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); 14420 14421 // Our location for everything implicitly-generated. 14422 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 14423 ? MoveAssignOperator->getEndLoc() 14424 : MoveAssignOperator->getLocation(); 14425 14426 // Builds a reference to the "other" object. 14427 RefBuilder OtherRef(Other, OtherRefType); 14428 // Cast to rvalue. 14429 MoveCastBuilder MoveOther(OtherRef); 14430 14431 // Builds the "this" pointer. 14432 ThisBuilder This; 14433 14434 // Assign base classes. 14435 bool Invalid = false; 14436 for (auto &Base : ClassDecl->bases()) { 14437 // C++11 [class.copy]p28: 14438 // It is unspecified whether subobjects representing virtual base classes 14439 // are assigned more than once by the implicitly-defined copy assignment 14440 // operator. 14441 // FIXME: Do not assign to a vbase that will be assigned by some other base 14442 // class. For a move-assignment, this can result in the vbase being moved 14443 // multiple times. 14444 14445 // Form the assignment: 14446 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 14447 QualType BaseType = Base.getType().getUnqualifiedType(); 14448 if (!BaseType->isRecordType()) { 14449 Invalid = true; 14450 continue; 14451 } 14452 14453 CXXCastPath BasePath; 14454 BasePath.push_back(&Base); 14455 14456 // Construct the "from" expression, which is an implicit cast to the 14457 // appropriately-qualified base type. 14458 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 14459 14460 // Dereference "this". 14461 DerefBuilder DerefThis(This); 14462 14463 // Implicitly cast "this" to the appropriately-qualified base type. 14464 CastBuilder To(DerefThis, 14465 Context.getQualifiedType( 14466 BaseType, MoveAssignOperator->getMethodQualifiers()), 14467 VK_LValue, BasePath); 14468 14469 // Build the move. 14470 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 14471 To, From, 14472 /*CopyingBaseSubobject=*/true, 14473 /*Copying=*/false); 14474 if (Move.isInvalid()) { 14475 MoveAssignOperator->setInvalidDecl(); 14476 return; 14477 } 14478 14479 // Success! Record the move. 14480 Statements.push_back(Move.getAs<Expr>()); 14481 } 14482 14483 // Assign non-static members. 14484 for (auto *Field : ClassDecl->fields()) { 14485 // FIXME: We should form some kind of AST representation for the implied 14486 // memcpy in a union copy operation. 14487 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14488 continue; 14489 14490 if (Field->isInvalidDecl()) { 14491 Invalid = true; 14492 continue; 14493 } 14494 14495 // Check for members of reference type; we can't move those. 14496 if (Field->getType()->isReferenceType()) { 14497 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14498 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14499 Diag(Field->getLocation(), diag::note_declared_at); 14500 Invalid = true; 14501 continue; 14502 } 14503 14504 // Check for members of const-qualified, non-class type. 14505 QualType BaseType = Context.getBaseElementType(Field->getType()); 14506 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14507 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14508 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14509 Diag(Field->getLocation(), diag::note_declared_at); 14510 Invalid = true; 14511 continue; 14512 } 14513 14514 // Suppress assigning zero-width bitfields. 14515 if (Field->isZeroLengthBitField(Context)) 14516 continue; 14517 14518 QualType FieldType = Field->getType().getNonReferenceType(); 14519 if (FieldType->isIncompleteArrayType()) { 14520 assert(ClassDecl->hasFlexibleArrayMember() && 14521 "Incomplete array type is not valid"); 14522 continue; 14523 } 14524 14525 // Build references to the field in the object we're copying from and to. 14526 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14527 LookupMemberName); 14528 MemberLookup.addDecl(Field); 14529 MemberLookup.resolveKind(); 14530 MemberBuilder From(MoveOther, OtherRefType, 14531 /*IsArrow=*/false, MemberLookup); 14532 MemberBuilder To(This, getCurrentThisType(), 14533 /*IsArrow=*/true, MemberLookup); 14534 14535 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 14536 "Member reference with rvalue base must be rvalue except for reference " 14537 "members, which aren't allowed for move assignment."); 14538 14539 // Build the move of this field. 14540 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 14541 To, From, 14542 /*CopyingBaseSubobject=*/false, 14543 /*Copying=*/false); 14544 if (Move.isInvalid()) { 14545 MoveAssignOperator->setInvalidDecl(); 14546 return; 14547 } 14548 14549 // Success! Record the copy. 14550 Statements.push_back(Move.getAs<Stmt>()); 14551 } 14552 14553 if (!Invalid) { 14554 // Add a "return *this;" 14555 ExprResult ThisObj = 14556 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14557 14558 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14559 if (Return.isInvalid()) 14560 Invalid = true; 14561 else 14562 Statements.push_back(Return.getAs<Stmt>()); 14563 } 14564 14565 if (Invalid) { 14566 MoveAssignOperator->setInvalidDecl(); 14567 return; 14568 } 14569 14570 StmtResult Body; 14571 { 14572 CompoundScopeRAII CompoundScope(*this); 14573 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14574 /*isStmtExpr=*/false); 14575 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14576 } 14577 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 14578 MoveAssignOperator->markUsed(Context); 14579 14580 if (ASTMutationListener *L = getASTMutationListener()) { 14581 L->CompletedImplicitDefinition(MoveAssignOperator); 14582 } 14583 } 14584 14585 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 14586 CXXRecordDecl *ClassDecl) { 14587 // C++ [class.copy]p4: 14588 // If the class definition does not explicitly declare a copy 14589 // constructor, one is declared implicitly. 14590 assert(ClassDecl->needsImplicitCopyConstructor()); 14591 14592 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 14593 if (DSM.isAlreadyBeingDeclared()) 14594 return nullptr; 14595 14596 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14597 QualType ArgType = ClassType; 14598 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 14599 if (Const) 14600 ArgType = ArgType.withConst(); 14601 14602 LangAS AS = getDefaultCXXMethodAddrSpace(); 14603 if (AS != LangAS::Default) 14604 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14605 14606 ArgType = Context.getLValueReferenceType(ArgType); 14607 14608 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14609 CXXCopyConstructor, 14610 Const); 14611 14612 DeclarationName Name 14613 = Context.DeclarationNames.getCXXConstructorName( 14614 Context.getCanonicalType(ClassType)); 14615 SourceLocation ClassLoc = ClassDecl->getLocation(); 14616 DeclarationNameInfo NameInfo(Name, ClassLoc); 14617 14618 // An implicitly-declared copy constructor is an inline public 14619 // member of its class. 14620 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 14621 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14622 ExplicitSpecifier(), 14623 /*isInline=*/true, 14624 /*isImplicitlyDeclared=*/true, 14625 Constexpr ? ConstexprSpecKind::Constexpr 14626 : ConstexprSpecKind::Unspecified); 14627 CopyConstructor->setAccess(AS_public); 14628 CopyConstructor->setDefaulted(); 14629 14630 if (getLangOpts().CUDA) { 14631 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 14632 CopyConstructor, 14633 /* ConstRHS */ Const, 14634 /* Diagnose */ false); 14635 } 14636 14637 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 14638 14639 // Add the parameter to the constructor. 14640 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 14641 ClassLoc, ClassLoc, 14642 /*IdentifierInfo=*/nullptr, 14643 ArgType, /*TInfo=*/nullptr, 14644 SC_None, nullptr); 14645 CopyConstructor->setParams(FromParam); 14646 14647 CopyConstructor->setTrivial( 14648 ClassDecl->needsOverloadResolutionForCopyConstructor() 14649 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 14650 : ClassDecl->hasTrivialCopyConstructor()); 14651 14652 CopyConstructor->setTrivialForCall( 14653 ClassDecl->hasAttr<TrivialABIAttr>() || 14654 (ClassDecl->needsOverloadResolutionForCopyConstructor() 14655 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 14656 TAH_ConsiderTrivialABI) 14657 : ClassDecl->hasTrivialCopyConstructorForCall())); 14658 14659 // Note that we have declared this constructor. 14660 ++getASTContext().NumImplicitCopyConstructorsDeclared; 14661 14662 Scope *S = getScopeForContext(ClassDecl); 14663 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 14664 14665 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 14666 ClassDecl->setImplicitCopyConstructorIsDeleted(); 14667 SetDeclDeleted(CopyConstructor, ClassLoc); 14668 } 14669 14670 if (S) 14671 PushOnScopeChains(CopyConstructor, S, false); 14672 ClassDecl->addDecl(CopyConstructor); 14673 14674 return CopyConstructor; 14675 } 14676 14677 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 14678 CXXConstructorDecl *CopyConstructor) { 14679 assert((CopyConstructor->isDefaulted() && 14680 CopyConstructor->isCopyConstructor() && 14681 !CopyConstructor->doesThisDeclarationHaveABody() && 14682 !CopyConstructor->isDeleted()) && 14683 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 14684 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 14685 return; 14686 14687 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 14688 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 14689 14690 SynthesizedFunctionScope Scope(*this, CopyConstructor); 14691 14692 // The exception specification is needed because we are defining the 14693 // function. 14694 ResolveExceptionSpec(CurrentLocation, 14695 CopyConstructor->getType()->castAs<FunctionProtoType>()); 14696 MarkVTableUsed(CurrentLocation, ClassDecl); 14697 14698 // Add a context note for diagnostics produced after this point. 14699 Scope.addContextNote(CurrentLocation); 14700 14701 // C++11 [class.copy]p7: 14702 // The [definition of an implicitly declared copy constructor] is 14703 // deprecated if the class has a user-declared copy assignment operator 14704 // or a user-declared destructor. 14705 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 14706 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 14707 14708 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 14709 CopyConstructor->setInvalidDecl(); 14710 } else { 14711 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 14712 ? CopyConstructor->getEndLoc() 14713 : CopyConstructor->getLocation(); 14714 Sema::CompoundScopeRAII CompoundScope(*this); 14715 CopyConstructor->setBody( 14716 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 14717 CopyConstructor->markUsed(Context); 14718 } 14719 14720 if (ASTMutationListener *L = getASTMutationListener()) { 14721 L->CompletedImplicitDefinition(CopyConstructor); 14722 } 14723 } 14724 14725 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 14726 CXXRecordDecl *ClassDecl) { 14727 assert(ClassDecl->needsImplicitMoveConstructor()); 14728 14729 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 14730 if (DSM.isAlreadyBeingDeclared()) 14731 return nullptr; 14732 14733 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14734 14735 QualType ArgType = ClassType; 14736 LangAS AS = getDefaultCXXMethodAddrSpace(); 14737 if (AS != LangAS::Default) 14738 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 14739 ArgType = Context.getRValueReferenceType(ArgType); 14740 14741 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14742 CXXMoveConstructor, 14743 false); 14744 14745 DeclarationName Name 14746 = Context.DeclarationNames.getCXXConstructorName( 14747 Context.getCanonicalType(ClassType)); 14748 SourceLocation ClassLoc = ClassDecl->getLocation(); 14749 DeclarationNameInfo NameInfo(Name, ClassLoc); 14750 14751 // C++11 [class.copy]p11: 14752 // An implicitly-declared copy/move constructor is an inline public 14753 // member of its class. 14754 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 14755 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14756 ExplicitSpecifier(), 14757 /*isInline=*/true, 14758 /*isImplicitlyDeclared=*/true, 14759 Constexpr ? ConstexprSpecKind::Constexpr 14760 : ConstexprSpecKind::Unspecified); 14761 MoveConstructor->setAccess(AS_public); 14762 MoveConstructor->setDefaulted(); 14763 14764 if (getLangOpts().CUDA) { 14765 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 14766 MoveConstructor, 14767 /* ConstRHS */ false, 14768 /* Diagnose */ false); 14769 } 14770 14771 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 14772 14773 // Add the parameter to the constructor. 14774 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 14775 ClassLoc, ClassLoc, 14776 /*IdentifierInfo=*/nullptr, 14777 ArgType, /*TInfo=*/nullptr, 14778 SC_None, nullptr); 14779 MoveConstructor->setParams(FromParam); 14780 14781 MoveConstructor->setTrivial( 14782 ClassDecl->needsOverloadResolutionForMoveConstructor() 14783 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 14784 : ClassDecl->hasTrivialMoveConstructor()); 14785 14786 MoveConstructor->setTrivialForCall( 14787 ClassDecl->hasAttr<TrivialABIAttr>() || 14788 (ClassDecl->needsOverloadResolutionForMoveConstructor() 14789 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 14790 TAH_ConsiderTrivialABI) 14791 : ClassDecl->hasTrivialMoveConstructorForCall())); 14792 14793 // Note that we have declared this constructor. 14794 ++getASTContext().NumImplicitMoveConstructorsDeclared; 14795 14796 Scope *S = getScopeForContext(ClassDecl); 14797 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 14798 14799 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 14800 ClassDecl->setImplicitMoveConstructorIsDeleted(); 14801 SetDeclDeleted(MoveConstructor, ClassLoc); 14802 } 14803 14804 if (S) 14805 PushOnScopeChains(MoveConstructor, S, false); 14806 ClassDecl->addDecl(MoveConstructor); 14807 14808 return MoveConstructor; 14809 } 14810 14811 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 14812 CXXConstructorDecl *MoveConstructor) { 14813 assert((MoveConstructor->isDefaulted() && 14814 MoveConstructor->isMoveConstructor() && 14815 !MoveConstructor->doesThisDeclarationHaveABody() && 14816 !MoveConstructor->isDeleted()) && 14817 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 14818 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 14819 return; 14820 14821 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 14822 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 14823 14824 SynthesizedFunctionScope Scope(*this, MoveConstructor); 14825 14826 // The exception specification is needed because we are defining the 14827 // function. 14828 ResolveExceptionSpec(CurrentLocation, 14829 MoveConstructor->getType()->castAs<FunctionProtoType>()); 14830 MarkVTableUsed(CurrentLocation, ClassDecl); 14831 14832 // Add a context note for diagnostics produced after this point. 14833 Scope.addContextNote(CurrentLocation); 14834 14835 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 14836 MoveConstructor->setInvalidDecl(); 14837 } else { 14838 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 14839 ? MoveConstructor->getEndLoc() 14840 : MoveConstructor->getLocation(); 14841 Sema::CompoundScopeRAII CompoundScope(*this); 14842 MoveConstructor->setBody(ActOnCompoundStmt( 14843 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 14844 MoveConstructor->markUsed(Context); 14845 } 14846 14847 if (ASTMutationListener *L = getASTMutationListener()) { 14848 L->CompletedImplicitDefinition(MoveConstructor); 14849 } 14850 } 14851 14852 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 14853 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 14854 } 14855 14856 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 14857 SourceLocation CurrentLocation, 14858 CXXConversionDecl *Conv) { 14859 SynthesizedFunctionScope Scope(*this, Conv); 14860 assert(!Conv->getReturnType()->isUndeducedType()); 14861 14862 QualType ConvRT = Conv->getType()->getAs<FunctionType>()->getReturnType(); 14863 CallingConv CC = 14864 ConvRT->getPointeeType()->getAs<FunctionType>()->getCallConv(); 14865 14866 CXXRecordDecl *Lambda = Conv->getParent(); 14867 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 14868 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC); 14869 14870 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 14871 CallOp = InstantiateFunctionDeclaration( 14872 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14873 if (!CallOp) 14874 return; 14875 14876 Invoker = InstantiateFunctionDeclaration( 14877 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14878 if (!Invoker) 14879 return; 14880 } 14881 14882 if (CallOp->isInvalidDecl()) 14883 return; 14884 14885 // Mark the call operator referenced (and add to pending instantiations 14886 // if necessary). 14887 // For both the conversion and static-invoker template specializations 14888 // we construct their body's in this function, so no need to add them 14889 // to the PendingInstantiations. 14890 MarkFunctionReferenced(CurrentLocation, CallOp); 14891 14892 // Fill in the __invoke function with a dummy implementation. IR generation 14893 // will fill in the actual details. Update its type in case it contained 14894 // an 'auto'. 14895 Invoker->markUsed(Context); 14896 Invoker->setReferenced(); 14897 Invoker->setType(Conv->getReturnType()->getPointeeType()); 14898 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 14899 14900 // Construct the body of the conversion function { return __invoke; }. 14901 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 14902 VK_LValue, Conv->getLocation()); 14903 assert(FunctionRef && "Can't refer to __invoke function?"); 14904 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 14905 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 14906 Conv->getLocation())); 14907 Conv->markUsed(Context); 14908 Conv->setReferenced(); 14909 14910 if (ASTMutationListener *L = getASTMutationListener()) { 14911 L->CompletedImplicitDefinition(Conv); 14912 L->CompletedImplicitDefinition(Invoker); 14913 } 14914 } 14915 14916 14917 14918 void Sema::DefineImplicitLambdaToBlockPointerConversion( 14919 SourceLocation CurrentLocation, 14920 CXXConversionDecl *Conv) 14921 { 14922 assert(!Conv->getParent()->isGenericLambda()); 14923 14924 SynthesizedFunctionScope Scope(*this, Conv); 14925 14926 // Copy-initialize the lambda object as needed to capture it. 14927 Expr *This = ActOnCXXThis(CurrentLocation).get(); 14928 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 14929 14930 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 14931 Conv->getLocation(), 14932 Conv, DerefThis); 14933 14934 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 14935 // behavior. Note that only the general conversion function does this 14936 // (since it's unusable otherwise); in the case where we inline the 14937 // block literal, it has block literal lifetime semantics. 14938 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 14939 BuildBlock = ImplicitCastExpr::Create( 14940 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject, 14941 BuildBlock.get(), nullptr, VK_RValue, FPOptionsOverride()); 14942 14943 if (BuildBlock.isInvalid()) { 14944 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14945 Conv->setInvalidDecl(); 14946 return; 14947 } 14948 14949 // Create the return statement that returns the block from the conversion 14950 // function. 14951 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 14952 if (Return.isInvalid()) { 14953 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14954 Conv->setInvalidDecl(); 14955 return; 14956 } 14957 14958 // Set the body of the conversion function. 14959 Stmt *ReturnS = Return.get(); 14960 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 14961 Conv->getLocation())); 14962 Conv->markUsed(Context); 14963 14964 // We're done; notify the mutation listener, if any. 14965 if (ASTMutationListener *L = getASTMutationListener()) { 14966 L->CompletedImplicitDefinition(Conv); 14967 } 14968 } 14969 14970 /// Determine whether the given list arguments contains exactly one 14971 /// "real" (non-default) argument. 14972 static bool hasOneRealArgument(MultiExprArg Args) { 14973 switch (Args.size()) { 14974 case 0: 14975 return false; 14976 14977 default: 14978 if (!Args[1]->isDefaultArgument()) 14979 return false; 14980 14981 LLVM_FALLTHROUGH; 14982 case 1: 14983 return !Args[0]->isDefaultArgument(); 14984 } 14985 14986 return false; 14987 } 14988 14989 ExprResult 14990 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14991 NamedDecl *FoundDecl, 14992 CXXConstructorDecl *Constructor, 14993 MultiExprArg ExprArgs, 14994 bool HadMultipleCandidates, 14995 bool IsListInitialization, 14996 bool IsStdInitListInitialization, 14997 bool RequiresZeroInit, 14998 unsigned ConstructKind, 14999 SourceRange ParenRange) { 15000 bool Elidable = false; 15001 15002 // C++0x [class.copy]p34: 15003 // When certain criteria are met, an implementation is allowed to 15004 // omit the copy/move construction of a class object, even if the 15005 // copy/move constructor and/or destructor for the object have 15006 // side effects. [...] 15007 // - when a temporary class object that has not been bound to a 15008 // reference (12.2) would be copied/moved to a class object 15009 // with the same cv-unqualified type, the copy/move operation 15010 // can be omitted by constructing the temporary object 15011 // directly into the target of the omitted copy/move 15012 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 15013 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 15014 Expr *SubExpr = ExprArgs[0]; 15015 Elidable = SubExpr->isTemporaryObject( 15016 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 15017 } 15018 15019 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 15020 FoundDecl, Constructor, 15021 Elidable, ExprArgs, HadMultipleCandidates, 15022 IsListInitialization, 15023 IsStdInitListInitialization, RequiresZeroInit, 15024 ConstructKind, ParenRange); 15025 } 15026 15027 ExprResult 15028 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15029 NamedDecl *FoundDecl, 15030 CXXConstructorDecl *Constructor, 15031 bool Elidable, 15032 MultiExprArg ExprArgs, 15033 bool HadMultipleCandidates, 15034 bool IsListInitialization, 15035 bool IsStdInitListInitialization, 15036 bool RequiresZeroInit, 15037 unsigned ConstructKind, 15038 SourceRange ParenRange) { 15039 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 15040 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 15041 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 15042 return ExprError(); 15043 } 15044 15045 return BuildCXXConstructExpr( 15046 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 15047 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 15048 RequiresZeroInit, ConstructKind, ParenRange); 15049 } 15050 15051 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 15052 /// including handling of its default argument expressions. 15053 ExprResult 15054 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15055 CXXConstructorDecl *Constructor, 15056 bool Elidable, 15057 MultiExprArg ExprArgs, 15058 bool HadMultipleCandidates, 15059 bool IsListInitialization, 15060 bool IsStdInitListInitialization, 15061 bool RequiresZeroInit, 15062 unsigned ConstructKind, 15063 SourceRange ParenRange) { 15064 assert(declaresSameEntity( 15065 Constructor->getParent(), 15066 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 15067 "given constructor for wrong type"); 15068 MarkFunctionReferenced(ConstructLoc, Constructor); 15069 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 15070 return ExprError(); 15071 if (getLangOpts().SYCLIsDevice && 15072 !checkSYCLDeviceFunction(ConstructLoc, Constructor)) 15073 return ExprError(); 15074 15075 return CheckForImmediateInvocation( 15076 CXXConstructExpr::Create( 15077 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 15078 HadMultipleCandidates, IsListInitialization, 15079 IsStdInitListInitialization, RequiresZeroInit, 15080 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 15081 ParenRange), 15082 Constructor); 15083 } 15084 15085 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 15086 assert(Field->hasInClassInitializer()); 15087 15088 // If we already have the in-class initializer nothing needs to be done. 15089 if (Field->getInClassInitializer()) 15090 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15091 15092 // If we might have already tried and failed to instantiate, don't try again. 15093 if (Field->isInvalidDecl()) 15094 return ExprError(); 15095 15096 // Maybe we haven't instantiated the in-class initializer. Go check the 15097 // pattern FieldDecl to see if it has one. 15098 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 15099 15100 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 15101 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 15102 DeclContext::lookup_result Lookup = 15103 ClassPattern->lookup(Field->getDeclName()); 15104 15105 FieldDecl *Pattern = nullptr; 15106 for (auto L : Lookup) { 15107 if (isa<FieldDecl>(L)) { 15108 Pattern = cast<FieldDecl>(L); 15109 break; 15110 } 15111 } 15112 assert(Pattern && "We must have set the Pattern!"); 15113 15114 if (!Pattern->hasInClassInitializer() || 15115 InstantiateInClassInitializer(Loc, Field, Pattern, 15116 getTemplateInstantiationArgs(Field))) { 15117 // Don't diagnose this again. 15118 Field->setInvalidDecl(); 15119 return ExprError(); 15120 } 15121 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15122 } 15123 15124 // DR1351: 15125 // If the brace-or-equal-initializer of a non-static data member 15126 // invokes a defaulted default constructor of its class or of an 15127 // enclosing class in a potentially evaluated subexpression, the 15128 // program is ill-formed. 15129 // 15130 // This resolution is unworkable: the exception specification of the 15131 // default constructor can be needed in an unevaluated context, in 15132 // particular, in the operand of a noexcept-expression, and we can be 15133 // unable to compute an exception specification for an enclosed class. 15134 // 15135 // Any attempt to resolve the exception specification of a defaulted default 15136 // constructor before the initializer is lexically complete will ultimately 15137 // come here at which point we can diagnose it. 15138 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 15139 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed) 15140 << OutermostClass << Field; 15141 Diag(Field->getEndLoc(), 15142 diag::note_default_member_initializer_not_yet_parsed); 15143 // Recover by marking the field invalid, unless we're in a SFINAE context. 15144 if (!isSFINAEContext()) 15145 Field->setInvalidDecl(); 15146 return ExprError(); 15147 } 15148 15149 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 15150 if (VD->isInvalidDecl()) return; 15151 // If initializing the variable failed, don't also diagnose problems with 15152 // the desctructor, they're likely related. 15153 if (VD->getInit() && VD->getInit()->containsErrors()) 15154 return; 15155 15156 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 15157 if (ClassDecl->isInvalidDecl()) return; 15158 if (ClassDecl->hasIrrelevantDestructor()) return; 15159 if (ClassDecl->isDependentContext()) return; 15160 15161 if (VD->isNoDestroy(getASTContext())) 15162 return; 15163 15164 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15165 15166 // If this is an array, we'll require the destructor during initialization, so 15167 // we can skip over this. We still want to emit exit-time destructor warnings 15168 // though. 15169 if (!VD->getType()->isArrayType()) { 15170 MarkFunctionReferenced(VD->getLocation(), Destructor); 15171 CheckDestructorAccess(VD->getLocation(), Destructor, 15172 PDiag(diag::err_access_dtor_var) 15173 << VD->getDeclName() << VD->getType()); 15174 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 15175 } 15176 15177 if (Destructor->isTrivial()) return; 15178 15179 // If the destructor is constexpr, check whether the variable has constant 15180 // destruction now. 15181 if (Destructor->isConstexpr()) { 15182 bool HasConstantInit = false; 15183 if (VD->getInit() && !VD->getInit()->isValueDependent()) 15184 HasConstantInit = VD->evaluateValue(); 15185 SmallVector<PartialDiagnosticAt, 8> Notes; 15186 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && 15187 HasConstantInit) { 15188 Diag(VD->getLocation(), 15189 diag::err_constexpr_var_requires_const_destruction) << VD; 15190 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 15191 Diag(Notes[I].first, Notes[I].second); 15192 } 15193 } 15194 15195 if (!VD->hasGlobalStorage()) return; 15196 15197 // Emit warning for non-trivial dtor in global scope (a real global, 15198 // class-static, function-static). 15199 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 15200 15201 // TODO: this should be re-enabled for static locals by !CXAAtExit 15202 if (!VD->isStaticLocal()) 15203 Diag(VD->getLocation(), diag::warn_global_destructor); 15204 } 15205 15206 /// Given a constructor and the set of arguments provided for the 15207 /// constructor, convert the arguments and add any required default arguments 15208 /// to form a proper call to this constructor. 15209 /// 15210 /// \returns true if an error occurred, false otherwise. 15211 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 15212 QualType DeclInitType, MultiExprArg ArgsPtr, 15213 SourceLocation Loc, 15214 SmallVectorImpl<Expr *> &ConvertedArgs, 15215 bool AllowExplicit, 15216 bool IsListInitialization) { 15217 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 15218 unsigned NumArgs = ArgsPtr.size(); 15219 Expr **Args = ArgsPtr.data(); 15220 15221 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); 15222 unsigned NumParams = Proto->getNumParams(); 15223 15224 // If too few arguments are available, we'll fill in the rest with defaults. 15225 if (NumArgs < NumParams) 15226 ConvertedArgs.reserve(NumParams); 15227 else 15228 ConvertedArgs.reserve(NumArgs); 15229 15230 VariadicCallType CallType = 15231 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 15232 SmallVector<Expr *, 8> AllArgs; 15233 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 15234 Proto, 0, 15235 llvm::makeArrayRef(Args, NumArgs), 15236 AllArgs, 15237 CallType, AllowExplicit, 15238 IsListInitialization); 15239 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 15240 15241 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 15242 15243 CheckConstructorCall(Constructor, DeclInitType, 15244 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 15245 Proto, Loc); 15246 15247 return Invalid; 15248 } 15249 15250 static inline bool 15251 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 15252 const FunctionDecl *FnDecl) { 15253 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 15254 if (isa<NamespaceDecl>(DC)) { 15255 return SemaRef.Diag(FnDecl->getLocation(), 15256 diag::err_operator_new_delete_declared_in_namespace) 15257 << FnDecl->getDeclName(); 15258 } 15259 15260 if (isa<TranslationUnitDecl>(DC) && 15261 FnDecl->getStorageClass() == SC_Static) { 15262 return SemaRef.Diag(FnDecl->getLocation(), 15263 diag::err_operator_new_delete_declared_static) 15264 << FnDecl->getDeclName(); 15265 } 15266 15267 return false; 15268 } 15269 15270 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, 15271 const PointerType *PtrTy) { 15272 auto &Ctx = SemaRef.Context; 15273 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers(); 15274 PtrQuals.removeAddressSpace(); 15275 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType( 15276 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals))); 15277 } 15278 15279 static inline bool 15280 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 15281 CanQualType ExpectedResultType, 15282 CanQualType ExpectedFirstParamType, 15283 unsigned DependentParamTypeDiag, 15284 unsigned InvalidParamTypeDiag) { 15285 QualType ResultType = 15286 FnDecl->getType()->castAs<FunctionType>()->getReturnType(); 15287 15288 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15289 // The operator is valid on any address space for OpenCL. 15290 // Drop address space from actual and expected result types. 15291 if (const auto *PtrTy = ResultType->getAs<PointerType>()) 15292 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15293 15294 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>()) 15295 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15296 } 15297 15298 // Check that the result type is what we expect. 15299 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) { 15300 // Reject even if the type is dependent; an operator delete function is 15301 // required to have a non-dependent result type. 15302 return SemaRef.Diag( 15303 FnDecl->getLocation(), 15304 ResultType->isDependentType() 15305 ? diag::err_operator_new_delete_dependent_result_type 15306 : diag::err_operator_new_delete_invalid_result_type) 15307 << FnDecl->getDeclName() << ExpectedResultType; 15308 } 15309 15310 // A function template must have at least 2 parameters. 15311 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 15312 return SemaRef.Diag(FnDecl->getLocation(), 15313 diag::err_operator_new_delete_template_too_few_parameters) 15314 << FnDecl->getDeclName(); 15315 15316 // The function decl must have at least 1 parameter. 15317 if (FnDecl->getNumParams() == 0) 15318 return SemaRef.Diag(FnDecl->getLocation(), 15319 diag::err_operator_new_delete_too_few_parameters) 15320 << FnDecl->getDeclName(); 15321 15322 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 15323 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15324 // The operator is valid on any address space for OpenCL. 15325 // Drop address space from actual and expected first parameter types. 15326 if (const auto *PtrTy = 15327 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) 15328 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15329 15330 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>()) 15331 ExpectedFirstParamType = 15332 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15333 } 15334 15335 // Check that the first parameter type is what we expect. 15336 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 15337 ExpectedFirstParamType) { 15338 // The first parameter type is not allowed to be dependent. As a tentative 15339 // DR resolution, we allow a dependent parameter type if it is the right 15340 // type anyway, to allow destroying operator delete in class templates. 15341 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType() 15342 ? DependentParamTypeDiag 15343 : InvalidParamTypeDiag) 15344 << FnDecl->getDeclName() << ExpectedFirstParamType; 15345 } 15346 15347 return false; 15348 } 15349 15350 static bool 15351 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 15352 // C++ [basic.stc.dynamic.allocation]p1: 15353 // A program is ill-formed if an allocation function is declared in a 15354 // namespace scope other than global scope or declared static in global 15355 // scope. 15356 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15357 return true; 15358 15359 CanQualType SizeTy = 15360 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 15361 15362 // C++ [basic.stc.dynamic.allocation]p1: 15363 // The return type shall be void*. The first parameter shall have type 15364 // std::size_t. 15365 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 15366 SizeTy, 15367 diag::err_operator_new_dependent_param_type, 15368 diag::err_operator_new_param_type)) 15369 return true; 15370 15371 // C++ [basic.stc.dynamic.allocation]p1: 15372 // The first parameter shall not have an associated default argument. 15373 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 15374 return SemaRef.Diag(FnDecl->getLocation(), 15375 diag::err_operator_new_default_arg) 15376 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 15377 15378 return false; 15379 } 15380 15381 static bool 15382 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 15383 // C++ [basic.stc.dynamic.deallocation]p1: 15384 // A program is ill-formed if deallocation functions are declared in a 15385 // namespace scope other than global scope or declared static in global 15386 // scope. 15387 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15388 return true; 15389 15390 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 15391 15392 // C++ P0722: 15393 // Within a class C, the first parameter of a destroying operator delete 15394 // shall be of type C *. The first parameter of any other deallocation 15395 // function shall be of type void *. 15396 CanQualType ExpectedFirstParamType = 15397 MD && MD->isDestroyingOperatorDelete() 15398 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 15399 SemaRef.Context.getRecordType(MD->getParent()))) 15400 : SemaRef.Context.VoidPtrTy; 15401 15402 // C++ [basic.stc.dynamic.deallocation]p2: 15403 // Each deallocation function shall return void 15404 if (CheckOperatorNewDeleteTypes( 15405 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 15406 diag::err_operator_delete_dependent_param_type, 15407 diag::err_operator_delete_param_type)) 15408 return true; 15409 15410 // C++ P0722: 15411 // A destroying operator delete shall be a usual deallocation function. 15412 if (MD && !MD->getParent()->isDependentContext() && 15413 MD->isDestroyingOperatorDelete() && 15414 !SemaRef.isUsualDeallocationFunction(MD)) { 15415 SemaRef.Diag(MD->getLocation(), 15416 diag::err_destroying_operator_delete_not_usual); 15417 return true; 15418 } 15419 15420 return false; 15421 } 15422 15423 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 15424 /// of this overloaded operator is well-formed. If so, returns false; 15425 /// otherwise, emits appropriate diagnostics and returns true. 15426 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 15427 assert(FnDecl && FnDecl->isOverloadedOperator() && 15428 "Expected an overloaded operator declaration"); 15429 15430 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 15431 15432 // C++ [over.oper]p5: 15433 // The allocation and deallocation functions, operator new, 15434 // operator new[], operator delete and operator delete[], are 15435 // described completely in 3.7.3. The attributes and restrictions 15436 // found in the rest of this subclause do not apply to them unless 15437 // explicitly stated in 3.7.3. 15438 if (Op == OO_Delete || Op == OO_Array_Delete) 15439 return CheckOperatorDeleteDeclaration(*this, FnDecl); 15440 15441 if (Op == OO_New || Op == OO_Array_New) 15442 return CheckOperatorNewDeclaration(*this, FnDecl); 15443 15444 // C++ [over.oper]p6: 15445 // An operator function shall either be a non-static member 15446 // function or be a non-member function and have at least one 15447 // parameter whose type is a class, a reference to a class, an 15448 // enumeration, or a reference to an enumeration. 15449 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 15450 if (MethodDecl->isStatic()) 15451 return Diag(FnDecl->getLocation(), 15452 diag::err_operator_overload_static) << FnDecl->getDeclName(); 15453 } else { 15454 bool ClassOrEnumParam = false; 15455 for (auto Param : FnDecl->parameters()) { 15456 QualType ParamType = Param->getType().getNonReferenceType(); 15457 if (ParamType->isDependentType() || ParamType->isRecordType() || 15458 ParamType->isEnumeralType()) { 15459 ClassOrEnumParam = true; 15460 break; 15461 } 15462 } 15463 15464 if (!ClassOrEnumParam) 15465 return Diag(FnDecl->getLocation(), 15466 diag::err_operator_overload_needs_class_or_enum) 15467 << FnDecl->getDeclName(); 15468 } 15469 15470 // C++ [over.oper]p8: 15471 // An operator function cannot have default arguments (8.3.6), 15472 // except where explicitly stated below. 15473 // 15474 // Only the function-call operator allows default arguments 15475 // (C++ [over.call]p1). 15476 if (Op != OO_Call) { 15477 for (auto Param : FnDecl->parameters()) { 15478 if (Param->hasDefaultArg()) 15479 return Diag(Param->getLocation(), 15480 diag::err_operator_overload_default_arg) 15481 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 15482 } 15483 } 15484 15485 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 15486 { false, false, false } 15487 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 15488 , { Unary, Binary, MemberOnly } 15489 #include "clang/Basic/OperatorKinds.def" 15490 }; 15491 15492 bool CanBeUnaryOperator = OperatorUses[Op][0]; 15493 bool CanBeBinaryOperator = OperatorUses[Op][1]; 15494 bool MustBeMemberOperator = OperatorUses[Op][2]; 15495 15496 // C++ [over.oper]p8: 15497 // [...] Operator functions cannot have more or fewer parameters 15498 // than the number required for the corresponding operator, as 15499 // described in the rest of this subclause. 15500 unsigned NumParams = FnDecl->getNumParams() 15501 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 15502 if (Op != OO_Call && 15503 ((NumParams == 1 && !CanBeUnaryOperator) || 15504 (NumParams == 2 && !CanBeBinaryOperator) || 15505 (NumParams < 1) || (NumParams > 2))) { 15506 // We have the wrong number of parameters. 15507 unsigned ErrorKind; 15508 if (CanBeUnaryOperator && CanBeBinaryOperator) { 15509 ErrorKind = 2; // 2 -> unary or binary. 15510 } else if (CanBeUnaryOperator) { 15511 ErrorKind = 0; // 0 -> unary 15512 } else { 15513 assert(CanBeBinaryOperator && 15514 "All non-call overloaded operators are unary or binary!"); 15515 ErrorKind = 1; // 1 -> binary 15516 } 15517 15518 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 15519 << FnDecl->getDeclName() << NumParams << ErrorKind; 15520 } 15521 15522 // Overloaded operators other than operator() cannot be variadic. 15523 if (Op != OO_Call && 15524 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { 15525 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 15526 << FnDecl->getDeclName(); 15527 } 15528 15529 // Some operators must be non-static member functions. 15530 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 15531 return Diag(FnDecl->getLocation(), 15532 diag::err_operator_overload_must_be_member) 15533 << FnDecl->getDeclName(); 15534 } 15535 15536 // C++ [over.inc]p1: 15537 // The user-defined function called operator++ implements the 15538 // prefix and postfix ++ operator. If this function is a member 15539 // function with no parameters, or a non-member function with one 15540 // parameter of class or enumeration type, it defines the prefix 15541 // increment operator ++ for objects of that type. If the function 15542 // is a member function with one parameter (which shall be of type 15543 // int) or a non-member function with two parameters (the second 15544 // of which shall be of type int), it defines the postfix 15545 // increment operator ++ for objects of that type. 15546 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 15547 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 15548 QualType ParamType = LastParam->getType(); 15549 15550 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 15551 !ParamType->isDependentType()) 15552 return Diag(LastParam->getLocation(), 15553 diag::err_operator_overload_post_incdec_must_be_int) 15554 << LastParam->getType() << (Op == OO_MinusMinus); 15555 } 15556 15557 return false; 15558 } 15559 15560 static bool 15561 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 15562 FunctionTemplateDecl *TpDecl) { 15563 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 15564 15565 // Must have one or two template parameters. 15566 if (TemplateParams->size() == 1) { 15567 NonTypeTemplateParmDecl *PmDecl = 15568 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 15569 15570 // The template parameter must be a char parameter pack. 15571 if (PmDecl && PmDecl->isTemplateParameterPack() && 15572 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 15573 return false; 15574 15575 // C++20 [over.literal]p5: 15576 // A string literal operator template is a literal operator template 15577 // whose template-parameter-list comprises a single non-type 15578 // template-parameter of class type. 15579 // 15580 // As a DR resolution, we also allow placeholders for deduced class 15581 // template specializations. 15582 if (SemaRef.getLangOpts().CPlusPlus20 && 15583 !PmDecl->isTemplateParameterPack() && 15584 (PmDecl->getType()->isRecordType() || 15585 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>())) 15586 return false; 15587 } else if (TemplateParams->size() == 2) { 15588 TemplateTypeParmDecl *PmType = 15589 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 15590 NonTypeTemplateParmDecl *PmArgs = 15591 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 15592 15593 // The second template parameter must be a parameter pack with the 15594 // first template parameter as its type. 15595 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 15596 PmArgs->isTemplateParameterPack()) { 15597 const TemplateTypeParmType *TArgs = 15598 PmArgs->getType()->getAs<TemplateTypeParmType>(); 15599 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 15600 TArgs->getIndex() == PmType->getIndex()) { 15601 if (!SemaRef.inTemplateInstantiation()) 15602 SemaRef.Diag(TpDecl->getLocation(), 15603 diag::ext_string_literal_operator_template); 15604 return false; 15605 } 15606 } 15607 } 15608 15609 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 15610 diag::err_literal_operator_template) 15611 << TpDecl->getTemplateParameters()->getSourceRange(); 15612 return true; 15613 } 15614 15615 /// CheckLiteralOperatorDeclaration - Check whether the declaration 15616 /// of this literal operator function is well-formed. If so, returns 15617 /// false; otherwise, emits appropriate diagnostics and returns true. 15618 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 15619 if (isa<CXXMethodDecl>(FnDecl)) { 15620 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 15621 << FnDecl->getDeclName(); 15622 return true; 15623 } 15624 15625 if (FnDecl->isExternC()) { 15626 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 15627 if (const LinkageSpecDecl *LSD = 15628 FnDecl->getDeclContext()->getExternCContext()) 15629 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 15630 return true; 15631 } 15632 15633 // This might be the definition of a literal operator template. 15634 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 15635 15636 // This might be a specialization of a literal operator template. 15637 if (!TpDecl) 15638 TpDecl = FnDecl->getPrimaryTemplate(); 15639 15640 // template <char...> type operator "" name() and 15641 // template <class T, T...> type operator "" name() are the only valid 15642 // template signatures, and the only valid signatures with no parameters. 15643 // 15644 // C++20 also allows template <SomeClass T> type operator "" name(). 15645 if (TpDecl) { 15646 if (FnDecl->param_size() != 0) { 15647 Diag(FnDecl->getLocation(), 15648 diag::err_literal_operator_template_with_params); 15649 return true; 15650 } 15651 15652 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 15653 return true; 15654 15655 } else if (FnDecl->param_size() == 1) { 15656 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 15657 15658 QualType ParamType = Param->getType().getUnqualifiedType(); 15659 15660 // Only unsigned long long int, long double, any character type, and const 15661 // char * are allowed as the only parameters. 15662 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 15663 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 15664 Context.hasSameType(ParamType, Context.CharTy) || 15665 Context.hasSameType(ParamType, Context.WideCharTy) || 15666 Context.hasSameType(ParamType, Context.Char8Ty) || 15667 Context.hasSameType(ParamType, Context.Char16Ty) || 15668 Context.hasSameType(ParamType, Context.Char32Ty)) { 15669 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 15670 QualType InnerType = Ptr->getPointeeType(); 15671 15672 // Pointer parameter must be a const char *. 15673 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 15674 Context.CharTy) && 15675 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 15676 Diag(Param->getSourceRange().getBegin(), 15677 diag::err_literal_operator_param) 15678 << ParamType << "'const char *'" << Param->getSourceRange(); 15679 return true; 15680 } 15681 15682 } else if (ParamType->isRealFloatingType()) { 15683 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15684 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 15685 return true; 15686 15687 } else if (ParamType->isIntegerType()) { 15688 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15689 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 15690 return true; 15691 15692 } else { 15693 Diag(Param->getSourceRange().getBegin(), 15694 diag::err_literal_operator_invalid_param) 15695 << ParamType << Param->getSourceRange(); 15696 return true; 15697 } 15698 15699 } else if (FnDecl->param_size() == 2) { 15700 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 15701 15702 // First, verify that the first parameter is correct. 15703 15704 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 15705 15706 // Two parameter function must have a pointer to const as a 15707 // first parameter; let's strip those qualifiers. 15708 const PointerType *PT = FirstParamType->getAs<PointerType>(); 15709 15710 if (!PT) { 15711 Diag((*Param)->getSourceRange().getBegin(), 15712 diag::err_literal_operator_param) 15713 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15714 return true; 15715 } 15716 15717 QualType PointeeType = PT->getPointeeType(); 15718 // First parameter must be const 15719 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 15720 Diag((*Param)->getSourceRange().getBegin(), 15721 diag::err_literal_operator_param) 15722 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15723 return true; 15724 } 15725 15726 QualType InnerType = PointeeType.getUnqualifiedType(); 15727 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 15728 // const char32_t* are allowed as the first parameter to a two-parameter 15729 // function 15730 if (!(Context.hasSameType(InnerType, Context.CharTy) || 15731 Context.hasSameType(InnerType, Context.WideCharTy) || 15732 Context.hasSameType(InnerType, Context.Char8Ty) || 15733 Context.hasSameType(InnerType, Context.Char16Ty) || 15734 Context.hasSameType(InnerType, Context.Char32Ty))) { 15735 Diag((*Param)->getSourceRange().getBegin(), 15736 diag::err_literal_operator_param) 15737 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15738 return true; 15739 } 15740 15741 // Move on to the second and final parameter. 15742 ++Param; 15743 15744 // The second parameter must be a std::size_t. 15745 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 15746 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 15747 Diag((*Param)->getSourceRange().getBegin(), 15748 diag::err_literal_operator_param) 15749 << SecondParamType << Context.getSizeType() 15750 << (*Param)->getSourceRange(); 15751 return true; 15752 } 15753 } else { 15754 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 15755 return true; 15756 } 15757 15758 // Parameters are good. 15759 15760 // A parameter-declaration-clause containing a default argument is not 15761 // equivalent to any of the permitted forms. 15762 for (auto Param : FnDecl->parameters()) { 15763 if (Param->hasDefaultArg()) { 15764 Diag(Param->getDefaultArgRange().getBegin(), 15765 diag::err_literal_operator_default_argument) 15766 << Param->getDefaultArgRange(); 15767 break; 15768 } 15769 } 15770 15771 StringRef LiteralName 15772 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 15773 if (LiteralName[0] != '_' && 15774 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 15775 // C++11 [usrlit.suffix]p1: 15776 // Literal suffix identifiers that do not start with an underscore 15777 // are reserved for future standardization. 15778 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 15779 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 15780 } 15781 15782 return false; 15783 } 15784 15785 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 15786 /// linkage specification, including the language and (if present) 15787 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 15788 /// language string literal. LBraceLoc, if valid, provides the location of 15789 /// the '{' brace. Otherwise, this linkage specification does not 15790 /// have any braces. 15791 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 15792 Expr *LangStr, 15793 SourceLocation LBraceLoc) { 15794 StringLiteral *Lit = cast<StringLiteral>(LangStr); 15795 if (!Lit->isAscii()) { 15796 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 15797 << LangStr->getSourceRange(); 15798 return nullptr; 15799 } 15800 15801 StringRef Lang = Lit->getString(); 15802 LinkageSpecDecl::LanguageIDs Language; 15803 if (Lang == "C") 15804 Language = LinkageSpecDecl::lang_c; 15805 else if (Lang == "C++") 15806 Language = LinkageSpecDecl::lang_cxx; 15807 else { 15808 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 15809 << LangStr->getSourceRange(); 15810 return nullptr; 15811 } 15812 15813 // FIXME: Add all the various semantics of linkage specifications 15814 15815 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 15816 LangStr->getExprLoc(), Language, 15817 LBraceLoc.isValid()); 15818 CurContext->addDecl(D); 15819 PushDeclContext(S, D); 15820 return D; 15821 } 15822 15823 /// ActOnFinishLinkageSpecification - Complete the definition of 15824 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 15825 /// valid, it's the position of the closing '}' brace in a linkage 15826 /// specification that uses braces. 15827 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 15828 Decl *LinkageSpec, 15829 SourceLocation RBraceLoc) { 15830 if (RBraceLoc.isValid()) { 15831 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 15832 LSDecl->setRBraceLoc(RBraceLoc); 15833 } 15834 PopDeclContext(); 15835 return LinkageSpec; 15836 } 15837 15838 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 15839 const ParsedAttributesView &AttrList, 15840 SourceLocation SemiLoc) { 15841 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 15842 // Attribute declarations appertain to empty declaration so we handle 15843 // them here. 15844 ProcessDeclAttributeList(S, ED, AttrList); 15845 15846 CurContext->addDecl(ED); 15847 return ED; 15848 } 15849 15850 /// Perform semantic analysis for the variable declaration that 15851 /// occurs within a C++ catch clause, returning the newly-created 15852 /// variable. 15853 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 15854 TypeSourceInfo *TInfo, 15855 SourceLocation StartLoc, 15856 SourceLocation Loc, 15857 IdentifierInfo *Name) { 15858 bool Invalid = false; 15859 QualType ExDeclType = TInfo->getType(); 15860 15861 // Arrays and functions decay. 15862 if (ExDeclType->isArrayType()) 15863 ExDeclType = Context.getArrayDecayedType(ExDeclType); 15864 else if (ExDeclType->isFunctionType()) 15865 ExDeclType = Context.getPointerType(ExDeclType); 15866 15867 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 15868 // The exception-declaration shall not denote a pointer or reference to an 15869 // incomplete type, other than [cv] void*. 15870 // N2844 forbids rvalue references. 15871 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 15872 Diag(Loc, diag::err_catch_rvalue_ref); 15873 Invalid = true; 15874 } 15875 15876 if (ExDeclType->isVariablyModifiedType()) { 15877 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 15878 Invalid = true; 15879 } 15880 15881 QualType BaseType = ExDeclType; 15882 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 15883 unsigned DK = diag::err_catch_incomplete; 15884 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 15885 BaseType = Ptr->getPointeeType(); 15886 Mode = 1; 15887 DK = diag::err_catch_incomplete_ptr; 15888 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 15889 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 15890 BaseType = Ref->getPointeeType(); 15891 Mode = 2; 15892 DK = diag::err_catch_incomplete_ref; 15893 } 15894 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 15895 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 15896 Invalid = true; 15897 15898 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) { 15899 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType; 15900 Invalid = true; 15901 } 15902 15903 if (!Invalid && !ExDeclType->isDependentType() && 15904 RequireNonAbstractType(Loc, ExDeclType, 15905 diag::err_abstract_type_in_decl, 15906 AbstractVariableType)) 15907 Invalid = true; 15908 15909 // Only the non-fragile NeXT runtime currently supports C++ catches 15910 // of ObjC types, and no runtime supports catching ObjC types by value. 15911 if (!Invalid && getLangOpts().ObjC) { 15912 QualType T = ExDeclType; 15913 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 15914 T = RT->getPointeeType(); 15915 15916 if (T->isObjCObjectType()) { 15917 Diag(Loc, diag::err_objc_object_catch); 15918 Invalid = true; 15919 } else if (T->isObjCObjectPointerType()) { 15920 // FIXME: should this be a test for macosx-fragile specifically? 15921 if (getLangOpts().ObjCRuntime.isFragile()) 15922 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 15923 } 15924 } 15925 15926 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 15927 ExDeclType, TInfo, SC_None); 15928 ExDecl->setExceptionVariable(true); 15929 15930 // In ARC, infer 'retaining' for variables of retainable type. 15931 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 15932 Invalid = true; 15933 15934 if (!Invalid && !ExDeclType->isDependentType()) { 15935 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 15936 // Insulate this from anything else we might currently be parsing. 15937 EnterExpressionEvaluationContext scope( 15938 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15939 15940 // C++ [except.handle]p16: 15941 // The object declared in an exception-declaration or, if the 15942 // exception-declaration does not specify a name, a temporary (12.2) is 15943 // copy-initialized (8.5) from the exception object. [...] 15944 // The object is destroyed when the handler exits, after the destruction 15945 // of any automatic objects initialized within the handler. 15946 // 15947 // We just pretend to initialize the object with itself, then make sure 15948 // it can be destroyed later. 15949 QualType initType = Context.getExceptionObjectType(ExDeclType); 15950 15951 InitializedEntity entity = 15952 InitializedEntity::InitializeVariable(ExDecl); 15953 InitializationKind initKind = 15954 InitializationKind::CreateCopy(Loc, SourceLocation()); 15955 15956 Expr *opaqueValue = 15957 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 15958 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 15959 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 15960 if (result.isInvalid()) 15961 Invalid = true; 15962 else { 15963 // If the constructor used was non-trivial, set this as the 15964 // "initializer". 15965 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 15966 if (!construct->getConstructor()->isTrivial()) { 15967 Expr *init = MaybeCreateExprWithCleanups(construct); 15968 ExDecl->setInit(init); 15969 } 15970 15971 // And make sure it's destructable. 15972 FinalizeVarWithDestructor(ExDecl, recordType); 15973 } 15974 } 15975 } 15976 15977 if (Invalid) 15978 ExDecl->setInvalidDecl(); 15979 15980 return ExDecl; 15981 } 15982 15983 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 15984 /// handler. 15985 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 15986 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15987 bool Invalid = D.isInvalidType(); 15988 15989 // Check for unexpanded parameter packs. 15990 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15991 UPPC_ExceptionType)) { 15992 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 15993 D.getIdentifierLoc()); 15994 Invalid = true; 15995 } 15996 15997 IdentifierInfo *II = D.getIdentifier(); 15998 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 15999 LookupOrdinaryName, 16000 ForVisibleRedeclaration)) { 16001 // The scope should be freshly made just for us. There is just no way 16002 // it contains any previous declaration, except for function parameters in 16003 // a function-try-block's catch statement. 16004 assert(!S->isDeclScope(PrevDecl)); 16005 if (isDeclInScope(PrevDecl, CurContext, S)) { 16006 Diag(D.getIdentifierLoc(), diag::err_redefinition) 16007 << D.getIdentifier(); 16008 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 16009 Invalid = true; 16010 } else if (PrevDecl->isTemplateParameter()) 16011 // Maybe we will complain about the shadowed template parameter. 16012 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16013 } 16014 16015 if (D.getCXXScopeSpec().isSet() && !Invalid) { 16016 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 16017 << D.getCXXScopeSpec().getRange(); 16018 Invalid = true; 16019 } 16020 16021 VarDecl *ExDecl = BuildExceptionDeclaration( 16022 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 16023 if (Invalid) 16024 ExDecl->setInvalidDecl(); 16025 16026 // Add the exception declaration into this scope. 16027 if (II) 16028 PushOnScopeChains(ExDecl, S); 16029 else 16030 CurContext->addDecl(ExDecl); 16031 16032 ProcessDeclAttributes(S, ExDecl, D); 16033 return ExDecl; 16034 } 16035 16036 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16037 Expr *AssertExpr, 16038 Expr *AssertMessageExpr, 16039 SourceLocation RParenLoc) { 16040 StringLiteral *AssertMessage = 16041 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 16042 16043 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 16044 return nullptr; 16045 16046 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 16047 AssertMessage, RParenLoc, false); 16048 } 16049 16050 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16051 Expr *AssertExpr, 16052 StringLiteral *AssertMessage, 16053 SourceLocation RParenLoc, 16054 bool Failed) { 16055 assert(AssertExpr != nullptr && "Expected non-null condition"); 16056 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 16057 !Failed) { 16058 // In a static_assert-declaration, the constant-expression shall be a 16059 // constant expression that can be contextually converted to bool. 16060 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 16061 if (Converted.isInvalid()) 16062 Failed = true; 16063 16064 ExprResult FullAssertExpr = 16065 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 16066 /*DiscardedValue*/ false, 16067 /*IsConstexpr*/ true); 16068 if (FullAssertExpr.isInvalid()) 16069 Failed = true; 16070 else 16071 AssertExpr = FullAssertExpr.get(); 16072 16073 llvm::APSInt Cond; 16074 if (!Failed && VerifyIntegerConstantExpression( 16075 AssertExpr, &Cond, 16076 diag::err_static_assert_expression_is_not_constant) 16077 .isInvalid()) 16078 Failed = true; 16079 16080 if (!Failed && !Cond) { 16081 SmallString<256> MsgBuffer; 16082 llvm::raw_svector_ostream Msg(MsgBuffer); 16083 if (AssertMessage) 16084 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 16085 16086 Expr *InnerCond = nullptr; 16087 std::string InnerCondDescription; 16088 std::tie(InnerCond, InnerCondDescription) = 16089 findFailedBooleanCondition(Converted.get()); 16090 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 16091 // Drill down into concept specialization expressions to see why they 16092 // weren't satisfied. 16093 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16094 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16095 ConstraintSatisfaction Satisfaction; 16096 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 16097 DiagnoseUnsatisfiedConstraint(Satisfaction); 16098 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 16099 && !isa<IntegerLiteral>(InnerCond)) { 16100 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 16101 << InnerCondDescription << !AssertMessage 16102 << Msg.str() << InnerCond->getSourceRange(); 16103 } else { 16104 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16105 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16106 } 16107 Failed = true; 16108 } 16109 } else { 16110 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 16111 /*DiscardedValue*/false, 16112 /*IsConstexpr*/true); 16113 if (FullAssertExpr.isInvalid()) 16114 Failed = true; 16115 else 16116 AssertExpr = FullAssertExpr.get(); 16117 } 16118 16119 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 16120 AssertExpr, AssertMessage, RParenLoc, 16121 Failed); 16122 16123 CurContext->addDecl(Decl); 16124 return Decl; 16125 } 16126 16127 /// Perform semantic analysis of the given friend type declaration. 16128 /// 16129 /// \returns A friend declaration that. 16130 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 16131 SourceLocation FriendLoc, 16132 TypeSourceInfo *TSInfo) { 16133 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 16134 16135 QualType T = TSInfo->getType(); 16136 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 16137 16138 // C++03 [class.friend]p2: 16139 // An elaborated-type-specifier shall be used in a friend declaration 16140 // for a class.* 16141 // 16142 // * The class-key of the elaborated-type-specifier is required. 16143 if (!CodeSynthesisContexts.empty()) { 16144 // Do not complain about the form of friend template types during any kind 16145 // of code synthesis. For template instantiation, we will have complained 16146 // when the template was defined. 16147 } else { 16148 if (!T->isElaboratedTypeSpecifier()) { 16149 // If we evaluated the type to a record type, suggest putting 16150 // a tag in front. 16151 if (const RecordType *RT = T->getAs<RecordType>()) { 16152 RecordDecl *RD = RT->getDecl(); 16153 16154 SmallString<16> InsertionText(" "); 16155 InsertionText += RD->getKindName(); 16156 16157 Diag(TypeRange.getBegin(), 16158 getLangOpts().CPlusPlus11 ? 16159 diag::warn_cxx98_compat_unelaborated_friend_type : 16160 diag::ext_unelaborated_friend_type) 16161 << (unsigned) RD->getTagKind() 16162 << T 16163 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 16164 InsertionText); 16165 } else { 16166 Diag(FriendLoc, 16167 getLangOpts().CPlusPlus11 ? 16168 diag::warn_cxx98_compat_nonclass_type_friend : 16169 diag::ext_nonclass_type_friend) 16170 << T 16171 << TypeRange; 16172 } 16173 } else if (T->getAs<EnumType>()) { 16174 Diag(FriendLoc, 16175 getLangOpts().CPlusPlus11 ? 16176 diag::warn_cxx98_compat_enum_friend : 16177 diag::ext_enum_friend) 16178 << T 16179 << TypeRange; 16180 } 16181 16182 // C++11 [class.friend]p3: 16183 // A friend declaration that does not declare a function shall have one 16184 // of the following forms: 16185 // friend elaborated-type-specifier ; 16186 // friend simple-type-specifier ; 16187 // friend typename-specifier ; 16188 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 16189 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 16190 } 16191 16192 // If the type specifier in a friend declaration designates a (possibly 16193 // cv-qualified) class type, that class is declared as a friend; otherwise, 16194 // the friend declaration is ignored. 16195 return FriendDecl::Create(Context, CurContext, 16196 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 16197 FriendLoc); 16198 } 16199 16200 /// Handle a friend tag declaration where the scope specifier was 16201 /// templated. 16202 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 16203 unsigned TagSpec, SourceLocation TagLoc, 16204 CXXScopeSpec &SS, IdentifierInfo *Name, 16205 SourceLocation NameLoc, 16206 const ParsedAttributesView &Attr, 16207 MultiTemplateParamsArg TempParamLists) { 16208 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16209 16210 bool IsMemberSpecialization = false; 16211 bool Invalid = false; 16212 16213 if (TemplateParameterList *TemplateParams = 16214 MatchTemplateParametersToScopeSpecifier( 16215 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 16216 IsMemberSpecialization, Invalid)) { 16217 if (TemplateParams->size() > 0) { 16218 // This is a declaration of a class template. 16219 if (Invalid) 16220 return nullptr; 16221 16222 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 16223 NameLoc, Attr, TemplateParams, AS_public, 16224 /*ModulePrivateLoc=*/SourceLocation(), 16225 FriendLoc, TempParamLists.size() - 1, 16226 TempParamLists.data()).get(); 16227 } else { 16228 // The "template<>" header is extraneous. 16229 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16230 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16231 IsMemberSpecialization = true; 16232 } 16233 } 16234 16235 if (Invalid) return nullptr; 16236 16237 bool isAllExplicitSpecializations = true; 16238 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 16239 if (TempParamLists[I]->size()) { 16240 isAllExplicitSpecializations = false; 16241 break; 16242 } 16243 } 16244 16245 // FIXME: don't ignore attributes. 16246 16247 // If it's explicit specializations all the way down, just forget 16248 // about the template header and build an appropriate non-templated 16249 // friend. TODO: for source fidelity, remember the headers. 16250 if (isAllExplicitSpecializations) { 16251 if (SS.isEmpty()) { 16252 bool Owned = false; 16253 bool IsDependent = false; 16254 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 16255 Attr, AS_public, 16256 /*ModulePrivateLoc=*/SourceLocation(), 16257 MultiTemplateParamsArg(), Owned, IsDependent, 16258 /*ScopedEnumKWLoc=*/SourceLocation(), 16259 /*ScopedEnumUsesClassTag=*/false, 16260 /*UnderlyingType=*/TypeResult(), 16261 /*IsTypeSpecifier=*/false, 16262 /*IsTemplateParamOrArg=*/false); 16263 } 16264 16265 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 16266 ElaboratedTypeKeyword Keyword 16267 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16268 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 16269 *Name, NameLoc); 16270 if (T.isNull()) 16271 return nullptr; 16272 16273 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16274 if (isa<DependentNameType>(T)) { 16275 DependentNameTypeLoc TL = 16276 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16277 TL.setElaboratedKeywordLoc(TagLoc); 16278 TL.setQualifierLoc(QualifierLoc); 16279 TL.setNameLoc(NameLoc); 16280 } else { 16281 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 16282 TL.setElaboratedKeywordLoc(TagLoc); 16283 TL.setQualifierLoc(QualifierLoc); 16284 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 16285 } 16286 16287 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16288 TSI, FriendLoc, TempParamLists); 16289 Friend->setAccess(AS_public); 16290 CurContext->addDecl(Friend); 16291 return Friend; 16292 } 16293 16294 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 16295 16296 16297 16298 // Handle the case of a templated-scope friend class. e.g. 16299 // template <class T> class A<T>::B; 16300 // FIXME: we don't support these right now. 16301 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 16302 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 16303 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16304 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 16305 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16306 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16307 TL.setElaboratedKeywordLoc(TagLoc); 16308 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 16309 TL.setNameLoc(NameLoc); 16310 16311 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16312 TSI, FriendLoc, TempParamLists); 16313 Friend->setAccess(AS_public); 16314 Friend->setUnsupportedFriend(true); 16315 CurContext->addDecl(Friend); 16316 return Friend; 16317 } 16318 16319 /// Handle a friend type declaration. This works in tandem with 16320 /// ActOnTag. 16321 /// 16322 /// Notes on friend class templates: 16323 /// 16324 /// We generally treat friend class declarations as if they were 16325 /// declaring a class. So, for example, the elaborated type specifier 16326 /// in a friend declaration is required to obey the restrictions of a 16327 /// class-head (i.e. no typedefs in the scope chain), template 16328 /// parameters are required to match up with simple template-ids, &c. 16329 /// However, unlike when declaring a template specialization, it's 16330 /// okay to refer to a template specialization without an empty 16331 /// template parameter declaration, e.g. 16332 /// friend class A<T>::B<unsigned>; 16333 /// We permit this as a special case; if there are any template 16334 /// parameters present at all, require proper matching, i.e. 16335 /// template <> template \<class T> friend class A<int>::B; 16336 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 16337 MultiTemplateParamsArg TempParams) { 16338 SourceLocation Loc = DS.getBeginLoc(); 16339 16340 assert(DS.isFriendSpecified()); 16341 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16342 16343 // C++ [class.friend]p3: 16344 // A friend declaration that does not declare a function shall have one of 16345 // the following forms: 16346 // friend elaborated-type-specifier ; 16347 // friend simple-type-specifier ; 16348 // friend typename-specifier ; 16349 // 16350 // Any declaration with a type qualifier does not have that form. (It's 16351 // legal to specify a qualified type as a friend, you just can't write the 16352 // keywords.) 16353 if (DS.getTypeQualifiers()) { 16354 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 16355 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 16356 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 16357 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 16358 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 16359 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 16360 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 16361 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 16362 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 16363 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 16364 } 16365 16366 // Try to convert the decl specifier to a type. This works for 16367 // friend templates because ActOnTag never produces a ClassTemplateDecl 16368 // for a TUK_Friend. 16369 Declarator TheDeclarator(DS, DeclaratorContext::Member); 16370 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 16371 QualType T = TSI->getType(); 16372 if (TheDeclarator.isInvalidType()) 16373 return nullptr; 16374 16375 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 16376 return nullptr; 16377 16378 // This is definitely an error in C++98. It's probably meant to 16379 // be forbidden in C++0x, too, but the specification is just 16380 // poorly written. 16381 // 16382 // The problem is with declarations like the following: 16383 // template <T> friend A<T>::foo; 16384 // where deciding whether a class C is a friend or not now hinges 16385 // on whether there exists an instantiation of A that causes 16386 // 'foo' to equal C. There are restrictions on class-heads 16387 // (which we declare (by fiat) elaborated friend declarations to 16388 // be) that makes this tractable. 16389 // 16390 // FIXME: handle "template <> friend class A<T>;", which 16391 // is possibly well-formed? Who even knows? 16392 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 16393 Diag(Loc, diag::err_tagless_friend_type_template) 16394 << DS.getSourceRange(); 16395 return nullptr; 16396 } 16397 16398 // C++98 [class.friend]p1: A friend of a class is a function 16399 // or class that is not a member of the class . . . 16400 // This is fixed in DR77, which just barely didn't make the C++03 16401 // deadline. It's also a very silly restriction that seriously 16402 // affects inner classes and which nobody else seems to implement; 16403 // thus we never diagnose it, not even in -pedantic. 16404 // 16405 // But note that we could warn about it: it's always useless to 16406 // friend one of your own members (it's not, however, worthless to 16407 // friend a member of an arbitrary specialization of your template). 16408 16409 Decl *D; 16410 if (!TempParams.empty()) 16411 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 16412 TempParams, 16413 TSI, 16414 DS.getFriendSpecLoc()); 16415 else 16416 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 16417 16418 if (!D) 16419 return nullptr; 16420 16421 D->setAccess(AS_public); 16422 CurContext->addDecl(D); 16423 16424 return D; 16425 } 16426 16427 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 16428 MultiTemplateParamsArg TemplateParams) { 16429 const DeclSpec &DS = D.getDeclSpec(); 16430 16431 assert(DS.isFriendSpecified()); 16432 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16433 16434 SourceLocation Loc = D.getIdentifierLoc(); 16435 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16436 16437 // C++ [class.friend]p1 16438 // A friend of a class is a function or class.... 16439 // Note that this sees through typedefs, which is intended. 16440 // It *doesn't* see through dependent types, which is correct 16441 // according to [temp.arg.type]p3: 16442 // If a declaration acquires a function type through a 16443 // type dependent on a template-parameter and this causes 16444 // a declaration that does not use the syntactic form of a 16445 // function declarator to have a function type, the program 16446 // is ill-formed. 16447 if (!TInfo->getType()->isFunctionType()) { 16448 Diag(Loc, diag::err_unexpected_friend); 16449 16450 // It might be worthwhile to try to recover by creating an 16451 // appropriate declaration. 16452 return nullptr; 16453 } 16454 16455 // C++ [namespace.memdef]p3 16456 // - If a friend declaration in a non-local class first declares a 16457 // class or function, the friend class or function is a member 16458 // of the innermost enclosing namespace. 16459 // - The name of the friend is not found by simple name lookup 16460 // until a matching declaration is provided in that namespace 16461 // scope (either before or after the class declaration granting 16462 // friendship). 16463 // - If a friend function is called, its name may be found by the 16464 // name lookup that considers functions from namespaces and 16465 // classes associated with the types of the function arguments. 16466 // - When looking for a prior declaration of a class or a function 16467 // declared as a friend, scopes outside the innermost enclosing 16468 // namespace scope are not considered. 16469 16470 CXXScopeSpec &SS = D.getCXXScopeSpec(); 16471 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 16472 assert(NameInfo.getName()); 16473 16474 // Check for unexpanded parameter packs. 16475 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 16476 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 16477 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 16478 return nullptr; 16479 16480 // The context we found the declaration in, or in which we should 16481 // create the declaration. 16482 DeclContext *DC; 16483 Scope *DCScope = S; 16484 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 16485 ForExternalRedeclaration); 16486 16487 // There are five cases here. 16488 // - There's no scope specifier and we're in a local class. Only look 16489 // for functions declared in the immediately-enclosing block scope. 16490 // We recover from invalid scope qualifiers as if they just weren't there. 16491 FunctionDecl *FunctionContainingLocalClass = nullptr; 16492 if ((SS.isInvalid() || !SS.isSet()) && 16493 (FunctionContainingLocalClass = 16494 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 16495 // C++11 [class.friend]p11: 16496 // If a friend declaration appears in a local class and the name 16497 // specified is an unqualified name, a prior declaration is 16498 // looked up without considering scopes that are outside the 16499 // innermost enclosing non-class scope. For a friend function 16500 // declaration, if there is no prior declaration, the program is 16501 // ill-formed. 16502 16503 // Find the innermost enclosing non-class scope. This is the block 16504 // scope containing the local class definition (or for a nested class, 16505 // the outer local class). 16506 DCScope = S->getFnParent(); 16507 16508 // Look up the function name in the scope. 16509 Previous.clear(LookupLocalFriendName); 16510 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 16511 16512 if (!Previous.empty()) { 16513 // All possible previous declarations must have the same context: 16514 // either they were declared at block scope or they are members of 16515 // one of the enclosing local classes. 16516 DC = Previous.getRepresentativeDecl()->getDeclContext(); 16517 } else { 16518 // This is ill-formed, but provide the context that we would have 16519 // declared the function in, if we were permitted to, for error recovery. 16520 DC = FunctionContainingLocalClass; 16521 } 16522 adjustContextForLocalExternDecl(DC); 16523 16524 // C++ [class.friend]p6: 16525 // A function can be defined in a friend declaration of a class if and 16526 // only if the class is a non-local class (9.8), the function name is 16527 // unqualified, and the function has namespace scope. 16528 if (D.isFunctionDefinition()) { 16529 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 16530 } 16531 16532 // - There's no scope specifier, in which case we just go to the 16533 // appropriate scope and look for a function or function template 16534 // there as appropriate. 16535 } else if (SS.isInvalid() || !SS.isSet()) { 16536 // C++11 [namespace.memdef]p3: 16537 // If the name in a friend declaration is neither qualified nor 16538 // a template-id and the declaration is a function or an 16539 // elaborated-type-specifier, the lookup to determine whether 16540 // the entity has been previously declared shall not consider 16541 // any scopes outside the innermost enclosing namespace. 16542 bool isTemplateId = 16543 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 16544 16545 // Find the appropriate context according to the above. 16546 DC = CurContext; 16547 16548 // Skip class contexts. If someone can cite chapter and verse 16549 // for this behavior, that would be nice --- it's what GCC and 16550 // EDG do, and it seems like a reasonable intent, but the spec 16551 // really only says that checks for unqualified existing 16552 // declarations should stop at the nearest enclosing namespace, 16553 // not that they should only consider the nearest enclosing 16554 // namespace. 16555 while (DC->isRecord()) 16556 DC = DC->getParent(); 16557 16558 DeclContext *LookupDC = DC; 16559 while (LookupDC->isTransparentContext()) 16560 LookupDC = LookupDC->getParent(); 16561 16562 while (true) { 16563 LookupQualifiedName(Previous, LookupDC); 16564 16565 if (!Previous.empty()) { 16566 DC = LookupDC; 16567 break; 16568 } 16569 16570 if (isTemplateId) { 16571 if (isa<TranslationUnitDecl>(LookupDC)) break; 16572 } else { 16573 if (LookupDC->isFileContext()) break; 16574 } 16575 LookupDC = LookupDC->getParent(); 16576 } 16577 16578 DCScope = getScopeForDeclContext(S, DC); 16579 16580 // - There's a non-dependent scope specifier, in which case we 16581 // compute it and do a previous lookup there for a function 16582 // or function template. 16583 } else if (!SS.getScopeRep()->isDependent()) { 16584 DC = computeDeclContext(SS); 16585 if (!DC) return nullptr; 16586 16587 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 16588 16589 LookupQualifiedName(Previous, DC); 16590 16591 // C++ [class.friend]p1: A friend of a class is a function or 16592 // class that is not a member of the class . . . 16593 if (DC->Equals(CurContext)) 16594 Diag(DS.getFriendSpecLoc(), 16595 getLangOpts().CPlusPlus11 ? 16596 diag::warn_cxx98_compat_friend_is_member : 16597 diag::err_friend_is_member); 16598 16599 if (D.isFunctionDefinition()) { 16600 // C++ [class.friend]p6: 16601 // A function can be defined in a friend declaration of a class if and 16602 // only if the class is a non-local class (9.8), the function name is 16603 // unqualified, and the function has namespace scope. 16604 // 16605 // FIXME: We should only do this if the scope specifier names the 16606 // innermost enclosing namespace; otherwise the fixit changes the 16607 // meaning of the code. 16608 SemaDiagnosticBuilder DB 16609 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 16610 16611 DB << SS.getScopeRep(); 16612 if (DC->isFileContext()) 16613 DB << FixItHint::CreateRemoval(SS.getRange()); 16614 SS.clear(); 16615 } 16616 16617 // - There's a scope specifier that does not match any template 16618 // parameter lists, in which case we use some arbitrary context, 16619 // create a method or method template, and wait for instantiation. 16620 // - There's a scope specifier that does match some template 16621 // parameter lists, which we don't handle right now. 16622 } else { 16623 if (D.isFunctionDefinition()) { 16624 // C++ [class.friend]p6: 16625 // A function can be defined in a friend declaration of a class if and 16626 // only if the class is a non-local class (9.8), the function name is 16627 // unqualified, and the function has namespace scope. 16628 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 16629 << SS.getScopeRep(); 16630 } 16631 16632 DC = CurContext; 16633 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 16634 } 16635 16636 if (!DC->isRecord()) { 16637 int DiagArg = -1; 16638 switch (D.getName().getKind()) { 16639 case UnqualifiedIdKind::IK_ConstructorTemplateId: 16640 case UnqualifiedIdKind::IK_ConstructorName: 16641 DiagArg = 0; 16642 break; 16643 case UnqualifiedIdKind::IK_DestructorName: 16644 DiagArg = 1; 16645 break; 16646 case UnqualifiedIdKind::IK_ConversionFunctionId: 16647 DiagArg = 2; 16648 break; 16649 case UnqualifiedIdKind::IK_DeductionGuideName: 16650 DiagArg = 3; 16651 break; 16652 case UnqualifiedIdKind::IK_Identifier: 16653 case UnqualifiedIdKind::IK_ImplicitSelfParam: 16654 case UnqualifiedIdKind::IK_LiteralOperatorId: 16655 case UnqualifiedIdKind::IK_OperatorFunctionId: 16656 case UnqualifiedIdKind::IK_TemplateId: 16657 break; 16658 } 16659 // This implies that it has to be an operator or function. 16660 if (DiagArg >= 0) { 16661 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 16662 return nullptr; 16663 } 16664 } 16665 16666 // FIXME: This is an egregious hack to cope with cases where the scope stack 16667 // does not contain the declaration context, i.e., in an out-of-line 16668 // definition of a class. 16669 Scope FakeDCScope(S, Scope::DeclScope, Diags); 16670 if (!DCScope) { 16671 FakeDCScope.setEntity(DC); 16672 DCScope = &FakeDCScope; 16673 } 16674 16675 bool AddToScope = true; 16676 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 16677 TemplateParams, AddToScope); 16678 if (!ND) return nullptr; 16679 16680 assert(ND->getLexicalDeclContext() == CurContext); 16681 16682 // If we performed typo correction, we might have added a scope specifier 16683 // and changed the decl context. 16684 DC = ND->getDeclContext(); 16685 16686 // Add the function declaration to the appropriate lookup tables, 16687 // adjusting the redeclarations list as necessary. We don't 16688 // want to do this yet if the friending class is dependent. 16689 // 16690 // Also update the scope-based lookup if the target context's 16691 // lookup context is in lexical scope. 16692 if (!CurContext->isDependentContext()) { 16693 DC = DC->getRedeclContext(); 16694 DC->makeDeclVisibleInContext(ND); 16695 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16696 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 16697 } 16698 16699 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 16700 D.getIdentifierLoc(), ND, 16701 DS.getFriendSpecLoc()); 16702 FrD->setAccess(AS_public); 16703 CurContext->addDecl(FrD); 16704 16705 if (ND->isInvalidDecl()) { 16706 FrD->setInvalidDecl(); 16707 } else { 16708 if (DC->isRecord()) CheckFriendAccess(ND); 16709 16710 FunctionDecl *FD; 16711 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 16712 FD = FTD->getTemplatedDecl(); 16713 else 16714 FD = cast<FunctionDecl>(ND); 16715 16716 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 16717 // default argument expression, that declaration shall be a definition 16718 // and shall be the only declaration of the function or function 16719 // template in the translation unit. 16720 if (functionDeclHasDefaultArgument(FD)) { 16721 // We can't look at FD->getPreviousDecl() because it may not have been set 16722 // if we're in a dependent context. If the function is known to be a 16723 // redeclaration, we will have narrowed Previous down to the right decl. 16724 if (D.isRedeclaration()) { 16725 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 16726 Diag(Previous.getRepresentativeDecl()->getLocation(), 16727 diag::note_previous_declaration); 16728 } else if (!D.isFunctionDefinition()) 16729 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 16730 } 16731 16732 // Mark templated-scope function declarations as unsupported. 16733 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 16734 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 16735 << SS.getScopeRep() << SS.getRange() 16736 << cast<CXXRecordDecl>(CurContext); 16737 FrD->setUnsupportedFriend(true); 16738 } 16739 } 16740 16741 return ND; 16742 } 16743 16744 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 16745 AdjustDeclIfTemplate(Dcl); 16746 16747 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 16748 if (!Fn) { 16749 Diag(DelLoc, diag::err_deleted_non_function); 16750 return; 16751 } 16752 16753 // Deleted function does not have a body. 16754 Fn->setWillHaveBody(false); 16755 16756 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 16757 // Don't consider the implicit declaration we generate for explicit 16758 // specializations. FIXME: Do not generate these implicit declarations. 16759 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 16760 Prev->getPreviousDecl()) && 16761 !Prev->isDefined()) { 16762 Diag(DelLoc, diag::err_deleted_decl_not_first); 16763 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 16764 Prev->isImplicit() ? diag::note_previous_implicit_declaration 16765 : diag::note_previous_declaration); 16766 // We can't recover from this; the declaration might have already 16767 // been used. 16768 Fn->setInvalidDecl(); 16769 return; 16770 } 16771 16772 // To maintain the invariant that functions are only deleted on their first 16773 // declaration, mark the implicitly-instantiated declaration of the 16774 // explicitly-specialized function as deleted instead of marking the 16775 // instantiated redeclaration. 16776 Fn = Fn->getCanonicalDecl(); 16777 } 16778 16779 // dllimport/dllexport cannot be deleted. 16780 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 16781 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 16782 Fn->setInvalidDecl(); 16783 } 16784 16785 // C++11 [basic.start.main]p3: 16786 // A program that defines main as deleted [...] is ill-formed. 16787 if (Fn->isMain()) 16788 Diag(DelLoc, diag::err_deleted_main); 16789 16790 // C++11 [dcl.fct.def.delete]p4: 16791 // A deleted function is implicitly inline. 16792 Fn->setImplicitlyInline(); 16793 Fn->setDeletedAsWritten(); 16794 } 16795 16796 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 16797 if (!Dcl || Dcl->isInvalidDecl()) 16798 return; 16799 16800 auto *FD = dyn_cast<FunctionDecl>(Dcl); 16801 if (!FD) { 16802 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 16803 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 16804 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 16805 return; 16806 } 16807 } 16808 16809 Diag(DefaultLoc, diag::err_default_special_members) 16810 << getLangOpts().CPlusPlus20; 16811 return; 16812 } 16813 16814 // Reject if this can't possibly be a defaultable function. 16815 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 16816 if (!DefKind && 16817 // A dependent function that doesn't locally look defaultable can 16818 // still instantiate to a defaultable function if it's a constructor 16819 // or assignment operator. 16820 (!FD->isDependentContext() || 16821 (!isa<CXXConstructorDecl>(FD) && 16822 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 16823 Diag(DefaultLoc, diag::err_default_special_members) 16824 << getLangOpts().CPlusPlus20; 16825 return; 16826 } 16827 16828 if (DefKind.isComparison() && 16829 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 16830 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class) 16831 << (int)DefKind.asComparison(); 16832 return; 16833 } 16834 16835 // Issue compatibility warning. We already warned if the operator is 16836 // 'operator<=>' when parsing the '<=>' token. 16837 if (DefKind.isComparison() && 16838 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 16839 Diag(DefaultLoc, getLangOpts().CPlusPlus20 16840 ? diag::warn_cxx17_compat_defaulted_comparison 16841 : diag::ext_defaulted_comparison); 16842 } 16843 16844 FD->setDefaulted(); 16845 FD->setExplicitlyDefaulted(); 16846 16847 // Defer checking functions that are defaulted in a dependent context. 16848 if (FD->isDependentContext()) 16849 return; 16850 16851 // Unset that we will have a body for this function. We might not, 16852 // if it turns out to be trivial, and we don't need this marking now 16853 // that we've marked it as defaulted. 16854 FD->setWillHaveBody(false); 16855 16856 // If this definition appears within the record, do the checking when 16857 // the record is complete. This is always the case for a defaulted 16858 // comparison. 16859 if (DefKind.isComparison()) 16860 return; 16861 auto *MD = cast<CXXMethodDecl>(FD); 16862 16863 const FunctionDecl *Primary = FD; 16864 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 16865 // Ask the template instantiation pattern that actually had the 16866 // '= default' on it. 16867 Primary = Pattern; 16868 16869 // If the method was defaulted on its first declaration, we will have 16870 // already performed the checking in CheckCompletedCXXClass. Such a 16871 // declaration doesn't trigger an implicit definition. 16872 if (Primary->getCanonicalDecl()->isDefaulted()) 16873 return; 16874 16875 // FIXME: Once we support defining comparisons out of class, check for a 16876 // defaulted comparison here. 16877 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 16878 MD->setInvalidDecl(); 16879 else 16880 DefineDefaultedFunction(*this, MD, DefaultLoc); 16881 } 16882 16883 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 16884 for (Stmt *SubStmt : S->children()) { 16885 if (!SubStmt) 16886 continue; 16887 if (isa<ReturnStmt>(SubStmt)) 16888 Self.Diag(SubStmt->getBeginLoc(), 16889 diag::err_return_in_constructor_handler); 16890 if (!isa<Expr>(SubStmt)) 16891 SearchForReturnInStmt(Self, SubStmt); 16892 } 16893 } 16894 16895 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 16896 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 16897 CXXCatchStmt *Handler = TryBlock->getHandler(I); 16898 SearchForReturnInStmt(*this, Handler); 16899 } 16900 } 16901 16902 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 16903 const CXXMethodDecl *Old) { 16904 const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); 16905 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); 16906 16907 if (OldFT->hasExtParameterInfos()) { 16908 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 16909 // A parameter of the overriding method should be annotated with noescape 16910 // if the corresponding parameter of the overridden method is annotated. 16911 if (OldFT->getExtParameterInfo(I).isNoEscape() && 16912 !NewFT->getExtParameterInfo(I).isNoEscape()) { 16913 Diag(New->getParamDecl(I)->getLocation(), 16914 diag::warn_overriding_method_missing_noescape); 16915 Diag(Old->getParamDecl(I)->getLocation(), 16916 diag::note_overridden_marked_noescape); 16917 } 16918 } 16919 16920 // Virtual overrides must have the same code_seg. 16921 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 16922 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 16923 if ((NewCSA || OldCSA) && 16924 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 16925 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 16926 Diag(Old->getLocation(), diag::note_previous_declaration); 16927 return true; 16928 } 16929 16930 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 16931 16932 // If the calling conventions match, everything is fine 16933 if (NewCC == OldCC) 16934 return false; 16935 16936 // If the calling conventions mismatch because the new function is static, 16937 // suppress the calling convention mismatch error; the error about static 16938 // function override (err_static_overrides_virtual from 16939 // Sema::CheckFunctionDeclaration) is more clear. 16940 if (New->getStorageClass() == SC_Static) 16941 return false; 16942 16943 Diag(New->getLocation(), 16944 diag::err_conflicting_overriding_cc_attributes) 16945 << New->getDeclName() << New->getType() << Old->getType(); 16946 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 16947 return true; 16948 } 16949 16950 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 16951 const CXXMethodDecl *Old) { 16952 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); 16953 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); 16954 16955 if (Context.hasSameType(NewTy, OldTy) || 16956 NewTy->isDependentType() || OldTy->isDependentType()) 16957 return false; 16958 16959 // Check if the return types are covariant 16960 QualType NewClassTy, OldClassTy; 16961 16962 /// Both types must be pointers or references to classes. 16963 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 16964 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 16965 NewClassTy = NewPT->getPointeeType(); 16966 OldClassTy = OldPT->getPointeeType(); 16967 } 16968 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 16969 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 16970 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 16971 NewClassTy = NewRT->getPointeeType(); 16972 OldClassTy = OldRT->getPointeeType(); 16973 } 16974 } 16975 } 16976 16977 // The return types aren't either both pointers or references to a class type. 16978 if (NewClassTy.isNull()) { 16979 Diag(New->getLocation(), 16980 diag::err_different_return_type_for_overriding_virtual_function) 16981 << New->getDeclName() << NewTy << OldTy 16982 << New->getReturnTypeSourceRange(); 16983 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16984 << Old->getReturnTypeSourceRange(); 16985 16986 return true; 16987 } 16988 16989 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 16990 // C++14 [class.virtual]p8: 16991 // If the class type in the covariant return type of D::f differs from 16992 // that of B::f, the class type in the return type of D::f shall be 16993 // complete at the point of declaration of D::f or shall be the class 16994 // type D. 16995 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 16996 if (!RT->isBeingDefined() && 16997 RequireCompleteType(New->getLocation(), NewClassTy, 16998 diag::err_covariant_return_incomplete, 16999 New->getDeclName())) 17000 return true; 17001 } 17002 17003 // Check if the new class derives from the old class. 17004 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 17005 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 17006 << New->getDeclName() << NewTy << OldTy 17007 << New->getReturnTypeSourceRange(); 17008 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17009 << Old->getReturnTypeSourceRange(); 17010 return true; 17011 } 17012 17013 // Check if we the conversion from derived to base is valid. 17014 if (CheckDerivedToBaseConversion( 17015 NewClassTy, OldClassTy, 17016 diag::err_covariant_return_inaccessible_base, 17017 diag::err_covariant_return_ambiguous_derived_to_base_conv, 17018 New->getLocation(), New->getReturnTypeSourceRange(), 17019 New->getDeclName(), nullptr)) { 17020 // FIXME: this note won't trigger for delayed access control 17021 // diagnostics, and it's impossible to get an undelayed error 17022 // here from access control during the original parse because 17023 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 17024 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17025 << Old->getReturnTypeSourceRange(); 17026 return true; 17027 } 17028 } 17029 17030 // The qualifiers of the return types must be the same. 17031 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 17032 Diag(New->getLocation(), 17033 diag::err_covariant_return_type_different_qualifications) 17034 << New->getDeclName() << NewTy << OldTy 17035 << New->getReturnTypeSourceRange(); 17036 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17037 << Old->getReturnTypeSourceRange(); 17038 return true; 17039 } 17040 17041 17042 // The new class type must have the same or less qualifiers as the old type. 17043 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 17044 Diag(New->getLocation(), 17045 diag::err_covariant_return_type_class_type_more_qualified) 17046 << New->getDeclName() << NewTy << OldTy 17047 << New->getReturnTypeSourceRange(); 17048 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17049 << Old->getReturnTypeSourceRange(); 17050 return true; 17051 } 17052 17053 return false; 17054 } 17055 17056 /// Mark the given method pure. 17057 /// 17058 /// \param Method the method to be marked pure. 17059 /// 17060 /// \param InitRange the source range that covers the "0" initializer. 17061 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 17062 SourceLocation EndLoc = InitRange.getEnd(); 17063 if (EndLoc.isValid()) 17064 Method->setRangeEnd(EndLoc); 17065 17066 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 17067 Method->setPure(); 17068 return false; 17069 } 17070 17071 if (!Method->isInvalidDecl()) 17072 Diag(Method->getLocation(), diag::err_non_virtual_pure) 17073 << Method->getDeclName() << InitRange; 17074 return true; 17075 } 17076 17077 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 17078 if (D->getFriendObjectKind()) 17079 Diag(D->getLocation(), diag::err_pure_friend); 17080 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 17081 CheckPureMethod(M, ZeroLoc); 17082 else 17083 Diag(D->getLocation(), diag::err_illegal_initializer); 17084 } 17085 17086 /// Determine whether the given declaration is a global variable or 17087 /// static data member. 17088 static bool isNonlocalVariable(const Decl *D) { 17089 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 17090 return Var->hasGlobalStorage(); 17091 17092 return false; 17093 } 17094 17095 /// Invoked when we are about to parse an initializer for the declaration 17096 /// 'Dcl'. 17097 /// 17098 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 17099 /// static data member of class X, names should be looked up in the scope of 17100 /// class X. If the declaration had a scope specifier, a scope will have 17101 /// been created and passed in for this purpose. Otherwise, S will be null. 17102 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 17103 // If there is no declaration, there was an error parsing it. 17104 if (!D || D->isInvalidDecl()) 17105 return; 17106 17107 // We will always have a nested name specifier here, but this declaration 17108 // might not be out of line if the specifier names the current namespace: 17109 // extern int n; 17110 // int ::n = 0; 17111 if (S && D->isOutOfLine()) 17112 EnterDeclaratorContext(S, D->getDeclContext()); 17113 17114 // If we are parsing the initializer for a static data member, push a 17115 // new expression evaluation context that is associated with this static 17116 // data member. 17117 if (isNonlocalVariable(D)) 17118 PushExpressionEvaluationContext( 17119 ExpressionEvaluationContext::PotentiallyEvaluated, D); 17120 } 17121 17122 /// Invoked after we are finished parsing an initializer for the declaration D. 17123 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 17124 // If there is no declaration, there was an error parsing it. 17125 if (!D || D->isInvalidDecl()) 17126 return; 17127 17128 if (isNonlocalVariable(D)) 17129 PopExpressionEvaluationContext(); 17130 17131 if (S && D->isOutOfLine()) 17132 ExitDeclaratorContext(S); 17133 } 17134 17135 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 17136 /// C++ if/switch/while/for statement. 17137 /// e.g: "if (int x = f()) {...}" 17138 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 17139 // C++ 6.4p2: 17140 // The declarator shall not specify a function or an array. 17141 // The type-specifier-seq shall not contain typedef and shall not declare a 17142 // new class or enumeration. 17143 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 17144 "Parser allowed 'typedef' as storage class of condition decl."); 17145 17146 Decl *Dcl = ActOnDeclarator(S, D); 17147 if (!Dcl) 17148 return true; 17149 17150 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 17151 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 17152 << D.getSourceRange(); 17153 return true; 17154 } 17155 17156 return Dcl; 17157 } 17158 17159 void Sema::LoadExternalVTableUses() { 17160 if (!ExternalSource) 17161 return; 17162 17163 SmallVector<ExternalVTableUse, 4> VTables; 17164 ExternalSource->ReadUsedVTables(VTables); 17165 SmallVector<VTableUse, 4> NewUses; 17166 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 17167 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 17168 = VTablesUsed.find(VTables[I].Record); 17169 // Even if a definition wasn't required before, it may be required now. 17170 if (Pos != VTablesUsed.end()) { 17171 if (!Pos->second && VTables[I].DefinitionRequired) 17172 Pos->second = true; 17173 continue; 17174 } 17175 17176 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 17177 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 17178 } 17179 17180 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 17181 } 17182 17183 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 17184 bool DefinitionRequired) { 17185 // Ignore any vtable uses in unevaluated operands or for classes that do 17186 // not have a vtable. 17187 if (!Class->isDynamicClass() || Class->isDependentContext() || 17188 CurContext->isDependentContext() || isUnevaluatedContext()) 17189 return; 17190 // Do not mark as used if compiling for the device outside of the target 17191 // region. 17192 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 17193 !isInOpenMPDeclareTargetContext() && 17194 !isInOpenMPTargetExecutionDirective()) { 17195 if (!DefinitionRequired) 17196 MarkVirtualMembersReferenced(Loc, Class); 17197 return; 17198 } 17199 17200 // Try to insert this class into the map. 17201 LoadExternalVTableUses(); 17202 Class = Class->getCanonicalDecl(); 17203 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 17204 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 17205 if (!Pos.second) { 17206 // If we already had an entry, check to see if we are promoting this vtable 17207 // to require a definition. If so, we need to reappend to the VTableUses 17208 // list, since we may have already processed the first entry. 17209 if (DefinitionRequired && !Pos.first->second) { 17210 Pos.first->second = true; 17211 } else { 17212 // Otherwise, we can early exit. 17213 return; 17214 } 17215 } else { 17216 // The Microsoft ABI requires that we perform the destructor body 17217 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 17218 // the deleting destructor is emitted with the vtable, not with the 17219 // destructor definition as in the Itanium ABI. 17220 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17221 CXXDestructorDecl *DD = Class->getDestructor(); 17222 if (DD && DD->isVirtual() && !DD->isDeleted()) { 17223 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 17224 // If this is an out-of-line declaration, marking it referenced will 17225 // not do anything. Manually call CheckDestructor to look up operator 17226 // delete(). 17227 ContextRAII SavedContext(*this, DD); 17228 CheckDestructor(DD); 17229 } else { 17230 MarkFunctionReferenced(Loc, Class->getDestructor()); 17231 } 17232 } 17233 } 17234 } 17235 17236 // Local classes need to have their virtual members marked 17237 // immediately. For all other classes, we mark their virtual members 17238 // at the end of the translation unit. 17239 if (Class->isLocalClass()) 17240 MarkVirtualMembersReferenced(Loc, Class); 17241 else 17242 VTableUses.push_back(std::make_pair(Class, Loc)); 17243 } 17244 17245 bool Sema::DefineUsedVTables() { 17246 LoadExternalVTableUses(); 17247 if (VTableUses.empty()) 17248 return false; 17249 17250 // Note: The VTableUses vector could grow as a result of marking 17251 // the members of a class as "used", so we check the size each 17252 // time through the loop and prefer indices (which are stable) to 17253 // iterators (which are not). 17254 bool DefinedAnything = false; 17255 for (unsigned I = 0; I != VTableUses.size(); ++I) { 17256 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 17257 if (!Class) 17258 continue; 17259 TemplateSpecializationKind ClassTSK = 17260 Class->getTemplateSpecializationKind(); 17261 17262 SourceLocation Loc = VTableUses[I].second; 17263 17264 bool DefineVTable = true; 17265 17266 // If this class has a key function, but that key function is 17267 // defined in another translation unit, we don't need to emit the 17268 // vtable even though we're using it. 17269 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 17270 if (KeyFunction && !KeyFunction->hasBody()) { 17271 // The key function is in another translation unit. 17272 DefineVTable = false; 17273 TemplateSpecializationKind TSK = 17274 KeyFunction->getTemplateSpecializationKind(); 17275 assert(TSK != TSK_ExplicitInstantiationDefinition && 17276 TSK != TSK_ImplicitInstantiation && 17277 "Instantiations don't have key functions"); 17278 (void)TSK; 17279 } else if (!KeyFunction) { 17280 // If we have a class with no key function that is the subject 17281 // of an explicit instantiation declaration, suppress the 17282 // vtable; it will live with the explicit instantiation 17283 // definition. 17284 bool IsExplicitInstantiationDeclaration = 17285 ClassTSK == TSK_ExplicitInstantiationDeclaration; 17286 for (auto R : Class->redecls()) { 17287 TemplateSpecializationKind TSK 17288 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 17289 if (TSK == TSK_ExplicitInstantiationDeclaration) 17290 IsExplicitInstantiationDeclaration = true; 17291 else if (TSK == TSK_ExplicitInstantiationDefinition) { 17292 IsExplicitInstantiationDeclaration = false; 17293 break; 17294 } 17295 } 17296 17297 if (IsExplicitInstantiationDeclaration) 17298 DefineVTable = false; 17299 } 17300 17301 // The exception specifications for all virtual members may be needed even 17302 // if we are not providing an authoritative form of the vtable in this TU. 17303 // We may choose to emit it available_externally anyway. 17304 if (!DefineVTable) { 17305 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 17306 continue; 17307 } 17308 17309 // Mark all of the virtual members of this class as referenced, so 17310 // that we can build a vtable. Then, tell the AST consumer that a 17311 // vtable for this class is required. 17312 DefinedAnything = true; 17313 MarkVirtualMembersReferenced(Loc, Class); 17314 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 17315 if (VTablesUsed[Canonical]) 17316 Consumer.HandleVTable(Class); 17317 17318 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 17319 // no key function or the key function is inlined. Don't warn in C++ ABIs 17320 // that lack key functions, since the user won't be able to make one. 17321 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 17322 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 17323 const FunctionDecl *KeyFunctionDef = nullptr; 17324 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 17325 KeyFunctionDef->isInlined())) { 17326 Diag(Class->getLocation(), 17327 ClassTSK == TSK_ExplicitInstantiationDefinition 17328 ? diag::warn_weak_template_vtable 17329 : diag::warn_weak_vtable) 17330 << Class; 17331 } 17332 } 17333 } 17334 VTableUses.clear(); 17335 17336 return DefinedAnything; 17337 } 17338 17339 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 17340 const CXXRecordDecl *RD) { 17341 for (const auto *I : RD->methods()) 17342 if (I->isVirtual() && !I->isPure()) 17343 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 17344 } 17345 17346 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 17347 const CXXRecordDecl *RD, 17348 bool ConstexprOnly) { 17349 // Mark all functions which will appear in RD's vtable as used. 17350 CXXFinalOverriderMap FinalOverriders; 17351 RD->getFinalOverriders(FinalOverriders); 17352 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 17353 E = FinalOverriders.end(); 17354 I != E; ++I) { 17355 for (OverridingMethods::const_iterator OI = I->second.begin(), 17356 OE = I->second.end(); 17357 OI != OE; ++OI) { 17358 assert(OI->second.size() > 0 && "no final overrider"); 17359 CXXMethodDecl *Overrider = OI->second.front().Method; 17360 17361 // C++ [basic.def.odr]p2: 17362 // [...] A virtual member function is used if it is not pure. [...] 17363 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 17364 MarkFunctionReferenced(Loc, Overrider); 17365 } 17366 } 17367 17368 // Only classes that have virtual bases need a VTT. 17369 if (RD->getNumVBases() == 0) 17370 return; 17371 17372 for (const auto &I : RD->bases()) { 17373 const auto *Base = 17374 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 17375 if (Base->getNumVBases() == 0) 17376 continue; 17377 MarkVirtualMembersReferenced(Loc, Base); 17378 } 17379 } 17380 17381 /// SetIvarInitializers - This routine builds initialization ASTs for the 17382 /// Objective-C implementation whose ivars need be initialized. 17383 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 17384 if (!getLangOpts().CPlusPlus) 17385 return; 17386 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 17387 SmallVector<ObjCIvarDecl*, 8> ivars; 17388 CollectIvarsToConstructOrDestruct(OID, ivars); 17389 if (ivars.empty()) 17390 return; 17391 SmallVector<CXXCtorInitializer*, 32> AllToInit; 17392 for (unsigned i = 0; i < ivars.size(); i++) { 17393 FieldDecl *Field = ivars[i]; 17394 if (Field->isInvalidDecl()) 17395 continue; 17396 17397 CXXCtorInitializer *Member; 17398 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 17399 InitializationKind InitKind = 17400 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 17401 17402 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 17403 ExprResult MemberInit = 17404 InitSeq.Perform(*this, InitEntity, InitKind, None); 17405 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 17406 // Note, MemberInit could actually come back empty if no initialization 17407 // is required (e.g., because it would call a trivial default constructor) 17408 if (!MemberInit.get() || MemberInit.isInvalid()) 17409 continue; 17410 17411 Member = 17412 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 17413 SourceLocation(), 17414 MemberInit.getAs<Expr>(), 17415 SourceLocation()); 17416 AllToInit.push_back(Member); 17417 17418 // Be sure that the destructor is accessible and is marked as referenced. 17419 if (const RecordType *RecordTy = 17420 Context.getBaseElementType(Field->getType()) 17421 ->getAs<RecordType>()) { 17422 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 17423 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 17424 MarkFunctionReferenced(Field->getLocation(), Destructor); 17425 CheckDestructorAccess(Field->getLocation(), Destructor, 17426 PDiag(diag::err_access_dtor_ivar) 17427 << Context.getBaseElementType(Field->getType())); 17428 } 17429 } 17430 } 17431 ObjCImplementation->setIvarInitializers(Context, 17432 AllToInit.data(), AllToInit.size()); 17433 } 17434 } 17435 17436 static 17437 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 17438 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 17439 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 17440 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 17441 Sema &S) { 17442 if (Ctor->isInvalidDecl()) 17443 return; 17444 17445 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 17446 17447 // Target may not be determinable yet, for instance if this is a dependent 17448 // call in an uninstantiated template. 17449 if (Target) { 17450 const FunctionDecl *FNTarget = nullptr; 17451 (void)Target->hasBody(FNTarget); 17452 Target = const_cast<CXXConstructorDecl*>( 17453 cast_or_null<CXXConstructorDecl>(FNTarget)); 17454 } 17455 17456 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 17457 // Avoid dereferencing a null pointer here. 17458 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 17459 17460 if (!Current.insert(Canonical).second) 17461 return; 17462 17463 // We know that beyond here, we aren't chaining into a cycle. 17464 if (!Target || !Target->isDelegatingConstructor() || 17465 Target->isInvalidDecl() || Valid.count(TCanonical)) { 17466 Valid.insert(Current.begin(), Current.end()); 17467 Current.clear(); 17468 // We've hit a cycle. 17469 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 17470 Current.count(TCanonical)) { 17471 // If we haven't diagnosed this cycle yet, do so now. 17472 if (!Invalid.count(TCanonical)) { 17473 S.Diag((*Ctor->init_begin())->getSourceLocation(), 17474 diag::warn_delegating_ctor_cycle) 17475 << Ctor; 17476 17477 // Don't add a note for a function delegating directly to itself. 17478 if (TCanonical != Canonical) 17479 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 17480 17481 CXXConstructorDecl *C = Target; 17482 while (C->getCanonicalDecl() != Canonical) { 17483 const FunctionDecl *FNTarget = nullptr; 17484 (void)C->getTargetConstructor()->hasBody(FNTarget); 17485 assert(FNTarget && "Ctor cycle through bodiless function"); 17486 17487 C = const_cast<CXXConstructorDecl*>( 17488 cast<CXXConstructorDecl>(FNTarget)); 17489 S.Diag(C->getLocation(), diag::note_which_delegates_to); 17490 } 17491 } 17492 17493 Invalid.insert(Current.begin(), Current.end()); 17494 Current.clear(); 17495 } else { 17496 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 17497 } 17498 } 17499 17500 17501 void Sema::CheckDelegatingCtorCycles() { 17502 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 17503 17504 for (DelegatingCtorDeclsType::iterator 17505 I = DelegatingCtorDecls.begin(ExternalSource), 17506 E = DelegatingCtorDecls.end(); 17507 I != E; ++I) 17508 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 17509 17510 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 17511 (*CI)->setInvalidDecl(); 17512 } 17513 17514 namespace { 17515 /// AST visitor that finds references to the 'this' expression. 17516 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 17517 Sema &S; 17518 17519 public: 17520 explicit FindCXXThisExpr(Sema &S) : S(S) { } 17521 17522 bool VisitCXXThisExpr(CXXThisExpr *E) { 17523 S.Diag(E->getLocation(), diag::err_this_static_member_func) 17524 << E->isImplicit(); 17525 return false; 17526 } 17527 }; 17528 } 17529 17530 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 17531 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17532 if (!TSInfo) 17533 return false; 17534 17535 TypeLoc TL = TSInfo->getTypeLoc(); 17536 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17537 if (!ProtoTL) 17538 return false; 17539 17540 // C++11 [expr.prim.general]p3: 17541 // [The expression this] shall not appear before the optional 17542 // cv-qualifier-seq and it shall not appear within the declaration of a 17543 // static member function (although its type and value category are defined 17544 // within a static member function as they are within a non-static member 17545 // function). [ Note: this is because declaration matching does not occur 17546 // until the complete declarator is known. - end note ] 17547 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17548 FindCXXThisExpr Finder(*this); 17549 17550 // If the return type came after the cv-qualifier-seq, check it now. 17551 if (Proto->hasTrailingReturn() && 17552 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 17553 return true; 17554 17555 // Check the exception specification. 17556 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 17557 return true; 17558 17559 // Check the trailing requires clause 17560 if (Expr *E = Method->getTrailingRequiresClause()) 17561 if (!Finder.TraverseStmt(E)) 17562 return true; 17563 17564 return checkThisInStaticMemberFunctionAttributes(Method); 17565 } 17566 17567 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 17568 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17569 if (!TSInfo) 17570 return false; 17571 17572 TypeLoc TL = TSInfo->getTypeLoc(); 17573 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17574 if (!ProtoTL) 17575 return false; 17576 17577 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17578 FindCXXThisExpr Finder(*this); 17579 17580 switch (Proto->getExceptionSpecType()) { 17581 case EST_Unparsed: 17582 case EST_Uninstantiated: 17583 case EST_Unevaluated: 17584 case EST_BasicNoexcept: 17585 case EST_NoThrow: 17586 case EST_DynamicNone: 17587 case EST_MSAny: 17588 case EST_None: 17589 break; 17590 17591 case EST_DependentNoexcept: 17592 case EST_NoexceptFalse: 17593 case EST_NoexceptTrue: 17594 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 17595 return true; 17596 LLVM_FALLTHROUGH; 17597 17598 case EST_Dynamic: 17599 for (const auto &E : Proto->exceptions()) { 17600 if (!Finder.TraverseType(E)) 17601 return true; 17602 } 17603 break; 17604 } 17605 17606 return false; 17607 } 17608 17609 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 17610 FindCXXThisExpr Finder(*this); 17611 17612 // Check attributes. 17613 for (const auto *A : Method->attrs()) { 17614 // FIXME: This should be emitted by tblgen. 17615 Expr *Arg = nullptr; 17616 ArrayRef<Expr *> Args; 17617 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 17618 Arg = G->getArg(); 17619 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 17620 Arg = G->getArg(); 17621 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 17622 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 17623 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 17624 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 17625 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 17626 Arg = ETLF->getSuccessValue(); 17627 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 17628 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 17629 Arg = STLF->getSuccessValue(); 17630 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 17631 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 17632 Arg = LR->getArg(); 17633 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 17634 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 17635 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 17636 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17637 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 17638 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17639 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 17640 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17641 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 17642 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17643 17644 if (Arg && !Finder.TraverseStmt(Arg)) 17645 return true; 17646 17647 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 17648 if (!Finder.TraverseStmt(Args[I])) 17649 return true; 17650 } 17651 } 17652 17653 return false; 17654 } 17655 17656 void Sema::checkExceptionSpecification( 17657 bool IsTopLevel, ExceptionSpecificationType EST, 17658 ArrayRef<ParsedType> DynamicExceptions, 17659 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 17660 SmallVectorImpl<QualType> &Exceptions, 17661 FunctionProtoType::ExceptionSpecInfo &ESI) { 17662 Exceptions.clear(); 17663 ESI.Type = EST; 17664 if (EST == EST_Dynamic) { 17665 Exceptions.reserve(DynamicExceptions.size()); 17666 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 17667 // FIXME: Preserve type source info. 17668 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 17669 17670 if (IsTopLevel) { 17671 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 17672 collectUnexpandedParameterPacks(ET, Unexpanded); 17673 if (!Unexpanded.empty()) { 17674 DiagnoseUnexpandedParameterPacks( 17675 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 17676 Unexpanded); 17677 continue; 17678 } 17679 } 17680 17681 // Check that the type is valid for an exception spec, and 17682 // drop it if not. 17683 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 17684 Exceptions.push_back(ET); 17685 } 17686 ESI.Exceptions = Exceptions; 17687 return; 17688 } 17689 17690 if (isComputedNoexcept(EST)) { 17691 assert((NoexceptExpr->isTypeDependent() || 17692 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 17693 Context.BoolTy) && 17694 "Parser should have made sure that the expression is boolean"); 17695 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 17696 ESI.Type = EST_BasicNoexcept; 17697 return; 17698 } 17699 17700 ESI.NoexceptExpr = NoexceptExpr; 17701 return; 17702 } 17703 } 17704 17705 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 17706 ExceptionSpecificationType EST, 17707 SourceRange SpecificationRange, 17708 ArrayRef<ParsedType> DynamicExceptions, 17709 ArrayRef<SourceRange> DynamicExceptionRanges, 17710 Expr *NoexceptExpr) { 17711 if (!MethodD) 17712 return; 17713 17714 // Dig out the method we're referring to. 17715 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 17716 MethodD = FunTmpl->getTemplatedDecl(); 17717 17718 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 17719 if (!Method) 17720 return; 17721 17722 // Check the exception specification. 17723 llvm::SmallVector<QualType, 4> Exceptions; 17724 FunctionProtoType::ExceptionSpecInfo ESI; 17725 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 17726 DynamicExceptionRanges, NoexceptExpr, Exceptions, 17727 ESI); 17728 17729 // Update the exception specification on the function type. 17730 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 17731 17732 if (Method->isStatic()) 17733 checkThisInStaticMemberFunctionExceptionSpec(Method); 17734 17735 if (Method->isVirtual()) { 17736 // Check overrides, which we previously had to delay. 17737 for (const CXXMethodDecl *O : Method->overridden_methods()) 17738 CheckOverridingFunctionExceptionSpec(Method, O); 17739 } 17740 } 17741 17742 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 17743 /// 17744 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 17745 SourceLocation DeclStart, Declarator &D, 17746 Expr *BitWidth, 17747 InClassInitStyle InitStyle, 17748 AccessSpecifier AS, 17749 const ParsedAttr &MSPropertyAttr) { 17750 IdentifierInfo *II = D.getIdentifier(); 17751 if (!II) { 17752 Diag(DeclStart, diag::err_anonymous_property); 17753 return nullptr; 17754 } 17755 SourceLocation Loc = D.getIdentifierLoc(); 17756 17757 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17758 QualType T = TInfo->getType(); 17759 if (getLangOpts().CPlusPlus) { 17760 CheckExtraCXXDefaultArguments(D); 17761 17762 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 17763 UPPC_DataMemberType)) { 17764 D.setInvalidType(); 17765 T = Context.IntTy; 17766 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 17767 } 17768 } 17769 17770 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 17771 17772 if (D.getDeclSpec().isInlineSpecified()) 17773 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 17774 << getLangOpts().CPlusPlus17; 17775 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 17776 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 17777 diag::err_invalid_thread) 17778 << DeclSpec::getSpecifierName(TSCS); 17779 17780 // Check to see if this name was declared as a member previously 17781 NamedDecl *PrevDecl = nullptr; 17782 LookupResult Previous(*this, II, Loc, LookupMemberName, 17783 ForVisibleRedeclaration); 17784 LookupName(Previous, S); 17785 switch (Previous.getResultKind()) { 17786 case LookupResult::Found: 17787 case LookupResult::FoundUnresolvedValue: 17788 PrevDecl = Previous.getAsSingle<NamedDecl>(); 17789 break; 17790 17791 case LookupResult::FoundOverloaded: 17792 PrevDecl = Previous.getRepresentativeDecl(); 17793 break; 17794 17795 case LookupResult::NotFound: 17796 case LookupResult::NotFoundInCurrentInstantiation: 17797 case LookupResult::Ambiguous: 17798 break; 17799 } 17800 17801 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17802 // Maybe we will complain about the shadowed template parameter. 17803 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 17804 // Just pretend that we didn't see the previous declaration. 17805 PrevDecl = nullptr; 17806 } 17807 17808 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 17809 PrevDecl = nullptr; 17810 17811 SourceLocation TSSL = D.getBeginLoc(); 17812 MSPropertyDecl *NewPD = 17813 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 17814 MSPropertyAttr.getPropertyDataGetter(), 17815 MSPropertyAttr.getPropertyDataSetter()); 17816 ProcessDeclAttributes(TUScope, NewPD, D); 17817 NewPD->setAccess(AS); 17818 17819 if (NewPD->isInvalidDecl()) 17820 Record->setInvalidDecl(); 17821 17822 if (D.getDeclSpec().isModulePrivateSpecified()) 17823 NewPD->setModulePrivate(); 17824 17825 if (NewPD->isInvalidDecl() && PrevDecl) { 17826 // Don't introduce NewFD into scope; there's already something 17827 // with the same name in the same scope. 17828 } else if (II) { 17829 PushOnScopeChains(NewPD, S); 17830 } else 17831 Record->addDecl(NewPD); 17832 17833 return NewPD; 17834 } 17835 17836 void Sema::ActOnStartFunctionDeclarationDeclarator( 17837 Declarator &Declarator, unsigned TemplateParameterDepth) { 17838 auto &Info = InventedParameterInfos.emplace_back(); 17839 TemplateParameterList *ExplicitParams = nullptr; 17840 ArrayRef<TemplateParameterList *> ExplicitLists = 17841 Declarator.getTemplateParameterLists(); 17842 if (!ExplicitLists.empty()) { 17843 bool IsMemberSpecialization, IsInvalid; 17844 ExplicitParams = MatchTemplateParametersToScopeSpecifier( 17845 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), 17846 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, 17847 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, 17848 /*SuppressDiagnostic=*/true); 17849 } 17850 if (ExplicitParams) { 17851 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); 17852 for (NamedDecl *Param : *ExplicitParams) 17853 Info.TemplateParams.push_back(Param); 17854 Info.NumExplicitTemplateParams = ExplicitParams->size(); 17855 } else { 17856 Info.AutoTemplateParameterDepth = TemplateParameterDepth; 17857 Info.NumExplicitTemplateParams = 0; 17858 } 17859 } 17860 17861 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { 17862 auto &FSI = InventedParameterInfos.back(); 17863 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { 17864 if (FSI.NumExplicitTemplateParams != 0) { 17865 TemplateParameterList *ExplicitParams = 17866 Declarator.getTemplateParameterLists().back(); 17867 Declarator.setInventedTemplateParameterList( 17868 TemplateParameterList::Create( 17869 Context, ExplicitParams->getTemplateLoc(), 17870 ExplicitParams->getLAngleLoc(), FSI.TemplateParams, 17871 ExplicitParams->getRAngleLoc(), 17872 ExplicitParams->getRequiresClause())); 17873 } else { 17874 Declarator.setInventedTemplateParameterList( 17875 TemplateParameterList::Create( 17876 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, 17877 SourceLocation(), /*RequiresClause=*/nullptr)); 17878 } 17879 } 17880 InventedParameterInfos.pop_back(); 17881 } 17882