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(const ParmVarDecl *Param, 258 Expr *Arg, 259 SourceLocation EqualLoc) { 260 if (RequireCompleteType(Param->getLocation(), Param->getType(), 261 diag::err_typecheck_decl_incomplete_type)) 262 return true; 263 264 // C++ [dcl.fct.default]p5 265 // A default argument expression is implicitly converted (clause 266 // 4) to the parameter type. The default argument expression has 267 // the same semantic constraints as the initializer expression in 268 // a declaration of a variable of the parameter type, using the 269 // copy-initialization semantics (8.5). 270 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 271 Param); 272 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 273 EqualLoc); 274 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 275 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 276 if (Result.isInvalid()) 277 return true; 278 Arg = Result.getAs<Expr>(); 279 280 CheckCompletedExpr(Arg, EqualLoc); 281 Arg = MaybeCreateExprWithCleanups(Arg); 282 283 return Arg; 284 } 285 286 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 287 SourceLocation EqualLoc) { 288 // Add the default argument to the parameter 289 Param->setDefaultArg(Arg); 290 291 // We have already instantiated this parameter; provide each of the 292 // instantiations with the uninstantiated default argument. 293 UnparsedDefaultArgInstantiationsMap::iterator InstPos 294 = UnparsedDefaultArgInstantiations.find(Param); 295 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 296 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 297 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 298 299 // We're done tracking this parameter's instantiations. 300 UnparsedDefaultArgInstantiations.erase(InstPos); 301 } 302 } 303 304 /// ActOnParamDefaultArgument - Check whether the default argument 305 /// provided for a function parameter is well-formed. If so, attach it 306 /// to the parameter declaration. 307 void 308 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 309 Expr *DefaultArg) { 310 if (!param || !DefaultArg) 311 return; 312 313 ParmVarDecl *Param = cast<ParmVarDecl>(param); 314 UnparsedDefaultArgLocs.erase(Param); 315 316 auto Fail = [&] { 317 Param->setInvalidDecl(); 318 Param->setDefaultArg(new (Context) OpaqueValueExpr( 319 EqualLoc, Param->getType().getNonReferenceType(), VK_RValue)); 320 }; 321 322 // Default arguments are only permitted in C++ 323 if (!getLangOpts().CPlusPlus) { 324 Diag(EqualLoc, diag::err_param_default_argument) 325 << DefaultArg->getSourceRange(); 326 return Fail(); 327 } 328 329 // Check for unexpanded parameter packs. 330 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 331 return Fail(); 332 } 333 334 // C++11 [dcl.fct.default]p3 335 // A default argument expression [...] shall not be specified for a 336 // parameter pack. 337 if (Param->isParameterPack()) { 338 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 339 << DefaultArg->getSourceRange(); 340 // Recover by discarding the default argument. 341 Param->setDefaultArg(nullptr); 342 return; 343 } 344 345 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc); 346 if (Result.isInvalid()) 347 return Fail(); 348 349 DefaultArg = Result.getAs<Expr>(); 350 351 // Check that the default argument is well-formed 352 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg); 353 if (DefaultArgChecker.Visit(DefaultArg)) 354 return Fail(); 355 356 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 357 } 358 359 /// ActOnParamUnparsedDefaultArgument - We've seen a default 360 /// argument for a function parameter, but we can't parse it yet 361 /// because we're inside a class definition. Note that this default 362 /// argument will be parsed later. 363 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 364 SourceLocation EqualLoc, 365 SourceLocation ArgLoc) { 366 if (!param) 367 return; 368 369 ParmVarDecl *Param = cast<ParmVarDecl>(param); 370 Param->setUnparsedDefaultArg(); 371 UnparsedDefaultArgLocs[Param] = ArgLoc; 372 } 373 374 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 375 /// the default argument for the parameter param failed. 376 void Sema::ActOnParamDefaultArgumentError(Decl *param, 377 SourceLocation EqualLoc) { 378 if (!param) 379 return; 380 381 ParmVarDecl *Param = cast<ParmVarDecl>(param); 382 Param->setInvalidDecl(); 383 UnparsedDefaultArgLocs.erase(Param); 384 Param->setDefaultArg(new(Context) 385 OpaqueValueExpr(EqualLoc, 386 Param->getType().getNonReferenceType(), 387 VK_RValue)); 388 } 389 390 /// CheckExtraCXXDefaultArguments - Check for any extra default 391 /// arguments in the declarator, which is not a function declaration 392 /// or definition and therefore is not permitted to have default 393 /// arguments. This routine should be invoked for every declarator 394 /// that is not a function declaration or definition. 395 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 396 // C++ [dcl.fct.default]p3 397 // A default argument expression shall be specified only in the 398 // parameter-declaration-clause of a function declaration or in a 399 // template-parameter (14.1). It shall not be specified for a 400 // parameter pack. If it is specified in a 401 // parameter-declaration-clause, it shall not occur within a 402 // declarator or abstract-declarator of a parameter-declaration. 403 bool MightBeFunction = D.isFunctionDeclarationContext(); 404 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 405 DeclaratorChunk &chunk = D.getTypeObject(i); 406 if (chunk.Kind == DeclaratorChunk::Function) { 407 if (MightBeFunction) { 408 // This is a function declaration. It can have default arguments, but 409 // keep looking in case its return type is a function type with default 410 // arguments. 411 MightBeFunction = false; 412 continue; 413 } 414 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 415 ++argIdx) { 416 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 417 if (Param->hasUnparsedDefaultArg()) { 418 std::unique_ptr<CachedTokens> Toks = 419 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 420 SourceRange SR; 421 if (Toks->size() > 1) 422 SR = SourceRange((*Toks)[1].getLocation(), 423 Toks->back().getLocation()); 424 else 425 SR = UnparsedDefaultArgLocs[Param]; 426 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 427 << SR; 428 } else if (Param->getDefaultArg()) { 429 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 430 << Param->getDefaultArg()->getSourceRange(); 431 Param->setDefaultArg(nullptr); 432 } 433 } 434 } else if (chunk.Kind != DeclaratorChunk::Paren) { 435 MightBeFunction = false; 436 } 437 } 438 } 439 440 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 441 return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) { 442 return P->hasDefaultArg() && !P->hasInheritedDefaultArg(); 443 }); 444 } 445 446 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 447 /// function, once we already know that they have the same 448 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 449 /// error, false otherwise. 450 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 451 Scope *S) { 452 bool Invalid = false; 453 454 // The declaration context corresponding to the scope is the semantic 455 // parent, unless this is a local function declaration, in which case 456 // it is that surrounding function. 457 DeclContext *ScopeDC = New->isLocalExternDecl() 458 ? New->getLexicalDeclContext() 459 : New->getDeclContext(); 460 461 // Find the previous declaration for the purpose of default arguments. 462 FunctionDecl *PrevForDefaultArgs = Old; 463 for (/**/; PrevForDefaultArgs; 464 // Don't bother looking back past the latest decl if this is a local 465 // extern declaration; nothing else could work. 466 PrevForDefaultArgs = New->isLocalExternDecl() 467 ? nullptr 468 : PrevForDefaultArgs->getPreviousDecl()) { 469 // Ignore hidden declarations. 470 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 471 continue; 472 473 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 474 !New->isCXXClassMember()) { 475 // Ignore default arguments of old decl if they are not in 476 // the same scope and this is not an out-of-line definition of 477 // a member function. 478 continue; 479 } 480 481 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 482 // If only one of these is a local function declaration, then they are 483 // declared in different scopes, even though isDeclInScope may think 484 // they're in the same scope. (If both are local, the scope check is 485 // sufficient, and if neither is local, then they are in the same scope.) 486 continue; 487 } 488 489 // We found the right previous declaration. 490 break; 491 } 492 493 // C++ [dcl.fct.default]p4: 494 // For non-template functions, default arguments can be added in 495 // later declarations of a function in the same 496 // scope. Declarations in different scopes have completely 497 // distinct sets of default arguments. That is, declarations in 498 // inner scopes do not acquire default arguments from 499 // declarations in outer scopes, and vice versa. In a given 500 // function declaration, all parameters subsequent to a 501 // parameter with a default argument shall have default 502 // arguments supplied in this or previous declarations. A 503 // default argument shall not be redefined by a later 504 // declaration (not even to the same value). 505 // 506 // C++ [dcl.fct.default]p6: 507 // Except for member functions of class templates, the default arguments 508 // in a member function definition that appears outside of the class 509 // definition are added to the set of default arguments provided by the 510 // member function declaration in the class definition. 511 for (unsigned p = 0, NumParams = PrevForDefaultArgs 512 ? PrevForDefaultArgs->getNumParams() 513 : 0; 514 p < NumParams; ++p) { 515 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 516 ParmVarDecl *NewParam = New->getParamDecl(p); 517 518 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 519 bool NewParamHasDfl = NewParam->hasDefaultArg(); 520 521 if (OldParamHasDfl && NewParamHasDfl) { 522 unsigned DiagDefaultParamID = 523 diag::err_param_default_argument_redefinition; 524 525 // MSVC accepts that default parameters be redefined for member functions 526 // of template class. The new default parameter's value is ignored. 527 Invalid = true; 528 if (getLangOpts().MicrosoftExt) { 529 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 530 if (MD && MD->getParent()->getDescribedClassTemplate()) { 531 // Merge the old default argument into the new parameter. 532 NewParam->setHasInheritedDefaultArg(); 533 if (OldParam->hasUninstantiatedDefaultArg()) 534 NewParam->setUninstantiatedDefaultArg( 535 OldParam->getUninstantiatedDefaultArg()); 536 else 537 NewParam->setDefaultArg(OldParam->getInit()); 538 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 539 Invalid = false; 540 } 541 } 542 543 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 544 // hint here. Alternatively, we could walk the type-source information 545 // for NewParam to find the last source location in the type... but it 546 // isn't worth the effort right now. This is the kind of test case that 547 // is hard to get right: 548 // int f(int); 549 // void g(int (*fp)(int) = f); 550 // void g(int (*fp)(int) = &f); 551 Diag(NewParam->getLocation(), DiagDefaultParamID) 552 << NewParam->getDefaultArgRange(); 553 554 // Look for the function declaration where the default argument was 555 // actually written, which may be a declaration prior to Old. 556 for (auto Older = PrevForDefaultArgs; 557 OldParam->hasInheritedDefaultArg(); /**/) { 558 Older = Older->getPreviousDecl(); 559 OldParam = Older->getParamDecl(p); 560 } 561 562 Diag(OldParam->getLocation(), diag::note_previous_definition) 563 << OldParam->getDefaultArgRange(); 564 } else if (OldParamHasDfl) { 565 // Merge the old default argument into the new parameter unless the new 566 // function is a friend declaration in a template class. In the latter 567 // case the default arguments will be inherited when the friend 568 // declaration will be instantiated. 569 if (New->getFriendObjectKind() == Decl::FOK_None || 570 !New->getLexicalDeclContext()->isDependentContext()) { 571 // It's important to use getInit() here; getDefaultArg() 572 // strips off any top-level ExprWithCleanups. 573 NewParam->setHasInheritedDefaultArg(); 574 if (OldParam->hasUnparsedDefaultArg()) 575 NewParam->setUnparsedDefaultArg(); 576 else if (OldParam->hasUninstantiatedDefaultArg()) 577 NewParam->setUninstantiatedDefaultArg( 578 OldParam->getUninstantiatedDefaultArg()); 579 else 580 NewParam->setDefaultArg(OldParam->getInit()); 581 } 582 } else if (NewParamHasDfl) { 583 if (New->getDescribedFunctionTemplate()) { 584 // Paragraph 4, quoted above, only applies to non-template functions. 585 Diag(NewParam->getLocation(), 586 diag::err_param_default_argument_template_redecl) 587 << NewParam->getDefaultArgRange(); 588 Diag(PrevForDefaultArgs->getLocation(), 589 diag::note_template_prev_declaration) 590 << false; 591 } else if (New->getTemplateSpecializationKind() 592 != TSK_ImplicitInstantiation && 593 New->getTemplateSpecializationKind() != TSK_Undeclared) { 594 // C++ [temp.expr.spec]p21: 595 // Default function arguments shall not be specified in a declaration 596 // or a definition for one of the following explicit specializations: 597 // - the explicit specialization of a function template; 598 // - the explicit specialization of a member function template; 599 // - the explicit specialization of a member function of a class 600 // template where the class template specialization to which the 601 // member function specialization belongs is implicitly 602 // instantiated. 603 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 604 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 605 << New->getDeclName() 606 << NewParam->getDefaultArgRange(); 607 } else if (New->getDeclContext()->isDependentContext()) { 608 // C++ [dcl.fct.default]p6 (DR217): 609 // Default arguments for a member function of a class template shall 610 // be specified on the initial declaration of the member function 611 // within the class template. 612 // 613 // Reading the tea leaves a bit in DR217 and its reference to DR205 614 // leads me to the conclusion that one cannot add default function 615 // arguments for an out-of-line definition of a member function of a 616 // dependent type. 617 int WhichKind = 2; 618 if (CXXRecordDecl *Record 619 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 620 if (Record->getDescribedClassTemplate()) 621 WhichKind = 0; 622 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 623 WhichKind = 1; 624 else 625 WhichKind = 2; 626 } 627 628 Diag(NewParam->getLocation(), 629 diag::err_param_default_argument_member_template_redecl) 630 << WhichKind 631 << NewParam->getDefaultArgRange(); 632 } 633 } 634 } 635 636 // DR1344: If a default argument is added outside a class definition and that 637 // default argument makes the function a special member function, the program 638 // is ill-formed. This can only happen for constructors. 639 if (isa<CXXConstructorDecl>(New) && 640 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 641 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 642 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 643 if (NewSM != OldSM) { 644 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 645 assert(NewParam->hasDefaultArg()); 646 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 647 << NewParam->getDefaultArgRange() << NewSM; 648 Diag(Old->getLocation(), diag::note_previous_declaration); 649 } 650 } 651 652 const FunctionDecl *Def; 653 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 654 // template has a constexpr specifier then all its declarations shall 655 // contain the constexpr specifier. 656 if (New->getConstexprKind() != Old->getConstexprKind()) { 657 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 658 << New << static_cast<int>(New->getConstexprKind()) 659 << static_cast<int>(Old->getConstexprKind()); 660 Diag(Old->getLocation(), diag::note_previous_declaration); 661 Invalid = true; 662 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 663 Old->isDefined(Def) && 664 // If a friend function is inlined but does not have 'inline' 665 // specifier, it is a definition. Do not report attribute conflict 666 // in this case, redefinition will be diagnosed later. 667 (New->isInlineSpecified() || 668 New->getFriendObjectKind() == Decl::FOK_None)) { 669 // C++11 [dcl.fcn.spec]p4: 670 // If the definition of a function appears in a translation unit before its 671 // first declaration as inline, the program is ill-formed. 672 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 673 Diag(Def->getLocation(), diag::note_previous_definition); 674 Invalid = true; 675 } 676 677 // C++17 [temp.deduct.guide]p3: 678 // Two deduction guide declarations in the same translation unit 679 // for the same class template shall not have equivalent 680 // parameter-declaration-clauses. 681 if (isa<CXXDeductionGuideDecl>(New) && 682 !New->isFunctionTemplateSpecialization() && isVisible(Old)) { 683 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 684 Diag(Old->getLocation(), diag::note_previous_declaration); 685 } 686 687 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 688 // argument expression, that declaration shall be a definition and shall be 689 // the only declaration of the function or function template in the 690 // translation unit. 691 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 692 functionDeclHasDefaultArgument(Old)) { 693 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 694 Diag(Old->getLocation(), diag::note_previous_declaration); 695 Invalid = true; 696 } 697 698 // C++11 [temp.friend]p4 (DR329): 699 // When a function is defined in a friend function declaration in a class 700 // template, the function is instantiated when the function is odr-used. 701 // The same restrictions on multiple declarations and definitions that 702 // apply to non-template function declarations and definitions also apply 703 // to these implicit definitions. 704 const FunctionDecl *OldDefinition = nullptr; 705 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() && 706 Old->isDefined(OldDefinition, true)) 707 CheckForFunctionRedefinition(New, OldDefinition); 708 709 return Invalid; 710 } 711 712 NamedDecl * 713 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 714 MultiTemplateParamsArg TemplateParamLists) { 715 assert(D.isDecompositionDeclarator()); 716 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 717 718 // The syntax only allows a decomposition declarator as a simple-declaration, 719 // a for-range-declaration, or a condition in Clang, but we parse it in more 720 // cases than that. 721 if (!D.mayHaveDecompositionDeclarator()) { 722 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 723 << Decomp.getSourceRange(); 724 return nullptr; 725 } 726 727 if (!TemplateParamLists.empty()) { 728 // FIXME: There's no rule against this, but there are also no rules that 729 // would actually make it usable, so we reject it for now. 730 Diag(TemplateParamLists.front()->getTemplateLoc(), 731 diag::err_decomp_decl_template); 732 return nullptr; 733 } 734 735 Diag(Decomp.getLSquareLoc(), 736 !getLangOpts().CPlusPlus17 737 ? diag::ext_decomp_decl 738 : D.getContext() == DeclaratorContext::Condition 739 ? diag::ext_decomp_decl_cond 740 : diag::warn_cxx14_compat_decomp_decl) 741 << Decomp.getSourceRange(); 742 743 // The semantic context is always just the current context. 744 DeclContext *const DC = CurContext; 745 746 // C++17 [dcl.dcl]/8: 747 // The decl-specifier-seq shall contain only the type-specifier auto 748 // and cv-qualifiers. 749 // C++2a [dcl.dcl]/8: 750 // If decl-specifier-seq contains any decl-specifier other than static, 751 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 752 auto &DS = D.getDeclSpec(); 753 { 754 SmallVector<StringRef, 8> BadSpecifiers; 755 SmallVector<SourceLocation, 8> BadSpecifierLocs; 756 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 757 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 758 if (auto SCS = DS.getStorageClassSpec()) { 759 if (SCS == DeclSpec::SCS_static) { 760 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 761 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 762 } else { 763 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 764 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 765 } 766 } 767 if (auto TSCS = DS.getThreadStorageClassSpec()) { 768 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 769 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 770 } 771 if (DS.hasConstexprSpecifier()) { 772 BadSpecifiers.push_back( 773 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 774 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 775 } 776 if (DS.isInlineSpecified()) { 777 BadSpecifiers.push_back("inline"); 778 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 779 } 780 if (!BadSpecifiers.empty()) { 781 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 782 Err << (int)BadSpecifiers.size() 783 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 784 // Don't add FixItHints to remove the specifiers; we do still respect 785 // them when building the underlying variable. 786 for (auto Loc : BadSpecifierLocs) 787 Err << SourceRange(Loc, Loc); 788 } else if (!CPlusPlus20Specifiers.empty()) { 789 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 790 getLangOpts().CPlusPlus20 791 ? diag::warn_cxx17_compat_decomp_decl_spec 792 : diag::ext_decomp_decl_spec); 793 Warn << (int)CPlusPlus20Specifiers.size() 794 << llvm::join(CPlusPlus20Specifiers.begin(), 795 CPlusPlus20Specifiers.end(), " "); 796 for (auto Loc : CPlusPlus20SpecifierLocs) 797 Warn << SourceRange(Loc, Loc); 798 } 799 // We can't recover from it being declared as a typedef. 800 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 801 return nullptr; 802 } 803 804 // C++2a [dcl.struct.bind]p1: 805 // A cv that includes volatile is deprecated 806 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && 807 getLangOpts().CPlusPlus20) 808 Diag(DS.getVolatileSpecLoc(), 809 diag::warn_deprecated_volatile_structured_binding); 810 811 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 812 QualType R = TInfo->getType(); 813 814 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 815 UPPC_DeclarationType)) 816 D.setInvalidType(); 817 818 // The syntax only allows a single ref-qualifier prior to the decomposition 819 // declarator. No other declarator chunks are permitted. Also check the type 820 // specifier here. 821 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 822 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 823 (D.getNumTypeObjects() == 1 && 824 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 825 Diag(Decomp.getLSquareLoc(), 826 (D.hasGroupingParens() || 827 (D.getNumTypeObjects() && 828 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 829 ? diag::err_decomp_decl_parens 830 : diag::err_decomp_decl_type) 831 << R; 832 833 // In most cases, there's no actual problem with an explicitly-specified 834 // type, but a function type won't work here, and ActOnVariableDeclarator 835 // shouldn't be called for such a type. 836 if (R->isFunctionType()) 837 D.setInvalidType(); 838 } 839 840 // Build the BindingDecls. 841 SmallVector<BindingDecl*, 8> Bindings; 842 843 // Build the BindingDecls. 844 for (auto &B : D.getDecompositionDeclarator().bindings()) { 845 // Check for name conflicts. 846 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 847 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 848 ForVisibleRedeclaration); 849 LookupName(Previous, S, 850 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 851 852 // It's not permitted to shadow a template parameter name. 853 if (Previous.isSingleResult() && 854 Previous.getFoundDecl()->isTemplateParameter()) { 855 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 856 Previous.getFoundDecl()); 857 Previous.clear(); 858 } 859 860 bool ConsiderLinkage = DC->isFunctionOrMethod() && 861 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 862 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 863 /*AllowInlineNamespace*/false); 864 if (!Previous.empty()) { 865 auto *Old = Previous.getRepresentativeDecl(); 866 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 867 Diag(Old->getLocation(), diag::note_previous_definition); 868 } 869 870 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 871 PushOnScopeChains(BD, S, true); 872 Bindings.push_back(BD); 873 ParsingInitForAutoVars.insert(BD); 874 } 875 876 // There are no prior lookup results for the variable itself, because it 877 // is unnamed. 878 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 879 Decomp.getLSquareLoc()); 880 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 881 ForVisibleRedeclaration); 882 883 // Build the variable that holds the non-decomposed object. 884 bool AddToScope = true; 885 NamedDecl *New = 886 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 887 MultiTemplateParamsArg(), AddToScope, Bindings); 888 if (AddToScope) { 889 S->AddDecl(New); 890 CurContext->addHiddenDecl(New); 891 } 892 893 if (isInOpenMPDeclareTargetContext()) 894 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 895 896 return New; 897 } 898 899 static bool checkSimpleDecomposition( 900 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 901 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 902 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 903 if ((int64_t)Bindings.size() != NumElems) { 904 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 905 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 906 << (NumElems < Bindings.size()); 907 return true; 908 } 909 910 unsigned I = 0; 911 for (auto *B : Bindings) { 912 SourceLocation Loc = B->getLocation(); 913 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 914 if (E.isInvalid()) 915 return true; 916 E = GetInit(Loc, E.get(), I++); 917 if (E.isInvalid()) 918 return true; 919 B->setBinding(ElemType, E.get()); 920 } 921 922 return false; 923 } 924 925 static bool checkArrayLikeDecomposition(Sema &S, 926 ArrayRef<BindingDecl *> Bindings, 927 ValueDecl *Src, QualType DecompType, 928 const llvm::APSInt &NumElems, 929 QualType ElemType) { 930 return checkSimpleDecomposition( 931 S, Bindings, Src, DecompType, NumElems, ElemType, 932 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 933 ExprResult E = S.ActOnIntegerConstant(Loc, I); 934 if (E.isInvalid()) 935 return ExprError(); 936 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 937 }); 938 } 939 940 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 941 ValueDecl *Src, QualType DecompType, 942 const ConstantArrayType *CAT) { 943 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 944 llvm::APSInt(CAT->getSize()), 945 CAT->getElementType()); 946 } 947 948 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 949 ValueDecl *Src, QualType DecompType, 950 const VectorType *VT) { 951 return checkArrayLikeDecomposition( 952 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 953 S.Context.getQualifiedType(VT->getElementType(), 954 DecompType.getQualifiers())); 955 } 956 957 static bool checkComplexDecomposition(Sema &S, 958 ArrayRef<BindingDecl *> Bindings, 959 ValueDecl *Src, QualType DecompType, 960 const ComplexType *CT) { 961 return checkSimpleDecomposition( 962 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 963 S.Context.getQualifiedType(CT->getElementType(), 964 DecompType.getQualifiers()), 965 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 966 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 967 }); 968 } 969 970 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 971 TemplateArgumentListInfo &Args) { 972 SmallString<128> SS; 973 llvm::raw_svector_ostream OS(SS); 974 bool First = true; 975 for (auto &Arg : Args.arguments()) { 976 if (!First) 977 OS << ", "; 978 Arg.getArgument().print(PrintingPolicy, OS); 979 First = false; 980 } 981 return std::string(OS.str()); 982 } 983 984 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 985 SourceLocation Loc, StringRef Trait, 986 TemplateArgumentListInfo &Args, 987 unsigned DiagID) { 988 auto DiagnoseMissing = [&] { 989 if (DiagID) 990 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 991 Args); 992 return true; 993 }; 994 995 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 996 NamespaceDecl *Std = S.getStdNamespace(); 997 if (!Std) 998 return DiagnoseMissing(); 999 1000 // Look up the trait itself, within namespace std. We can diagnose various 1001 // problems with this lookup even if we've been asked to not diagnose a 1002 // missing specialization, because this can only fail if the user has been 1003 // declaring their own names in namespace std or we don't support the 1004 // standard library implementation in use. 1005 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 1006 Loc, Sema::LookupOrdinaryName); 1007 if (!S.LookupQualifiedName(Result, Std)) 1008 return DiagnoseMissing(); 1009 if (Result.isAmbiguous()) 1010 return true; 1011 1012 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 1013 if (!TraitTD) { 1014 Result.suppressDiagnostics(); 1015 NamedDecl *Found = *Result.begin(); 1016 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 1017 S.Diag(Found->getLocation(), diag::note_declared_at); 1018 return true; 1019 } 1020 1021 // Build the template-id. 1022 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 1023 if (TraitTy.isNull()) 1024 return true; 1025 if (!S.isCompleteType(Loc, TraitTy)) { 1026 if (DiagID) 1027 S.RequireCompleteType( 1028 Loc, TraitTy, DiagID, 1029 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 1030 return true; 1031 } 1032 1033 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1034 assert(RD && "specialization of class template is not a class?"); 1035 1036 // Look up the member of the trait type. 1037 S.LookupQualifiedName(TraitMemberLookup, RD); 1038 return TraitMemberLookup.isAmbiguous(); 1039 } 1040 1041 static TemplateArgumentLoc 1042 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1043 uint64_t I) { 1044 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1045 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1046 } 1047 1048 static TemplateArgumentLoc 1049 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1050 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1051 } 1052 1053 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1054 1055 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1056 llvm::APSInt &Size) { 1057 EnterExpressionEvaluationContext ContextRAII( 1058 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1059 1060 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1061 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1062 1063 // Form template argument list for tuple_size<T>. 1064 TemplateArgumentListInfo Args(Loc, Loc); 1065 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1066 1067 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1068 // it's not tuple-like. 1069 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1070 R.empty()) 1071 return IsTupleLike::NotTupleLike; 1072 1073 // If we get this far, we've committed to the tuple interpretation, but 1074 // we can still fail if there actually isn't a usable ::value. 1075 1076 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1077 LookupResult &R; 1078 TemplateArgumentListInfo &Args; 1079 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1080 : R(R), Args(Args) {} 1081 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 1082 SourceLocation Loc) override { 1083 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1084 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1085 } 1086 } Diagnoser(R, Args); 1087 1088 ExprResult E = 1089 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1090 if (E.isInvalid()) 1091 return IsTupleLike::Error; 1092 1093 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser); 1094 if (E.isInvalid()) 1095 return IsTupleLike::Error; 1096 1097 return IsTupleLike::TupleLike; 1098 } 1099 1100 /// \return std::tuple_element<I, T>::type. 1101 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1102 unsigned I, QualType T) { 1103 // Form template argument list for tuple_element<I, T>. 1104 TemplateArgumentListInfo Args(Loc, Loc); 1105 Args.addArgument( 1106 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1107 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1108 1109 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1110 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1111 if (lookupStdTypeTraitMember( 1112 S, R, Loc, "tuple_element", Args, 1113 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1114 return QualType(); 1115 1116 auto *TD = R.getAsSingle<TypeDecl>(); 1117 if (!TD) { 1118 R.suppressDiagnostics(); 1119 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1120 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1121 if (!R.empty()) 1122 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1123 return QualType(); 1124 } 1125 1126 return S.Context.getTypeDeclType(TD); 1127 } 1128 1129 namespace { 1130 struct InitializingBinding { 1131 Sema &S; 1132 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) { 1133 Sema::CodeSynthesisContext Ctx; 1134 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding; 1135 Ctx.PointOfInstantiation = BD->getLocation(); 1136 Ctx.Entity = BD; 1137 S.pushCodeSynthesisContext(Ctx); 1138 } 1139 ~InitializingBinding() { 1140 S.popCodeSynthesisContext(); 1141 } 1142 }; 1143 } 1144 1145 static bool checkTupleLikeDecomposition(Sema &S, 1146 ArrayRef<BindingDecl *> Bindings, 1147 VarDecl *Src, QualType DecompType, 1148 const llvm::APSInt &TupleSize) { 1149 if ((int64_t)Bindings.size() != TupleSize) { 1150 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1151 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1152 << (TupleSize < Bindings.size()); 1153 return true; 1154 } 1155 1156 if (Bindings.empty()) 1157 return false; 1158 1159 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1160 1161 // [dcl.decomp]p3: 1162 // The unqualified-id get is looked up in the scope of E by class member 1163 // access lookup ... 1164 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1165 bool UseMemberGet = false; 1166 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1167 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1168 S.LookupQualifiedName(MemberGet, RD); 1169 if (MemberGet.isAmbiguous()) 1170 return true; 1171 // ... and if that finds at least one declaration that is a function 1172 // template whose first template parameter is a non-type parameter ... 1173 for (NamedDecl *D : MemberGet) { 1174 if (FunctionTemplateDecl *FTD = 1175 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1176 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1177 if (TPL->size() != 0 && 1178 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1179 // ... the initializer is e.get<i>(). 1180 UseMemberGet = true; 1181 break; 1182 } 1183 } 1184 } 1185 } 1186 1187 unsigned I = 0; 1188 for (auto *B : Bindings) { 1189 InitializingBinding InitContext(S, B); 1190 SourceLocation Loc = B->getLocation(); 1191 1192 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1193 if (E.isInvalid()) 1194 return true; 1195 1196 // e is an lvalue if the type of the entity is an lvalue reference and 1197 // an xvalue otherwise 1198 if (!Src->getType()->isLValueReferenceType()) 1199 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1200 E.get(), nullptr, VK_XValue, 1201 FPOptionsOverride()); 1202 1203 TemplateArgumentListInfo Args(Loc, Loc); 1204 Args.addArgument( 1205 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1206 1207 if (UseMemberGet) { 1208 // if [lookup of member get] finds at least one declaration, the 1209 // initializer is e.get<i-1>(). 1210 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1211 CXXScopeSpec(), SourceLocation(), nullptr, 1212 MemberGet, &Args, nullptr); 1213 if (E.isInvalid()) 1214 return true; 1215 1216 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1217 } else { 1218 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1219 // in the associated namespaces. 1220 Expr *Get = UnresolvedLookupExpr::Create( 1221 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1222 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1223 UnresolvedSetIterator(), UnresolvedSetIterator()); 1224 1225 Expr *Arg = E.get(); 1226 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1227 } 1228 if (E.isInvalid()) 1229 return true; 1230 Expr *Init = E.get(); 1231 1232 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1233 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1234 if (T.isNull()) 1235 return true; 1236 1237 // each vi is a variable of type "reference to T" initialized with the 1238 // initializer, where the reference is an lvalue reference if the 1239 // initializer is an lvalue and an rvalue reference otherwise 1240 QualType RefType = 1241 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1242 if (RefType.isNull()) 1243 return true; 1244 auto *RefVD = VarDecl::Create( 1245 S.Context, Src->getDeclContext(), Loc, Loc, 1246 B->getDeclName().getAsIdentifierInfo(), RefType, 1247 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1248 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1249 RefVD->setTSCSpec(Src->getTSCSpec()); 1250 RefVD->setImplicit(); 1251 if (Src->isInlineSpecified()) 1252 RefVD->setInlineSpecified(); 1253 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1254 1255 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1256 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1257 InitializationSequence Seq(S, Entity, Kind, Init); 1258 E = Seq.Perform(S, Entity, Kind, Init); 1259 if (E.isInvalid()) 1260 return true; 1261 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1262 if (E.isInvalid()) 1263 return true; 1264 RefVD->setInit(E.get()); 1265 S.CheckCompleteVariableDeclaration(RefVD); 1266 1267 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1268 DeclarationNameInfo(B->getDeclName(), Loc), 1269 RefVD); 1270 if (E.isInvalid()) 1271 return true; 1272 1273 B->setBinding(T, E.get()); 1274 I++; 1275 } 1276 1277 return false; 1278 } 1279 1280 /// Find the base class to decompose in a built-in decomposition of a class type. 1281 /// This base class search is, unfortunately, not quite like any other that we 1282 /// perform anywhere else in C++. 1283 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1284 const CXXRecordDecl *RD, 1285 CXXCastPath &BasePath) { 1286 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1287 CXXBasePath &Path) { 1288 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1289 }; 1290 1291 const CXXRecordDecl *ClassWithFields = nullptr; 1292 AccessSpecifier AS = AS_public; 1293 if (RD->hasDirectFields()) 1294 // [dcl.decomp]p4: 1295 // Otherwise, all of E's non-static data members shall be public direct 1296 // members of E ... 1297 ClassWithFields = RD; 1298 else { 1299 // ... or of ... 1300 CXXBasePaths Paths; 1301 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1302 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1303 // If no classes have fields, just decompose RD itself. (This will work 1304 // if and only if zero bindings were provided.) 1305 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1306 } 1307 1308 CXXBasePath *BestPath = nullptr; 1309 for (auto &P : Paths) { 1310 if (!BestPath) 1311 BestPath = &P; 1312 else if (!S.Context.hasSameType(P.back().Base->getType(), 1313 BestPath->back().Base->getType())) { 1314 // ... the same ... 1315 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1316 << false << RD << BestPath->back().Base->getType() 1317 << P.back().Base->getType(); 1318 return DeclAccessPair(); 1319 } else if (P.Access < BestPath->Access) { 1320 BestPath = &P; 1321 } 1322 } 1323 1324 // ... unambiguous ... 1325 QualType BaseType = BestPath->back().Base->getType(); 1326 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1327 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1328 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1329 return DeclAccessPair(); 1330 } 1331 1332 // ... [accessible, implied by other rules] base class of E. 1333 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1334 *BestPath, diag::err_decomp_decl_inaccessible_base); 1335 AS = BestPath->Access; 1336 1337 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1338 S.BuildBasePathArray(Paths, BasePath); 1339 } 1340 1341 // The above search did not check whether the selected class itself has base 1342 // classes with fields, so check that now. 1343 CXXBasePaths Paths; 1344 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1345 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1346 << (ClassWithFields == RD) << RD << ClassWithFields 1347 << Paths.front().back().Base->getType(); 1348 return DeclAccessPair(); 1349 } 1350 1351 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1352 } 1353 1354 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1355 ValueDecl *Src, QualType DecompType, 1356 const CXXRecordDecl *OrigRD) { 1357 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1358 diag::err_incomplete_type)) 1359 return true; 1360 1361 CXXCastPath BasePath; 1362 DeclAccessPair BasePair = 1363 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1364 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1365 if (!RD) 1366 return true; 1367 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1368 DecompType.getQualifiers()); 1369 1370 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1371 unsigned NumFields = 1372 std::count_if(RD->field_begin(), RD->field_end(), 1373 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1374 assert(Bindings.size() != NumFields); 1375 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1376 << DecompType << (unsigned)Bindings.size() << NumFields 1377 << (NumFields < Bindings.size()); 1378 return true; 1379 }; 1380 1381 // all of E's non-static data members shall be [...] well-formed 1382 // when named as e.name in the context of the structured binding, 1383 // E shall not have an anonymous union member, ... 1384 unsigned I = 0; 1385 for (auto *FD : RD->fields()) { 1386 if (FD->isUnnamedBitfield()) 1387 continue; 1388 1389 // All the non-static data members are required to be nameable, so they 1390 // must all have names. 1391 if (!FD->getDeclName()) { 1392 if (RD->isLambda()) { 1393 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda); 1394 S.Diag(RD->getLocation(), diag::note_lambda_decl); 1395 return true; 1396 } 1397 1398 if (FD->isAnonymousStructOrUnion()) { 1399 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1400 << DecompType << FD->getType()->isUnionType(); 1401 S.Diag(FD->getLocation(), diag::note_declared_at); 1402 return true; 1403 } 1404 1405 // FIXME: Are there any other ways we could have an anonymous member? 1406 } 1407 1408 // We have a real field to bind. 1409 if (I >= Bindings.size()) 1410 return DiagnoseBadNumberOfBindings(); 1411 auto *B = Bindings[I++]; 1412 SourceLocation Loc = B->getLocation(); 1413 1414 // The field must be accessible in the context of the structured binding. 1415 // We already checked that the base class is accessible. 1416 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1417 // const_cast here. 1418 S.CheckStructuredBindingMemberAccess( 1419 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1420 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1421 BasePair.getAccess(), FD->getAccess()))); 1422 1423 // Initialize the binding to Src.FD. 1424 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1425 if (E.isInvalid()) 1426 return true; 1427 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1428 VK_LValue, &BasePath); 1429 if (E.isInvalid()) 1430 return true; 1431 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1432 CXXScopeSpec(), FD, 1433 DeclAccessPair::make(FD, FD->getAccess()), 1434 DeclarationNameInfo(FD->getDeclName(), Loc)); 1435 if (E.isInvalid()) 1436 return true; 1437 1438 // If the type of the member is T, the referenced type is cv T, where cv is 1439 // the cv-qualification of the decomposition expression. 1440 // 1441 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1442 // 'const' to the type of the field. 1443 Qualifiers Q = DecompType.getQualifiers(); 1444 if (FD->isMutable()) 1445 Q.removeConst(); 1446 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1447 } 1448 1449 if (I != Bindings.size()) 1450 return DiagnoseBadNumberOfBindings(); 1451 1452 return false; 1453 } 1454 1455 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1456 QualType DecompType = DD->getType(); 1457 1458 // If the type of the decomposition is dependent, then so is the type of 1459 // each binding. 1460 if (DecompType->isDependentType()) { 1461 for (auto *B : DD->bindings()) 1462 B->setType(Context.DependentTy); 1463 return; 1464 } 1465 1466 DecompType = DecompType.getNonReferenceType(); 1467 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1468 1469 // C++1z [dcl.decomp]/2: 1470 // If E is an array type [...] 1471 // As an extension, we also support decomposition of built-in complex and 1472 // vector types. 1473 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1474 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1475 DD->setInvalidDecl(); 1476 return; 1477 } 1478 if (auto *VT = DecompType->getAs<VectorType>()) { 1479 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1480 DD->setInvalidDecl(); 1481 return; 1482 } 1483 if (auto *CT = DecompType->getAs<ComplexType>()) { 1484 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1485 DD->setInvalidDecl(); 1486 return; 1487 } 1488 1489 // C++1z [dcl.decomp]/3: 1490 // if the expression std::tuple_size<E>::value is a well-formed integral 1491 // constant expression, [...] 1492 llvm::APSInt TupleSize(32); 1493 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1494 case IsTupleLike::Error: 1495 DD->setInvalidDecl(); 1496 return; 1497 1498 case IsTupleLike::TupleLike: 1499 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1500 DD->setInvalidDecl(); 1501 return; 1502 1503 case IsTupleLike::NotTupleLike: 1504 break; 1505 } 1506 1507 // C++1z [dcl.dcl]/8: 1508 // [E shall be of array or non-union class type] 1509 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1510 if (!RD || RD->isUnion()) { 1511 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1512 << DD << !RD << DecompType; 1513 DD->setInvalidDecl(); 1514 return; 1515 } 1516 1517 // C++1z [dcl.decomp]/4: 1518 // all of E's non-static data members shall be [...] direct members of 1519 // E or of the same unambiguous public base class of E, ... 1520 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1521 DD->setInvalidDecl(); 1522 } 1523 1524 /// Merge the exception specifications of two variable declarations. 1525 /// 1526 /// This is called when there's a redeclaration of a VarDecl. The function 1527 /// checks if the redeclaration might have an exception specification and 1528 /// validates compatibility and merges the specs if necessary. 1529 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1530 // Shortcut if exceptions are disabled. 1531 if (!getLangOpts().CXXExceptions) 1532 return; 1533 1534 assert(Context.hasSameType(New->getType(), Old->getType()) && 1535 "Should only be called if types are otherwise the same."); 1536 1537 QualType NewType = New->getType(); 1538 QualType OldType = Old->getType(); 1539 1540 // We're only interested in pointers and references to functions, as well 1541 // as pointers to member functions. 1542 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1543 NewType = R->getPointeeType(); 1544 OldType = OldType->castAs<ReferenceType>()->getPointeeType(); 1545 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1546 NewType = P->getPointeeType(); 1547 OldType = OldType->castAs<PointerType>()->getPointeeType(); 1548 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1549 NewType = M->getPointeeType(); 1550 OldType = OldType->castAs<MemberPointerType>()->getPointeeType(); 1551 } 1552 1553 if (!NewType->isFunctionProtoType()) 1554 return; 1555 1556 // There's lots of special cases for functions. For function pointers, system 1557 // libraries are hopefully not as broken so that we don't need these 1558 // workarounds. 1559 if (CheckEquivalentExceptionSpec( 1560 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1561 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1562 New->setInvalidDecl(); 1563 } 1564 } 1565 1566 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1567 /// function declaration are well-formed according to C++ 1568 /// [dcl.fct.default]. 1569 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1570 unsigned NumParams = FD->getNumParams(); 1571 unsigned ParamIdx = 0; 1572 1573 // This checking doesn't make sense for explicit specializations; their 1574 // default arguments are determined by the declaration we're specializing, 1575 // not by FD. 1576 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1577 return; 1578 if (auto *FTD = FD->getDescribedFunctionTemplate()) 1579 if (FTD->isMemberSpecialization()) 1580 return; 1581 1582 // Find first parameter with a default argument 1583 for (; ParamIdx < NumParams; ++ParamIdx) { 1584 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1585 if (Param->hasDefaultArg()) 1586 break; 1587 } 1588 1589 // C++20 [dcl.fct.default]p4: 1590 // In a given function declaration, each parameter subsequent to a parameter 1591 // with a default argument shall have a default argument supplied in this or 1592 // a previous declaration, unless the parameter was expanded from a 1593 // parameter pack, or shall be a function parameter pack. 1594 for (; ParamIdx < NumParams; ++ParamIdx) { 1595 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1596 if (!Param->hasDefaultArg() && !Param->isParameterPack() && 1597 !(CurrentInstantiationScope && 1598 CurrentInstantiationScope->isLocalPackExpansion(Param))) { 1599 if (Param->isInvalidDecl()) 1600 /* We already complained about this parameter. */; 1601 else if (Param->getIdentifier()) 1602 Diag(Param->getLocation(), 1603 diag::err_param_default_argument_missing_name) 1604 << Param->getIdentifier(); 1605 else 1606 Diag(Param->getLocation(), 1607 diag::err_param_default_argument_missing); 1608 } 1609 } 1610 } 1611 1612 /// Check that the given type is a literal type. Issue a diagnostic if not, 1613 /// if Kind is Diagnose. 1614 /// \return \c true if a problem has been found (and optionally diagnosed). 1615 template <typename... Ts> 1616 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1617 SourceLocation Loc, QualType T, unsigned DiagID, 1618 Ts &&...DiagArgs) { 1619 if (T->isDependentType()) 1620 return false; 1621 1622 switch (Kind) { 1623 case Sema::CheckConstexprKind::Diagnose: 1624 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1625 std::forward<Ts>(DiagArgs)...); 1626 1627 case Sema::CheckConstexprKind::CheckValid: 1628 return !T->isLiteralType(SemaRef.Context); 1629 } 1630 1631 llvm_unreachable("unknown CheckConstexprKind"); 1632 } 1633 1634 /// Determine whether a destructor cannot be constexpr due to 1635 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, 1636 const CXXDestructorDecl *DD, 1637 Sema::CheckConstexprKind Kind) { 1638 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { 1639 const CXXRecordDecl *RD = 1640 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1641 if (!RD || RD->hasConstexprDestructor()) 1642 return true; 1643 1644 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1645 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) 1646 << static_cast<int>(DD->getConstexprKind()) << !FD 1647 << (FD ? FD->getDeclName() : DeclarationName()) << T; 1648 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) 1649 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; 1650 } 1651 return false; 1652 }; 1653 1654 const CXXRecordDecl *RD = DD->getParent(); 1655 for (const CXXBaseSpecifier &B : RD->bases()) 1656 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) 1657 return false; 1658 for (const FieldDecl *FD : RD->fields()) 1659 if (!Check(FD->getLocation(), FD->getType(), FD)) 1660 return false; 1661 return true; 1662 } 1663 1664 /// Check whether a function's parameter types are all literal types. If so, 1665 /// return true. If not, produce a suitable diagnostic and return false. 1666 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1667 const FunctionDecl *FD, 1668 Sema::CheckConstexprKind Kind) { 1669 unsigned ArgIndex = 0; 1670 const auto *FT = FD->getType()->castAs<FunctionProtoType>(); 1671 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1672 e = FT->param_type_end(); 1673 i != e; ++i, ++ArgIndex) { 1674 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1675 SourceLocation ParamLoc = PD->getLocation(); 1676 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1677 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1678 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1679 FD->isConsteval())) 1680 return false; 1681 } 1682 return true; 1683 } 1684 1685 /// Check whether a function's return type is a literal type. If so, return 1686 /// true. If not, produce a suitable diagnostic and return false. 1687 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, 1688 Sema::CheckConstexprKind Kind) { 1689 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), 1690 diag::err_constexpr_non_literal_return, 1691 FD->isConsteval())) 1692 return false; 1693 return true; 1694 } 1695 1696 /// Get diagnostic %select index for tag kind for 1697 /// record diagnostic message. 1698 /// WARNING: Indexes apply to particular diagnostics only! 1699 /// 1700 /// \returns diagnostic %select index. 1701 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1702 switch (Tag) { 1703 case TTK_Struct: return 0; 1704 case TTK_Interface: return 1; 1705 case TTK_Class: return 2; 1706 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1707 } 1708 } 1709 1710 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1711 Stmt *Body, 1712 Sema::CheckConstexprKind Kind); 1713 1714 // Check whether a function declaration satisfies the requirements of a 1715 // constexpr function definition or a constexpr constructor definition. If so, 1716 // return true. If not, produce appropriate diagnostics (unless asked not to by 1717 // Kind) and return false. 1718 // 1719 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1720 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1721 CheckConstexprKind Kind) { 1722 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1723 if (MD && MD->isInstance()) { 1724 // C++11 [dcl.constexpr]p4: 1725 // The definition of a constexpr constructor shall satisfy the following 1726 // constraints: 1727 // - the class shall not have any virtual base classes; 1728 // 1729 // FIXME: This only applies to constructors and destructors, not arbitrary 1730 // member functions. 1731 const CXXRecordDecl *RD = MD->getParent(); 1732 if (RD->getNumVBases()) { 1733 if (Kind == CheckConstexprKind::CheckValid) 1734 return false; 1735 1736 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1737 << isa<CXXConstructorDecl>(NewFD) 1738 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1739 for (const auto &I : RD->vbases()) 1740 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1741 << I.getSourceRange(); 1742 return false; 1743 } 1744 } 1745 1746 if (!isa<CXXConstructorDecl>(NewFD)) { 1747 // C++11 [dcl.constexpr]p3: 1748 // The definition of a constexpr function shall satisfy the following 1749 // constraints: 1750 // - it shall not be virtual; (removed in C++20) 1751 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1752 if (Method && Method->isVirtual()) { 1753 if (getLangOpts().CPlusPlus20) { 1754 if (Kind == CheckConstexprKind::Diagnose) 1755 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1756 } else { 1757 if (Kind == CheckConstexprKind::CheckValid) 1758 return false; 1759 1760 Method = Method->getCanonicalDecl(); 1761 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1762 1763 // If it's not obvious why this function is virtual, find an overridden 1764 // function which uses the 'virtual' keyword. 1765 const CXXMethodDecl *WrittenVirtual = Method; 1766 while (!WrittenVirtual->isVirtualAsWritten()) 1767 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1768 if (WrittenVirtual != Method) 1769 Diag(WrittenVirtual->getLocation(), 1770 diag::note_overridden_virtual_function); 1771 return false; 1772 } 1773 } 1774 1775 // - its return type shall be a literal type; 1776 if (!CheckConstexprReturnType(*this, NewFD, Kind)) 1777 return false; 1778 } 1779 1780 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { 1781 // A destructor can be constexpr only if the defaulted destructor could be; 1782 // we don't need to check the members and bases if we already know they all 1783 // have constexpr destructors. 1784 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { 1785 if (Kind == CheckConstexprKind::CheckValid) 1786 return false; 1787 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) 1788 return false; 1789 } 1790 } 1791 1792 // - each of its parameter types shall be a literal type; 1793 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1794 return false; 1795 1796 Stmt *Body = NewFD->getBody(); 1797 assert(Body && 1798 "CheckConstexprFunctionDefinition called on function with no body"); 1799 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1800 } 1801 1802 /// Check the given declaration statement is legal within a constexpr function 1803 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1804 /// 1805 /// \return true if the body is OK (maybe only as an extension), false if we 1806 /// have diagnosed a problem. 1807 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1808 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1809 Sema::CheckConstexprKind Kind) { 1810 // C++11 [dcl.constexpr]p3 and p4: 1811 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1812 // contain only 1813 for (const auto *DclIt : DS->decls()) { 1814 switch (DclIt->getKind()) { 1815 case Decl::StaticAssert: 1816 case Decl::Using: 1817 case Decl::UsingShadow: 1818 case Decl::UsingDirective: 1819 case Decl::UnresolvedUsingTypename: 1820 case Decl::UnresolvedUsingValue: 1821 // - static_assert-declarations 1822 // - using-declarations, 1823 // - using-directives, 1824 continue; 1825 1826 case Decl::Typedef: 1827 case Decl::TypeAlias: { 1828 // - typedef declarations and alias-declarations that do not define 1829 // classes or enumerations, 1830 const auto *TN = cast<TypedefNameDecl>(DclIt); 1831 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1832 // Don't allow variably-modified types in constexpr functions. 1833 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1834 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1835 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1836 << TL.getSourceRange() << TL.getType() 1837 << isa<CXXConstructorDecl>(Dcl); 1838 } 1839 return false; 1840 } 1841 continue; 1842 } 1843 1844 case Decl::Enum: 1845 case Decl::CXXRecord: 1846 // C++1y allows types to be defined, not just declared. 1847 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1848 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1849 SemaRef.Diag(DS->getBeginLoc(), 1850 SemaRef.getLangOpts().CPlusPlus14 1851 ? diag::warn_cxx11_compat_constexpr_type_definition 1852 : diag::ext_constexpr_type_definition) 1853 << isa<CXXConstructorDecl>(Dcl); 1854 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1855 return false; 1856 } 1857 } 1858 continue; 1859 1860 case Decl::EnumConstant: 1861 case Decl::IndirectField: 1862 case Decl::ParmVar: 1863 // These can only appear with other declarations which are banned in 1864 // C++11 and permitted in C++1y, so ignore them. 1865 continue; 1866 1867 case Decl::Var: 1868 case Decl::Decomposition: { 1869 // C++1y [dcl.constexpr]p3 allows anything except: 1870 // a definition of a variable of non-literal type or of static or 1871 // thread storage duration or [before C++2a] for which no 1872 // initialization is performed. 1873 const auto *VD = cast<VarDecl>(DclIt); 1874 if (VD->isThisDeclarationADefinition()) { 1875 if (VD->isStaticLocal()) { 1876 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1877 SemaRef.Diag(VD->getLocation(), 1878 diag::err_constexpr_local_var_static) 1879 << isa<CXXConstructorDecl>(Dcl) 1880 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1881 } 1882 return false; 1883 } 1884 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1885 diag::err_constexpr_local_var_non_literal_type, 1886 isa<CXXConstructorDecl>(Dcl))) 1887 return false; 1888 if (!VD->getType()->isDependentType() && 1889 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1890 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1891 SemaRef.Diag( 1892 VD->getLocation(), 1893 SemaRef.getLangOpts().CPlusPlus20 1894 ? diag::warn_cxx17_compat_constexpr_local_var_no_init 1895 : diag::ext_constexpr_local_var_no_init) 1896 << isa<CXXConstructorDecl>(Dcl); 1897 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1898 return false; 1899 } 1900 continue; 1901 } 1902 } 1903 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1904 SemaRef.Diag(VD->getLocation(), 1905 SemaRef.getLangOpts().CPlusPlus14 1906 ? diag::warn_cxx11_compat_constexpr_local_var 1907 : diag::ext_constexpr_local_var) 1908 << isa<CXXConstructorDecl>(Dcl); 1909 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1910 return false; 1911 } 1912 continue; 1913 } 1914 1915 case Decl::NamespaceAlias: 1916 case Decl::Function: 1917 // These are disallowed in C++11 and permitted in C++1y. Allow them 1918 // everywhere as an extension. 1919 if (!Cxx1yLoc.isValid()) 1920 Cxx1yLoc = DS->getBeginLoc(); 1921 continue; 1922 1923 default: 1924 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1925 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1926 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1927 } 1928 return false; 1929 } 1930 } 1931 1932 return true; 1933 } 1934 1935 /// Check that the given field is initialized within a constexpr constructor. 1936 /// 1937 /// \param Dcl The constexpr constructor being checked. 1938 /// \param Field The field being checked. This may be a member of an anonymous 1939 /// struct or union nested within the class being checked. 1940 /// \param Inits All declarations, including anonymous struct/union members and 1941 /// indirect members, for which any initialization was provided. 1942 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1943 /// multiple notes for different members to the same error. 1944 /// \param Kind Whether we're diagnosing a constructor as written or determining 1945 /// whether the formal requirements are satisfied. 1946 /// \return \c false if we're checking for validity and the constructor does 1947 /// not satisfy the requirements on a constexpr constructor. 1948 static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1949 const FunctionDecl *Dcl, 1950 FieldDecl *Field, 1951 llvm::SmallSet<Decl*, 16> &Inits, 1952 bool &Diagnosed, 1953 Sema::CheckConstexprKind Kind) { 1954 // In C++20 onwards, there's nothing to check for validity. 1955 if (Kind == Sema::CheckConstexprKind::CheckValid && 1956 SemaRef.getLangOpts().CPlusPlus20) 1957 return true; 1958 1959 if (Field->isInvalidDecl()) 1960 return true; 1961 1962 if (Field->isUnnamedBitfield()) 1963 return true; 1964 1965 // Anonymous unions with no variant members and empty anonymous structs do not 1966 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1967 // indirect fields don't need initializing. 1968 if (Field->isAnonymousStructOrUnion() && 1969 (Field->getType()->isUnionType() 1970 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1971 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1972 return true; 1973 1974 if (!Inits.count(Field)) { 1975 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1976 if (!Diagnosed) { 1977 SemaRef.Diag(Dcl->getLocation(), 1978 SemaRef.getLangOpts().CPlusPlus20 1979 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init 1980 : diag::ext_constexpr_ctor_missing_init); 1981 Diagnosed = true; 1982 } 1983 SemaRef.Diag(Field->getLocation(), 1984 diag::note_constexpr_ctor_missing_init); 1985 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1986 return false; 1987 } 1988 } else if (Field->isAnonymousStructOrUnion()) { 1989 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1990 for (auto *I : RD->fields()) 1991 // If an anonymous union contains an anonymous struct of which any member 1992 // is initialized, all members must be initialized. 1993 if (!RD->isUnion() || Inits.count(I)) 1994 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 1995 Kind)) 1996 return false; 1997 } 1998 return true; 1999 } 2000 2001 /// Check the provided statement is allowed in a constexpr function 2002 /// definition. 2003 static bool 2004 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 2005 SmallVectorImpl<SourceLocation> &ReturnStmts, 2006 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 2007 Sema::CheckConstexprKind Kind) { 2008 // - its function-body shall be [...] a compound-statement that contains only 2009 switch (S->getStmtClass()) { 2010 case Stmt::NullStmtClass: 2011 // - null statements, 2012 return true; 2013 2014 case Stmt::DeclStmtClass: 2015 // - static_assert-declarations 2016 // - using-declarations, 2017 // - using-directives, 2018 // - typedef declarations and alias-declarations that do not define 2019 // classes or enumerations, 2020 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 2021 return false; 2022 return true; 2023 2024 case Stmt::ReturnStmtClass: 2025 // - and exactly one return statement; 2026 if (isa<CXXConstructorDecl>(Dcl)) { 2027 // C++1y allows return statements in constexpr constructors. 2028 if (!Cxx1yLoc.isValid()) 2029 Cxx1yLoc = S->getBeginLoc(); 2030 return true; 2031 } 2032 2033 ReturnStmts.push_back(S->getBeginLoc()); 2034 return true; 2035 2036 case Stmt::CompoundStmtClass: { 2037 // C++1y allows compound-statements. 2038 if (!Cxx1yLoc.isValid()) 2039 Cxx1yLoc = S->getBeginLoc(); 2040 2041 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2042 for (auto *BodyIt : CompStmt->body()) { 2043 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2044 Cxx1yLoc, Cxx2aLoc, Kind)) 2045 return false; 2046 } 2047 return true; 2048 } 2049 2050 case Stmt::AttributedStmtClass: 2051 if (!Cxx1yLoc.isValid()) 2052 Cxx1yLoc = S->getBeginLoc(); 2053 return true; 2054 2055 case Stmt::IfStmtClass: { 2056 // C++1y allows if-statements. 2057 if (!Cxx1yLoc.isValid()) 2058 Cxx1yLoc = S->getBeginLoc(); 2059 2060 IfStmt *If = cast<IfStmt>(S); 2061 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2062 Cxx1yLoc, Cxx2aLoc, Kind)) 2063 return false; 2064 if (If->getElse() && 2065 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2066 Cxx1yLoc, Cxx2aLoc, Kind)) 2067 return false; 2068 return true; 2069 } 2070 2071 case Stmt::WhileStmtClass: 2072 case Stmt::DoStmtClass: 2073 case Stmt::ForStmtClass: 2074 case Stmt::CXXForRangeStmtClass: 2075 case Stmt::ContinueStmtClass: 2076 // C++1y allows all of these. We don't allow them as extensions in C++11, 2077 // because they don't make sense without variable mutation. 2078 if (!SemaRef.getLangOpts().CPlusPlus14) 2079 break; 2080 if (!Cxx1yLoc.isValid()) 2081 Cxx1yLoc = S->getBeginLoc(); 2082 for (Stmt *SubStmt : S->children()) 2083 if (SubStmt && 2084 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2085 Cxx1yLoc, Cxx2aLoc, Kind)) 2086 return false; 2087 return true; 2088 2089 case Stmt::SwitchStmtClass: 2090 case Stmt::CaseStmtClass: 2091 case Stmt::DefaultStmtClass: 2092 case Stmt::BreakStmtClass: 2093 // C++1y allows switch-statements, and since they don't need variable 2094 // mutation, we can reasonably allow them in C++11 as an extension. 2095 if (!Cxx1yLoc.isValid()) 2096 Cxx1yLoc = S->getBeginLoc(); 2097 for (Stmt *SubStmt : S->children()) 2098 if (SubStmt && 2099 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2100 Cxx1yLoc, Cxx2aLoc, Kind)) 2101 return false; 2102 return true; 2103 2104 case Stmt::GCCAsmStmtClass: 2105 case Stmt::MSAsmStmtClass: 2106 // C++2a allows inline assembly statements. 2107 case Stmt::CXXTryStmtClass: 2108 if (Cxx2aLoc.isInvalid()) 2109 Cxx2aLoc = S->getBeginLoc(); 2110 for (Stmt *SubStmt : S->children()) { 2111 if (SubStmt && 2112 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2113 Cxx1yLoc, Cxx2aLoc, Kind)) 2114 return false; 2115 } 2116 return true; 2117 2118 case Stmt::CXXCatchStmtClass: 2119 // Do not bother checking the language mode (already covered by the 2120 // try block check). 2121 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2122 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2123 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2124 return false; 2125 return true; 2126 2127 default: 2128 if (!isa<Expr>(S)) 2129 break; 2130 2131 // C++1y allows expression-statements. 2132 if (!Cxx1yLoc.isValid()) 2133 Cxx1yLoc = S->getBeginLoc(); 2134 return true; 2135 } 2136 2137 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2138 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2139 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2140 } 2141 return false; 2142 } 2143 2144 /// Check the body for the given constexpr function declaration only contains 2145 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2146 /// 2147 /// \return true if the body is OK, false if we have found or diagnosed a 2148 /// problem. 2149 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2150 Stmt *Body, 2151 Sema::CheckConstexprKind Kind) { 2152 SmallVector<SourceLocation, 4> ReturnStmts; 2153 2154 if (isa<CXXTryStmt>(Body)) { 2155 // C++11 [dcl.constexpr]p3: 2156 // The definition of a constexpr function shall satisfy the following 2157 // constraints: [...] 2158 // - its function-body shall be = delete, = default, or a 2159 // compound-statement 2160 // 2161 // C++11 [dcl.constexpr]p4: 2162 // In the definition of a constexpr constructor, [...] 2163 // - its function-body shall not be a function-try-block; 2164 // 2165 // This restriction is lifted in C++2a, as long as inner statements also 2166 // apply the general constexpr rules. 2167 switch (Kind) { 2168 case Sema::CheckConstexprKind::CheckValid: 2169 if (!SemaRef.getLangOpts().CPlusPlus20) 2170 return false; 2171 break; 2172 2173 case Sema::CheckConstexprKind::Diagnose: 2174 SemaRef.Diag(Body->getBeginLoc(), 2175 !SemaRef.getLangOpts().CPlusPlus20 2176 ? diag::ext_constexpr_function_try_block_cxx20 2177 : diag::warn_cxx17_compat_constexpr_function_try_block) 2178 << isa<CXXConstructorDecl>(Dcl); 2179 break; 2180 } 2181 } 2182 2183 // - its function-body shall be [...] a compound-statement that contains only 2184 // [... list of cases ...] 2185 // 2186 // Note that walking the children here is enough to properly check for 2187 // CompoundStmt and CXXTryStmt body. 2188 SourceLocation Cxx1yLoc, Cxx2aLoc; 2189 for (Stmt *SubStmt : Body->children()) { 2190 if (SubStmt && 2191 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2192 Cxx1yLoc, Cxx2aLoc, Kind)) 2193 return false; 2194 } 2195 2196 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2197 // If this is only valid as an extension, report that we don't satisfy the 2198 // constraints of the current language. 2199 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) || 2200 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2201 return false; 2202 } else if (Cxx2aLoc.isValid()) { 2203 SemaRef.Diag(Cxx2aLoc, 2204 SemaRef.getLangOpts().CPlusPlus20 2205 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2206 : diag::ext_constexpr_body_invalid_stmt_cxx20) 2207 << isa<CXXConstructorDecl>(Dcl); 2208 } else if (Cxx1yLoc.isValid()) { 2209 SemaRef.Diag(Cxx1yLoc, 2210 SemaRef.getLangOpts().CPlusPlus14 2211 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2212 : diag::ext_constexpr_body_invalid_stmt) 2213 << isa<CXXConstructorDecl>(Dcl); 2214 } 2215 2216 if (const CXXConstructorDecl *Constructor 2217 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2218 const CXXRecordDecl *RD = Constructor->getParent(); 2219 // DR1359: 2220 // - every non-variant non-static data member and base class sub-object 2221 // shall be initialized; 2222 // DR1460: 2223 // - if the class is a union having variant members, exactly one of them 2224 // shall be initialized; 2225 if (RD->isUnion()) { 2226 if (Constructor->getNumCtorInitializers() == 0 && 2227 RD->hasVariantMembers()) { 2228 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2229 SemaRef.Diag( 2230 Dcl->getLocation(), 2231 SemaRef.getLangOpts().CPlusPlus20 2232 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2233 : diag::ext_constexpr_union_ctor_no_init); 2234 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2235 return false; 2236 } 2237 } 2238 } else if (!Constructor->isDependentContext() && 2239 !Constructor->isDelegatingConstructor()) { 2240 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2241 2242 // Skip detailed checking if we have enough initializers, and we would 2243 // allow at most one initializer per member. 2244 bool AnyAnonStructUnionMembers = false; 2245 unsigned Fields = 0; 2246 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2247 E = RD->field_end(); I != E; ++I, ++Fields) { 2248 if (I->isAnonymousStructOrUnion()) { 2249 AnyAnonStructUnionMembers = true; 2250 break; 2251 } 2252 } 2253 // DR1460: 2254 // - if the class is a union-like class, but is not a union, for each of 2255 // its anonymous union members having variant members, exactly one of 2256 // them shall be initialized; 2257 if (AnyAnonStructUnionMembers || 2258 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2259 // Check initialization of non-static data members. Base classes are 2260 // always initialized so do not need to be checked. Dependent bases 2261 // might not have initializers in the member initializer list. 2262 llvm::SmallSet<Decl*, 16> Inits; 2263 for (const auto *I: Constructor->inits()) { 2264 if (FieldDecl *FD = I->getMember()) 2265 Inits.insert(FD); 2266 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2267 Inits.insert(ID->chain_begin(), ID->chain_end()); 2268 } 2269 2270 bool Diagnosed = false; 2271 for (auto *I : RD->fields()) 2272 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2273 Kind)) 2274 return false; 2275 } 2276 } 2277 } else { 2278 if (ReturnStmts.empty()) { 2279 // C++1y doesn't require constexpr functions to contain a 'return' 2280 // statement. We still do, unless the return type might be void, because 2281 // otherwise if there's no return statement, the function cannot 2282 // be used in a core constant expression. 2283 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2284 (Dcl->getReturnType()->isVoidType() || 2285 Dcl->getReturnType()->isDependentType()); 2286 switch (Kind) { 2287 case Sema::CheckConstexprKind::Diagnose: 2288 SemaRef.Diag(Dcl->getLocation(), 2289 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2290 : diag::err_constexpr_body_no_return) 2291 << Dcl->isConsteval(); 2292 if (!OK) 2293 return false; 2294 break; 2295 2296 case Sema::CheckConstexprKind::CheckValid: 2297 // The formal requirements don't include this rule in C++14, even 2298 // though the "must be able to produce a constant expression" rules 2299 // still imply it in some cases. 2300 if (!SemaRef.getLangOpts().CPlusPlus14) 2301 return false; 2302 break; 2303 } 2304 } else if (ReturnStmts.size() > 1) { 2305 switch (Kind) { 2306 case Sema::CheckConstexprKind::Diagnose: 2307 SemaRef.Diag( 2308 ReturnStmts.back(), 2309 SemaRef.getLangOpts().CPlusPlus14 2310 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2311 : diag::ext_constexpr_body_multiple_return); 2312 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2313 SemaRef.Diag(ReturnStmts[I], 2314 diag::note_constexpr_body_previous_return); 2315 break; 2316 2317 case Sema::CheckConstexprKind::CheckValid: 2318 if (!SemaRef.getLangOpts().CPlusPlus14) 2319 return false; 2320 break; 2321 } 2322 } 2323 } 2324 2325 // C++11 [dcl.constexpr]p5: 2326 // if no function argument values exist such that the function invocation 2327 // substitution would produce a constant expression, the program is 2328 // ill-formed; no diagnostic required. 2329 // C++11 [dcl.constexpr]p3: 2330 // - every constructor call and implicit conversion used in initializing the 2331 // return value shall be one of those allowed in a constant expression. 2332 // C++11 [dcl.constexpr]p4: 2333 // - every constructor involved in initializing non-static data members and 2334 // base class sub-objects shall be a constexpr constructor. 2335 // 2336 // Note that this rule is distinct from the "requirements for a constexpr 2337 // function", so is not checked in CheckValid mode. 2338 SmallVector<PartialDiagnosticAt, 8> Diags; 2339 if (Kind == Sema::CheckConstexprKind::Diagnose && 2340 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2341 SemaRef.Diag(Dcl->getLocation(), 2342 diag::ext_constexpr_function_never_constant_expr) 2343 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2344 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2345 SemaRef.Diag(Diags[I].first, Diags[I].second); 2346 // Don't return false here: we allow this for compatibility in 2347 // system headers. 2348 } 2349 2350 return true; 2351 } 2352 2353 /// Get the class that is directly named by the current context. This is the 2354 /// class for which an unqualified-id in this scope could name a constructor 2355 /// or destructor. 2356 /// 2357 /// If the scope specifier denotes a class, this will be that class. 2358 /// If the scope specifier is empty, this will be the class whose 2359 /// member-specification we are currently within. Otherwise, there 2360 /// is no such class. 2361 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2362 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2363 2364 if (SS && SS->isInvalid()) 2365 return nullptr; 2366 2367 if (SS && SS->isNotEmpty()) { 2368 DeclContext *DC = computeDeclContext(*SS, true); 2369 return dyn_cast_or_null<CXXRecordDecl>(DC); 2370 } 2371 2372 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2373 } 2374 2375 /// isCurrentClassName - Determine whether the identifier II is the 2376 /// name of the class type currently being defined. In the case of 2377 /// nested classes, this will only return true if II is the name of 2378 /// the innermost class. 2379 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2380 const CXXScopeSpec *SS) { 2381 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2382 return CurDecl && &II == CurDecl->getIdentifier(); 2383 } 2384 2385 /// Determine whether the identifier II is a typo for the name of 2386 /// the class type currently being defined. If so, update it to the identifier 2387 /// that should have been used. 2388 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2389 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2390 2391 if (!getLangOpts().SpellChecking) 2392 return false; 2393 2394 CXXRecordDecl *CurDecl; 2395 if (SS && SS->isSet() && !SS->isInvalid()) { 2396 DeclContext *DC = computeDeclContext(*SS, true); 2397 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2398 } else 2399 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2400 2401 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2402 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2403 < II->getLength()) { 2404 II = CurDecl->getIdentifier(); 2405 return true; 2406 } 2407 2408 return false; 2409 } 2410 2411 /// Determine whether the given class is a base class of the given 2412 /// class, including looking at dependent bases. 2413 static bool findCircularInheritance(const CXXRecordDecl *Class, 2414 const CXXRecordDecl *Current) { 2415 SmallVector<const CXXRecordDecl*, 8> Queue; 2416 2417 Class = Class->getCanonicalDecl(); 2418 while (true) { 2419 for (const auto &I : Current->bases()) { 2420 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2421 if (!Base) 2422 continue; 2423 2424 Base = Base->getDefinition(); 2425 if (!Base) 2426 continue; 2427 2428 if (Base->getCanonicalDecl() == Class) 2429 return true; 2430 2431 Queue.push_back(Base); 2432 } 2433 2434 if (Queue.empty()) 2435 return false; 2436 2437 Current = Queue.pop_back_val(); 2438 } 2439 2440 return false; 2441 } 2442 2443 /// Check the validity of a C++ base class specifier. 2444 /// 2445 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2446 /// and returns NULL otherwise. 2447 CXXBaseSpecifier * 2448 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2449 SourceRange SpecifierRange, 2450 bool Virtual, AccessSpecifier Access, 2451 TypeSourceInfo *TInfo, 2452 SourceLocation EllipsisLoc) { 2453 QualType BaseType = TInfo->getType(); 2454 if (BaseType->containsErrors()) { 2455 // Already emitted a diagnostic when parsing the error type. 2456 return nullptr; 2457 } 2458 // C++ [class.union]p1: 2459 // A union shall not have base classes. 2460 if (Class->isUnion()) { 2461 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2462 << SpecifierRange; 2463 return nullptr; 2464 } 2465 2466 if (EllipsisLoc.isValid() && 2467 !TInfo->getType()->containsUnexpandedParameterPack()) { 2468 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2469 << TInfo->getTypeLoc().getSourceRange(); 2470 EllipsisLoc = SourceLocation(); 2471 } 2472 2473 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2474 2475 if (BaseType->isDependentType()) { 2476 // Make sure that we don't have circular inheritance among our dependent 2477 // bases. For non-dependent bases, the check for completeness below handles 2478 // this. 2479 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2480 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2481 ((BaseDecl = BaseDecl->getDefinition()) && 2482 findCircularInheritance(Class, BaseDecl))) { 2483 Diag(BaseLoc, diag::err_circular_inheritance) 2484 << BaseType << Context.getTypeDeclType(Class); 2485 2486 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2487 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2488 << BaseType; 2489 2490 return nullptr; 2491 } 2492 } 2493 2494 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2495 Class->getTagKind() == TTK_Class, 2496 Access, TInfo, EllipsisLoc); 2497 } 2498 2499 // Base specifiers must be record types. 2500 if (!BaseType->isRecordType()) { 2501 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2502 return nullptr; 2503 } 2504 2505 // C++ [class.union]p1: 2506 // A union shall not be used as a base class. 2507 if (BaseType->isUnionType()) { 2508 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2509 return nullptr; 2510 } 2511 2512 // For the MS ABI, propagate DLL attributes to base class templates. 2513 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2514 if (Attr *ClassAttr = getDLLAttr(Class)) { 2515 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2516 BaseType->getAsCXXRecordDecl())) { 2517 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2518 BaseLoc); 2519 } 2520 } 2521 } 2522 2523 // C++ [class.derived]p2: 2524 // The class-name in a base-specifier shall not be an incompletely 2525 // defined class. 2526 if (RequireCompleteType(BaseLoc, BaseType, 2527 diag::err_incomplete_base_class, SpecifierRange)) { 2528 Class->setInvalidDecl(); 2529 return nullptr; 2530 } 2531 2532 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2533 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2534 assert(BaseDecl && "Record type has no declaration"); 2535 BaseDecl = BaseDecl->getDefinition(); 2536 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2537 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2538 assert(CXXBaseDecl && "Base type is not a C++ type"); 2539 2540 // Microsoft docs say: 2541 // "If a base-class has a code_seg attribute, derived classes must have the 2542 // same attribute." 2543 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2544 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2545 if ((DerivedCSA || BaseCSA) && 2546 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2547 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2548 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2549 << CXXBaseDecl; 2550 return nullptr; 2551 } 2552 2553 // A class which contains a flexible array member is not suitable for use as a 2554 // base class: 2555 // - If the layout determines that a base comes before another base, 2556 // the flexible array member would index into the subsequent base. 2557 // - If the layout determines that base comes before the derived class, 2558 // the flexible array member would index into the derived class. 2559 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2560 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2561 << CXXBaseDecl->getDeclName(); 2562 return nullptr; 2563 } 2564 2565 // C++ [class]p3: 2566 // If a class is marked final and it appears as a base-type-specifier in 2567 // base-clause, the program is ill-formed. 2568 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2569 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2570 << CXXBaseDecl->getDeclName() 2571 << FA->isSpelledAsSealed(); 2572 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2573 << CXXBaseDecl->getDeclName() << FA->getRange(); 2574 return nullptr; 2575 } 2576 2577 if (BaseDecl->isInvalidDecl()) 2578 Class->setInvalidDecl(); 2579 2580 // Create the base specifier. 2581 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2582 Class->getTagKind() == TTK_Class, 2583 Access, TInfo, EllipsisLoc); 2584 } 2585 2586 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2587 /// one entry in the base class list of a class specifier, for 2588 /// example: 2589 /// class foo : public bar, virtual private baz { 2590 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2591 BaseResult 2592 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2593 ParsedAttributes &Attributes, 2594 bool Virtual, AccessSpecifier Access, 2595 ParsedType basetype, SourceLocation BaseLoc, 2596 SourceLocation EllipsisLoc) { 2597 if (!classdecl) 2598 return true; 2599 2600 AdjustDeclIfTemplate(classdecl); 2601 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2602 if (!Class) 2603 return true; 2604 2605 // We haven't yet attached the base specifiers. 2606 Class->setIsParsingBaseSpecifiers(); 2607 2608 // We do not support any C++11 attributes on base-specifiers yet. 2609 // Diagnose any attributes we see. 2610 for (const ParsedAttr &AL : Attributes) { 2611 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2612 continue; 2613 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2614 ? (unsigned)diag::warn_unknown_attribute_ignored 2615 : (unsigned)diag::err_base_specifier_attribute) 2616 << AL << AL.getRange(); 2617 } 2618 2619 TypeSourceInfo *TInfo = nullptr; 2620 GetTypeFromParser(basetype, &TInfo); 2621 2622 if (EllipsisLoc.isInvalid() && 2623 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2624 UPPC_BaseType)) 2625 return true; 2626 2627 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2628 Virtual, Access, TInfo, 2629 EllipsisLoc)) 2630 return BaseSpec; 2631 else 2632 Class->setInvalidDecl(); 2633 2634 return true; 2635 } 2636 2637 /// Use small set to collect indirect bases. As this is only used 2638 /// locally, there's no need to abstract the small size parameter. 2639 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2640 2641 /// Recursively add the bases of Type. Don't add Type itself. 2642 static void 2643 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2644 const QualType &Type) 2645 { 2646 // Even though the incoming type is a base, it might not be 2647 // a class -- it could be a template parm, for instance. 2648 if (auto Rec = Type->getAs<RecordType>()) { 2649 auto Decl = Rec->getAsCXXRecordDecl(); 2650 2651 // Iterate over its bases. 2652 for (const auto &BaseSpec : Decl->bases()) { 2653 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2654 .getUnqualifiedType(); 2655 if (Set.insert(Base).second) 2656 // If we've not already seen it, recurse. 2657 NoteIndirectBases(Context, Set, Base); 2658 } 2659 } 2660 } 2661 2662 /// Performs the actual work of attaching the given base class 2663 /// specifiers to a C++ class. 2664 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2665 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2666 if (Bases.empty()) 2667 return false; 2668 2669 // Used to keep track of which base types we have already seen, so 2670 // that we can properly diagnose redundant direct base types. Note 2671 // that the key is always the unqualified canonical type of the base 2672 // class. 2673 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2674 2675 // Used to track indirect bases so we can see if a direct base is 2676 // ambiguous. 2677 IndirectBaseSet IndirectBaseTypes; 2678 2679 // Copy non-redundant base specifiers into permanent storage. 2680 unsigned NumGoodBases = 0; 2681 bool Invalid = false; 2682 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2683 QualType NewBaseType 2684 = Context.getCanonicalType(Bases[idx]->getType()); 2685 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2686 2687 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2688 if (KnownBase) { 2689 // C++ [class.mi]p3: 2690 // A class shall not be specified as a direct base class of a 2691 // derived class more than once. 2692 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2693 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2694 2695 // Delete the duplicate base class specifier; we're going to 2696 // overwrite its pointer later. 2697 Context.Deallocate(Bases[idx]); 2698 2699 Invalid = true; 2700 } else { 2701 // Okay, add this new base class. 2702 KnownBase = Bases[idx]; 2703 Bases[NumGoodBases++] = Bases[idx]; 2704 2705 // Note this base's direct & indirect bases, if there could be ambiguity. 2706 if (Bases.size() > 1) 2707 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2708 2709 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2710 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2711 if (Class->isInterface() && 2712 (!RD->isInterfaceLike() || 2713 KnownBase->getAccessSpecifier() != AS_public)) { 2714 // The Microsoft extension __interface does not permit bases that 2715 // are not themselves public interfaces. 2716 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2717 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2718 << RD->getSourceRange(); 2719 Invalid = true; 2720 } 2721 if (RD->hasAttr<WeakAttr>()) 2722 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2723 } 2724 } 2725 } 2726 2727 // Attach the remaining base class specifiers to the derived class. 2728 Class->setBases(Bases.data(), NumGoodBases); 2729 2730 // Check that the only base classes that are duplicate are virtual. 2731 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2732 // Check whether this direct base is inaccessible due to ambiguity. 2733 QualType BaseType = Bases[idx]->getType(); 2734 2735 // Skip all dependent types in templates being used as base specifiers. 2736 // Checks below assume that the base specifier is a CXXRecord. 2737 if (BaseType->isDependentType()) 2738 continue; 2739 2740 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2741 .getUnqualifiedType(); 2742 2743 if (IndirectBaseTypes.count(CanonicalBase)) { 2744 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2745 /*DetectVirtual=*/true); 2746 bool found 2747 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2748 assert(found); 2749 (void)found; 2750 2751 if (Paths.isAmbiguous(CanonicalBase)) 2752 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2753 << BaseType << getAmbiguousPathsDisplayString(Paths) 2754 << Bases[idx]->getSourceRange(); 2755 else 2756 assert(Bases[idx]->isVirtual()); 2757 } 2758 2759 // Delete the base class specifier, since its data has been copied 2760 // into the CXXRecordDecl. 2761 Context.Deallocate(Bases[idx]); 2762 } 2763 2764 return Invalid; 2765 } 2766 2767 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2768 /// class, after checking whether there are any duplicate base 2769 /// classes. 2770 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2771 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2772 if (!ClassDecl || Bases.empty()) 2773 return; 2774 2775 AdjustDeclIfTemplate(ClassDecl); 2776 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2777 } 2778 2779 /// Determine whether the type \p Derived is a C++ class that is 2780 /// derived from the type \p Base. 2781 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2782 if (!getLangOpts().CPlusPlus) 2783 return false; 2784 2785 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2786 if (!DerivedRD) 2787 return false; 2788 2789 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2790 if (!BaseRD) 2791 return false; 2792 2793 // If either the base or the derived type is invalid, don't try to 2794 // check whether one is derived from the other. 2795 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2796 return false; 2797 2798 // FIXME: In a modules build, do we need the entire path to be visible for us 2799 // to be able to use the inheritance relationship? 2800 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2801 return false; 2802 2803 return DerivedRD->isDerivedFrom(BaseRD); 2804 } 2805 2806 /// Determine whether the type \p Derived is a C++ class that is 2807 /// derived from the type \p Base. 2808 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2809 CXXBasePaths &Paths) { 2810 if (!getLangOpts().CPlusPlus) 2811 return false; 2812 2813 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2814 if (!DerivedRD) 2815 return false; 2816 2817 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2818 if (!BaseRD) 2819 return false; 2820 2821 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2822 return false; 2823 2824 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2825 } 2826 2827 static void BuildBasePathArray(const CXXBasePath &Path, 2828 CXXCastPath &BasePathArray) { 2829 // We first go backward and check if we have a virtual base. 2830 // FIXME: It would be better if CXXBasePath had the base specifier for 2831 // the nearest virtual base. 2832 unsigned Start = 0; 2833 for (unsigned I = Path.size(); I != 0; --I) { 2834 if (Path[I - 1].Base->isVirtual()) { 2835 Start = I - 1; 2836 break; 2837 } 2838 } 2839 2840 // Now add all bases. 2841 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2842 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2843 } 2844 2845 2846 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2847 CXXCastPath &BasePathArray) { 2848 assert(BasePathArray.empty() && "Base path array must be empty!"); 2849 assert(Paths.isRecordingPaths() && "Must record paths!"); 2850 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2851 } 2852 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2853 /// conversion (where Derived and Base are class types) is 2854 /// well-formed, meaning that the conversion is unambiguous (and 2855 /// that all of the base classes are accessible). Returns true 2856 /// and emits a diagnostic if the code is ill-formed, returns false 2857 /// otherwise. Loc is the location where this routine should point to 2858 /// if there is an error, and Range is the source range to highlight 2859 /// if there is an error. 2860 /// 2861 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the 2862 /// diagnostic for the respective type of error will be suppressed, but the 2863 /// check for ill-formed code will still be performed. 2864 bool 2865 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2866 unsigned InaccessibleBaseID, 2867 unsigned AmbiguousBaseConvID, 2868 SourceLocation Loc, SourceRange Range, 2869 DeclarationName Name, 2870 CXXCastPath *BasePath, 2871 bool IgnoreAccess) { 2872 // First, determine whether the path from Derived to Base is 2873 // ambiguous. This is slightly more expensive than checking whether 2874 // the Derived to Base conversion exists, because here we need to 2875 // explore multiple paths to determine if there is an ambiguity. 2876 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2877 /*DetectVirtual=*/false); 2878 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2879 if (!DerivationOkay) 2880 return true; 2881 2882 const CXXBasePath *Path = nullptr; 2883 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2884 Path = &Paths.front(); 2885 2886 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2887 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2888 // user to access such bases. 2889 if (!Path && getLangOpts().MSVCCompat) { 2890 for (const CXXBasePath &PossiblePath : Paths) { 2891 if (PossiblePath.size() == 1) { 2892 Path = &PossiblePath; 2893 if (AmbiguousBaseConvID) 2894 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2895 << Base << Derived << Range; 2896 break; 2897 } 2898 } 2899 } 2900 2901 if (Path) { 2902 if (!IgnoreAccess) { 2903 // Check that the base class can be accessed. 2904 switch ( 2905 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2906 case AR_inaccessible: 2907 return true; 2908 case AR_accessible: 2909 case AR_dependent: 2910 case AR_delayed: 2911 break; 2912 } 2913 } 2914 2915 // Build a base path if necessary. 2916 if (BasePath) 2917 ::BuildBasePathArray(*Path, *BasePath); 2918 return false; 2919 } 2920 2921 if (AmbiguousBaseConvID) { 2922 // We know that the derived-to-base conversion is ambiguous, and 2923 // we're going to produce a diagnostic. Perform the derived-to-base 2924 // search just one more time to compute all of the possible paths so 2925 // that we can print them out. This is more expensive than any of 2926 // the previous derived-to-base checks we've done, but at this point 2927 // performance isn't as much of an issue. 2928 Paths.clear(); 2929 Paths.setRecordingPaths(true); 2930 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2931 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2932 (void)StillOkay; 2933 2934 // Build up a textual representation of the ambiguous paths, e.g., 2935 // D -> B -> A, that will be used to illustrate the ambiguous 2936 // conversions in the diagnostic. We only print one of the paths 2937 // to each base class subobject. 2938 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2939 2940 Diag(Loc, AmbiguousBaseConvID) 2941 << Derived << Base << PathDisplayStr << Range << Name; 2942 } 2943 return true; 2944 } 2945 2946 bool 2947 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2948 SourceLocation Loc, SourceRange Range, 2949 CXXCastPath *BasePath, 2950 bool IgnoreAccess) { 2951 return CheckDerivedToBaseConversion( 2952 Derived, Base, diag::err_upcast_to_inaccessible_base, 2953 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2954 BasePath, IgnoreAccess); 2955 } 2956 2957 2958 /// Builds a string representing ambiguous paths from a 2959 /// specific derived class to different subobjects of the same base 2960 /// class. 2961 /// 2962 /// This function builds a string that can be used in error messages 2963 /// to show the different paths that one can take through the 2964 /// inheritance hierarchy to go from the derived class to different 2965 /// subobjects of a base class. The result looks something like this: 2966 /// @code 2967 /// struct D -> struct B -> struct A 2968 /// struct D -> struct C -> struct A 2969 /// @endcode 2970 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2971 std::string PathDisplayStr; 2972 std::set<unsigned> DisplayedPaths; 2973 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2974 Path != Paths.end(); ++Path) { 2975 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2976 // We haven't displayed a path to this particular base 2977 // class subobject yet. 2978 PathDisplayStr += "\n "; 2979 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2980 for (CXXBasePath::const_iterator Element = Path->begin(); 2981 Element != Path->end(); ++Element) 2982 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2983 } 2984 } 2985 2986 return PathDisplayStr; 2987 } 2988 2989 //===----------------------------------------------------------------------===// 2990 // C++ class member Handling 2991 //===----------------------------------------------------------------------===// 2992 2993 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2994 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 2995 SourceLocation ColonLoc, 2996 const ParsedAttributesView &Attrs) { 2997 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2998 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2999 ASLoc, ColonLoc); 3000 CurContext->addHiddenDecl(ASDecl); 3001 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 3002 } 3003 3004 /// CheckOverrideControl - Check C++11 override control semantics. 3005 void Sema::CheckOverrideControl(NamedDecl *D) { 3006 if (D->isInvalidDecl()) 3007 return; 3008 3009 // We only care about "override" and "final" declarations. 3010 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 3011 return; 3012 3013 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3014 3015 // We can't check dependent instance methods. 3016 if (MD && MD->isInstance() && 3017 (MD->getParent()->hasAnyDependentBases() || 3018 MD->getType()->isDependentType())) 3019 return; 3020 3021 if (MD && !MD->isVirtual()) { 3022 // If we have a non-virtual method, check if if hides a virtual method. 3023 // (In that case, it's most likely the method has the wrong type.) 3024 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 3025 FindHiddenVirtualMethods(MD, OverloadedMethods); 3026 3027 if (!OverloadedMethods.empty()) { 3028 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3029 Diag(OA->getLocation(), 3030 diag::override_keyword_hides_virtual_member_function) 3031 << "override" << (OverloadedMethods.size() > 1); 3032 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3033 Diag(FA->getLocation(), 3034 diag::override_keyword_hides_virtual_member_function) 3035 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3036 << (OverloadedMethods.size() > 1); 3037 } 3038 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3039 MD->setInvalidDecl(); 3040 return; 3041 } 3042 // Fall through into the general case diagnostic. 3043 // FIXME: We might want to attempt typo correction here. 3044 } 3045 3046 if (!MD || !MD->isVirtual()) { 3047 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3048 Diag(OA->getLocation(), 3049 diag::override_keyword_only_allowed_on_virtual_member_functions) 3050 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3051 D->dropAttr<OverrideAttr>(); 3052 } 3053 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3054 Diag(FA->getLocation(), 3055 diag::override_keyword_only_allowed_on_virtual_member_functions) 3056 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3057 << FixItHint::CreateRemoval(FA->getLocation()); 3058 D->dropAttr<FinalAttr>(); 3059 } 3060 return; 3061 } 3062 3063 // C++11 [class.virtual]p5: 3064 // If a function is marked with the virt-specifier override and 3065 // does not override a member function of a base class, the program is 3066 // ill-formed. 3067 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3068 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3069 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3070 << MD->getDeclName(); 3071 } 3072 3073 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { 3074 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3075 return; 3076 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3077 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3078 return; 3079 3080 SourceLocation Loc = MD->getLocation(); 3081 SourceLocation SpellingLoc = Loc; 3082 if (getSourceManager().isMacroArgExpansion(Loc)) 3083 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3084 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3085 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3086 return; 3087 3088 if (MD->size_overridden_methods() > 0) { 3089 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { 3090 unsigned DiagID = 3091 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation()) 3092 ? DiagInconsistent 3093 : DiagSuggest; 3094 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3095 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3096 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3097 }; 3098 if (isa<CXXDestructorDecl>(MD)) 3099 EmitDiag( 3100 diag::warn_inconsistent_destructor_marked_not_override_overriding, 3101 diag::warn_suggest_destructor_marked_not_override_overriding); 3102 else 3103 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding, 3104 diag::warn_suggest_function_marked_not_override_overriding); 3105 } 3106 } 3107 3108 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3109 /// function overrides a virtual member function marked 'final', according to 3110 /// C++11 [class.virtual]p4. 3111 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3112 const CXXMethodDecl *Old) { 3113 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3114 if (!FA) 3115 return false; 3116 3117 Diag(New->getLocation(), diag::err_final_function_overridden) 3118 << New->getDeclName() 3119 << FA->isSpelledAsSealed(); 3120 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3121 return true; 3122 } 3123 3124 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3125 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3126 // FIXME: Destruction of ObjC lifetime types has side-effects. 3127 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3128 return !RD->isCompleteDefinition() || 3129 !RD->hasTrivialDefaultConstructor() || 3130 !RD->hasTrivialDestructor(); 3131 return false; 3132 } 3133 3134 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3135 ParsedAttributesView::const_iterator Itr = 3136 llvm::find_if(list, [](const ParsedAttr &AL) { 3137 return AL.isDeclspecPropertyAttribute(); 3138 }); 3139 if (Itr != list.end()) 3140 return &*Itr; 3141 return nullptr; 3142 } 3143 3144 // Check if there is a field shadowing. 3145 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3146 DeclarationName FieldName, 3147 const CXXRecordDecl *RD, 3148 bool DeclIsField) { 3149 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3150 return; 3151 3152 // To record a shadowed field in a base 3153 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3154 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3155 CXXBasePath &Path) { 3156 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3157 // Record an ambiguous path directly 3158 if (Bases.find(Base) != Bases.end()) 3159 return true; 3160 for (const auto Field : Base->lookup(FieldName)) { 3161 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3162 Field->getAccess() != AS_private) { 3163 assert(Field->getAccess() != AS_none); 3164 assert(Bases.find(Base) == Bases.end()); 3165 Bases[Base] = Field; 3166 return true; 3167 } 3168 } 3169 return false; 3170 }; 3171 3172 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3173 /*DetectVirtual=*/true); 3174 if (!RD->lookupInBases(FieldShadowed, Paths)) 3175 return; 3176 3177 for (const auto &P : Paths) { 3178 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3179 auto It = Bases.find(Base); 3180 // Skip duplicated bases 3181 if (It == Bases.end()) 3182 continue; 3183 auto BaseField = It->second; 3184 assert(BaseField->getAccess() != AS_private); 3185 if (AS_none != 3186 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3187 Diag(Loc, diag::warn_shadow_field) 3188 << FieldName << RD << Base << DeclIsField; 3189 Diag(BaseField->getLocation(), diag::note_shadow_field); 3190 Bases.erase(It); 3191 } 3192 } 3193 } 3194 3195 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3196 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3197 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3198 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3199 /// present (but parsing it has been deferred). 3200 NamedDecl * 3201 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3202 MultiTemplateParamsArg TemplateParameterLists, 3203 Expr *BW, const VirtSpecifiers &VS, 3204 InClassInitStyle InitStyle) { 3205 const DeclSpec &DS = D.getDeclSpec(); 3206 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3207 DeclarationName Name = NameInfo.getName(); 3208 SourceLocation Loc = NameInfo.getLoc(); 3209 3210 // For anonymous bitfields, the location should point to the type. 3211 if (Loc.isInvalid()) 3212 Loc = D.getBeginLoc(); 3213 3214 Expr *BitWidth = static_cast<Expr*>(BW); 3215 3216 assert(isa<CXXRecordDecl>(CurContext)); 3217 assert(!DS.isFriendSpecified()); 3218 3219 bool isFunc = D.isDeclarationOfFunction(); 3220 const ParsedAttr *MSPropertyAttr = 3221 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3222 3223 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3224 // The Microsoft extension __interface only permits public member functions 3225 // and prohibits constructors, destructors, operators, non-public member 3226 // functions, static methods and data members. 3227 unsigned InvalidDecl; 3228 bool ShowDeclName = true; 3229 if (!isFunc && 3230 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3231 InvalidDecl = 0; 3232 else if (!isFunc) 3233 InvalidDecl = 1; 3234 else if (AS != AS_public) 3235 InvalidDecl = 2; 3236 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3237 InvalidDecl = 3; 3238 else switch (Name.getNameKind()) { 3239 case DeclarationName::CXXConstructorName: 3240 InvalidDecl = 4; 3241 ShowDeclName = false; 3242 break; 3243 3244 case DeclarationName::CXXDestructorName: 3245 InvalidDecl = 5; 3246 ShowDeclName = false; 3247 break; 3248 3249 case DeclarationName::CXXOperatorName: 3250 case DeclarationName::CXXConversionFunctionName: 3251 InvalidDecl = 6; 3252 break; 3253 3254 default: 3255 InvalidDecl = 0; 3256 break; 3257 } 3258 3259 if (InvalidDecl) { 3260 if (ShowDeclName) 3261 Diag(Loc, diag::err_invalid_member_in_interface) 3262 << (InvalidDecl-1) << Name; 3263 else 3264 Diag(Loc, diag::err_invalid_member_in_interface) 3265 << (InvalidDecl-1) << ""; 3266 return nullptr; 3267 } 3268 } 3269 3270 // C++ 9.2p6: A member shall not be declared to have automatic storage 3271 // duration (auto, register) or with the extern storage-class-specifier. 3272 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3273 // data members and cannot be applied to names declared const or static, 3274 // and cannot be applied to reference members. 3275 switch (DS.getStorageClassSpec()) { 3276 case DeclSpec::SCS_unspecified: 3277 case DeclSpec::SCS_typedef: 3278 case DeclSpec::SCS_static: 3279 break; 3280 case DeclSpec::SCS_mutable: 3281 if (isFunc) { 3282 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3283 3284 // FIXME: It would be nicer if the keyword was ignored only for this 3285 // declarator. Otherwise we could get follow-up errors. 3286 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3287 } 3288 break; 3289 default: 3290 Diag(DS.getStorageClassSpecLoc(), 3291 diag::err_storageclass_invalid_for_member); 3292 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3293 break; 3294 } 3295 3296 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3297 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3298 !isFunc); 3299 3300 if (DS.hasConstexprSpecifier() && isInstField) { 3301 SemaDiagnosticBuilder B = 3302 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3303 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3304 if (InitStyle == ICIS_NoInit) { 3305 B << 0 << 0; 3306 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3307 B << FixItHint::CreateRemoval(ConstexprLoc); 3308 else { 3309 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3310 D.getMutableDeclSpec().ClearConstexprSpec(); 3311 const char *PrevSpec; 3312 unsigned DiagID; 3313 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3314 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3315 (void)Failed; 3316 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3317 } 3318 } else { 3319 B << 1; 3320 const char *PrevSpec; 3321 unsigned DiagID; 3322 if (D.getMutableDeclSpec().SetStorageClassSpec( 3323 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3324 Context.getPrintingPolicy())) { 3325 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3326 "This is the only DeclSpec that should fail to be applied"); 3327 B << 1; 3328 } else { 3329 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3330 isInstField = false; 3331 } 3332 } 3333 } 3334 3335 NamedDecl *Member; 3336 if (isInstField) { 3337 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3338 3339 // Data members must have identifiers for names. 3340 if (!Name.isIdentifier()) { 3341 Diag(Loc, diag::err_bad_variable_name) 3342 << Name; 3343 return nullptr; 3344 } 3345 3346 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3347 3348 // Member field could not be with "template" keyword. 3349 // So TemplateParameterLists should be empty in this case. 3350 if (TemplateParameterLists.size()) { 3351 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3352 if (TemplateParams->size()) { 3353 // There is no such thing as a member field template. 3354 Diag(D.getIdentifierLoc(), diag::err_template_member) 3355 << II 3356 << SourceRange(TemplateParams->getTemplateLoc(), 3357 TemplateParams->getRAngleLoc()); 3358 } else { 3359 // There is an extraneous 'template<>' for this member. 3360 Diag(TemplateParams->getTemplateLoc(), 3361 diag::err_template_member_noparams) 3362 << II 3363 << SourceRange(TemplateParams->getTemplateLoc(), 3364 TemplateParams->getRAngleLoc()); 3365 } 3366 return nullptr; 3367 } 3368 3369 if (SS.isSet() && !SS.isInvalid()) { 3370 // The user provided a superfluous scope specifier inside a class 3371 // definition: 3372 // 3373 // class X { 3374 // int X::member; 3375 // }; 3376 if (DeclContext *DC = computeDeclContext(SS, false)) 3377 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3378 D.getName().getKind() == 3379 UnqualifiedIdKind::IK_TemplateId); 3380 else 3381 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3382 << Name << SS.getRange(); 3383 3384 SS.clear(); 3385 } 3386 3387 if (MSPropertyAttr) { 3388 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3389 BitWidth, InitStyle, AS, *MSPropertyAttr); 3390 if (!Member) 3391 return nullptr; 3392 isInstField = false; 3393 } else { 3394 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3395 BitWidth, InitStyle, AS); 3396 if (!Member) 3397 return nullptr; 3398 } 3399 3400 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3401 } else { 3402 Member = HandleDeclarator(S, D, TemplateParameterLists); 3403 if (!Member) 3404 return nullptr; 3405 3406 // Non-instance-fields can't have a bitfield. 3407 if (BitWidth) { 3408 if (Member->isInvalidDecl()) { 3409 // don't emit another diagnostic. 3410 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3411 // C++ 9.6p3: A bit-field shall not be a static member. 3412 // "static member 'A' cannot be a bit-field" 3413 Diag(Loc, diag::err_static_not_bitfield) 3414 << Name << BitWidth->getSourceRange(); 3415 } else if (isa<TypedefDecl>(Member)) { 3416 // "typedef member 'x' cannot be a bit-field" 3417 Diag(Loc, diag::err_typedef_not_bitfield) 3418 << Name << BitWidth->getSourceRange(); 3419 } else { 3420 // A function typedef ("typedef int f(); f a;"). 3421 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3422 Diag(Loc, diag::err_not_integral_type_bitfield) 3423 << Name << cast<ValueDecl>(Member)->getType() 3424 << BitWidth->getSourceRange(); 3425 } 3426 3427 BitWidth = nullptr; 3428 Member->setInvalidDecl(); 3429 } 3430 3431 NamedDecl *NonTemplateMember = Member; 3432 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3433 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3434 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3435 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3436 3437 Member->setAccess(AS); 3438 3439 // If we have declared a member function template or static data member 3440 // template, set the access of the templated declaration as well. 3441 if (NonTemplateMember != Member) 3442 NonTemplateMember->setAccess(AS); 3443 3444 // C++ [temp.deduct.guide]p3: 3445 // A deduction guide [...] for a member class template [shall be 3446 // declared] with the same access [as the template]. 3447 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3448 auto *TD = DG->getDeducedTemplate(); 3449 // Access specifiers are only meaningful if both the template and the 3450 // deduction guide are from the same scope. 3451 if (AS != TD->getAccess() && 3452 TD->getDeclContext()->getRedeclContext()->Equals( 3453 DG->getDeclContext()->getRedeclContext())) { 3454 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3455 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3456 << TD->getAccess(); 3457 const AccessSpecDecl *LastAccessSpec = nullptr; 3458 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3459 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3460 LastAccessSpec = AccessSpec; 3461 } 3462 assert(LastAccessSpec && "differing access with no access specifier"); 3463 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3464 << AS; 3465 } 3466 } 3467 } 3468 3469 if (VS.isOverrideSpecified()) 3470 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3471 AttributeCommonInfo::AS_Keyword)); 3472 if (VS.isFinalSpecified()) 3473 Member->addAttr(FinalAttr::Create( 3474 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3475 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3476 3477 if (VS.getLastLocation().isValid()) { 3478 // Update the end location of a method that has a virt-specifiers. 3479 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3480 MD->setRangeEnd(VS.getLastLocation()); 3481 } 3482 3483 CheckOverrideControl(Member); 3484 3485 assert((Name || isInstField) && "No identifier for non-field ?"); 3486 3487 if (isInstField) { 3488 FieldDecl *FD = cast<FieldDecl>(Member); 3489 FieldCollector->Add(FD); 3490 3491 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3492 // Remember all explicit private FieldDecls that have a name, no side 3493 // effects and are not part of a dependent type declaration. 3494 if (!FD->isImplicit() && FD->getDeclName() && 3495 FD->getAccess() == AS_private && 3496 !FD->hasAttr<UnusedAttr>() && 3497 !FD->getParent()->isDependentContext() && 3498 !InitializationHasSideEffects(*FD)) 3499 UnusedPrivateFields.insert(FD); 3500 } 3501 } 3502 3503 return Member; 3504 } 3505 3506 namespace { 3507 class UninitializedFieldVisitor 3508 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3509 Sema &S; 3510 // List of Decls to generate a warning on. Also remove Decls that become 3511 // initialized. 3512 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3513 // List of base classes of the record. Classes are removed after their 3514 // initializers. 3515 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3516 // Vector of decls to be removed from the Decl set prior to visiting the 3517 // nodes. These Decls may have been initialized in the prior initializer. 3518 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3519 // If non-null, add a note to the warning pointing back to the constructor. 3520 const CXXConstructorDecl *Constructor; 3521 // Variables to hold state when processing an initializer list. When 3522 // InitList is true, special case initialization of FieldDecls matching 3523 // InitListFieldDecl. 3524 bool InitList; 3525 FieldDecl *InitListFieldDecl; 3526 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3527 3528 public: 3529 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3530 UninitializedFieldVisitor(Sema &S, 3531 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3532 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3533 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3534 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3535 3536 // Returns true if the use of ME is not an uninitialized use. 3537 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3538 bool CheckReferenceOnly) { 3539 llvm::SmallVector<FieldDecl*, 4> Fields; 3540 bool ReferenceField = false; 3541 while (ME) { 3542 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3543 if (!FD) 3544 return false; 3545 Fields.push_back(FD); 3546 if (FD->getType()->isReferenceType()) 3547 ReferenceField = true; 3548 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3549 } 3550 3551 // Binding a reference to an uninitialized field is not an 3552 // uninitialized use. 3553 if (CheckReferenceOnly && !ReferenceField) 3554 return true; 3555 3556 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3557 // Discard the first field since it is the field decl that is being 3558 // initialized. 3559 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3560 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3561 } 3562 3563 for (auto UsedIter = UsedFieldIndex.begin(), 3564 UsedEnd = UsedFieldIndex.end(), 3565 OrigIter = InitFieldIndex.begin(), 3566 OrigEnd = InitFieldIndex.end(); 3567 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3568 if (*UsedIter < *OrigIter) 3569 return true; 3570 if (*UsedIter > *OrigIter) 3571 break; 3572 } 3573 3574 return false; 3575 } 3576 3577 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3578 bool AddressOf) { 3579 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3580 return; 3581 3582 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3583 // or union. 3584 MemberExpr *FieldME = ME; 3585 3586 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3587 3588 Expr *Base = ME; 3589 while (MemberExpr *SubME = 3590 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3591 3592 if (isa<VarDecl>(SubME->getMemberDecl())) 3593 return; 3594 3595 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3596 if (!FD->isAnonymousStructOrUnion()) 3597 FieldME = SubME; 3598 3599 if (!FieldME->getType().isPODType(S.Context)) 3600 AllPODFields = false; 3601 3602 Base = SubME->getBase(); 3603 } 3604 3605 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) { 3606 Visit(Base); 3607 return; 3608 } 3609 3610 if (AddressOf && AllPODFields) 3611 return; 3612 3613 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3614 3615 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3616 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3617 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3618 } 3619 3620 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3621 QualType T = BaseCast->getType(); 3622 if (T->isPointerType() && 3623 BaseClasses.count(T->getPointeeType())) { 3624 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3625 << T->getPointeeType() << FoundVD; 3626 } 3627 } 3628 } 3629 3630 if (!Decls.count(FoundVD)) 3631 return; 3632 3633 const bool IsReference = FoundVD->getType()->isReferenceType(); 3634 3635 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3636 // Special checking for initializer lists. 3637 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3638 return; 3639 } 3640 } else { 3641 // Prevent double warnings on use of unbounded references. 3642 if (CheckReferenceOnly && !IsReference) 3643 return; 3644 } 3645 3646 unsigned diag = IsReference 3647 ? diag::warn_reference_field_is_uninit 3648 : diag::warn_field_is_uninit; 3649 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3650 if (Constructor) 3651 S.Diag(Constructor->getLocation(), 3652 diag::note_uninit_in_this_constructor) 3653 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3654 3655 } 3656 3657 void HandleValue(Expr *E, bool AddressOf) { 3658 E = E->IgnoreParens(); 3659 3660 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3661 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3662 AddressOf /*AddressOf*/); 3663 return; 3664 } 3665 3666 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3667 Visit(CO->getCond()); 3668 HandleValue(CO->getTrueExpr(), AddressOf); 3669 HandleValue(CO->getFalseExpr(), AddressOf); 3670 return; 3671 } 3672 3673 if (BinaryConditionalOperator *BCO = 3674 dyn_cast<BinaryConditionalOperator>(E)) { 3675 Visit(BCO->getCond()); 3676 HandleValue(BCO->getFalseExpr(), AddressOf); 3677 return; 3678 } 3679 3680 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3681 HandleValue(OVE->getSourceExpr(), AddressOf); 3682 return; 3683 } 3684 3685 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3686 switch (BO->getOpcode()) { 3687 default: 3688 break; 3689 case(BO_PtrMemD): 3690 case(BO_PtrMemI): 3691 HandleValue(BO->getLHS(), AddressOf); 3692 Visit(BO->getRHS()); 3693 return; 3694 case(BO_Comma): 3695 Visit(BO->getLHS()); 3696 HandleValue(BO->getRHS(), AddressOf); 3697 return; 3698 } 3699 } 3700 3701 Visit(E); 3702 } 3703 3704 void CheckInitListExpr(InitListExpr *ILE) { 3705 InitFieldIndex.push_back(0); 3706 for (auto Child : ILE->children()) { 3707 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3708 CheckInitListExpr(SubList); 3709 } else { 3710 Visit(Child); 3711 } 3712 ++InitFieldIndex.back(); 3713 } 3714 InitFieldIndex.pop_back(); 3715 } 3716 3717 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3718 FieldDecl *Field, const Type *BaseClass) { 3719 // Remove Decls that may have been initialized in the previous 3720 // initializer. 3721 for (ValueDecl* VD : DeclsToRemove) 3722 Decls.erase(VD); 3723 DeclsToRemove.clear(); 3724 3725 Constructor = FieldConstructor; 3726 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3727 3728 if (ILE && Field) { 3729 InitList = true; 3730 InitListFieldDecl = Field; 3731 InitFieldIndex.clear(); 3732 CheckInitListExpr(ILE); 3733 } else { 3734 InitList = false; 3735 Visit(E); 3736 } 3737 3738 if (Field) 3739 Decls.erase(Field); 3740 if (BaseClass) 3741 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3742 } 3743 3744 void VisitMemberExpr(MemberExpr *ME) { 3745 // All uses of unbounded reference fields will warn. 3746 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3747 } 3748 3749 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3750 if (E->getCastKind() == CK_LValueToRValue) { 3751 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3752 return; 3753 } 3754 3755 Inherited::VisitImplicitCastExpr(E); 3756 } 3757 3758 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3759 if (E->getConstructor()->isCopyConstructor()) { 3760 Expr *ArgExpr = E->getArg(0); 3761 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3762 if (ILE->getNumInits() == 1) 3763 ArgExpr = ILE->getInit(0); 3764 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3765 if (ICE->getCastKind() == CK_NoOp) 3766 ArgExpr = ICE->getSubExpr(); 3767 HandleValue(ArgExpr, false /*AddressOf*/); 3768 return; 3769 } 3770 Inherited::VisitCXXConstructExpr(E); 3771 } 3772 3773 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3774 Expr *Callee = E->getCallee(); 3775 if (isa<MemberExpr>(Callee)) { 3776 HandleValue(Callee, false /*AddressOf*/); 3777 for (auto Arg : E->arguments()) 3778 Visit(Arg); 3779 return; 3780 } 3781 3782 Inherited::VisitCXXMemberCallExpr(E); 3783 } 3784 3785 void VisitCallExpr(CallExpr *E) { 3786 // Treat std::move as a use. 3787 if (E->isCallToStdMove()) { 3788 HandleValue(E->getArg(0), /*AddressOf=*/false); 3789 return; 3790 } 3791 3792 Inherited::VisitCallExpr(E); 3793 } 3794 3795 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3796 Expr *Callee = E->getCallee(); 3797 3798 if (isa<UnresolvedLookupExpr>(Callee)) 3799 return Inherited::VisitCXXOperatorCallExpr(E); 3800 3801 Visit(Callee); 3802 for (auto Arg : E->arguments()) 3803 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3804 } 3805 3806 void VisitBinaryOperator(BinaryOperator *E) { 3807 // If a field assignment is detected, remove the field from the 3808 // uninitiailized field set. 3809 if (E->getOpcode() == BO_Assign) 3810 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3811 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3812 if (!FD->getType()->isReferenceType()) 3813 DeclsToRemove.push_back(FD); 3814 3815 if (E->isCompoundAssignmentOp()) { 3816 HandleValue(E->getLHS(), false /*AddressOf*/); 3817 Visit(E->getRHS()); 3818 return; 3819 } 3820 3821 Inherited::VisitBinaryOperator(E); 3822 } 3823 3824 void VisitUnaryOperator(UnaryOperator *E) { 3825 if (E->isIncrementDecrementOp()) { 3826 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3827 return; 3828 } 3829 if (E->getOpcode() == UO_AddrOf) { 3830 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3831 HandleValue(ME->getBase(), true /*AddressOf*/); 3832 return; 3833 } 3834 } 3835 3836 Inherited::VisitUnaryOperator(E); 3837 } 3838 }; 3839 3840 // Diagnose value-uses of fields to initialize themselves, e.g. 3841 // foo(foo) 3842 // where foo is not also a parameter to the constructor. 3843 // Also diagnose across field uninitialized use such as 3844 // x(y), y(x) 3845 // TODO: implement -Wuninitialized and fold this into that framework. 3846 static void DiagnoseUninitializedFields( 3847 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3848 3849 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3850 Constructor->getLocation())) { 3851 return; 3852 } 3853 3854 if (Constructor->isInvalidDecl()) 3855 return; 3856 3857 const CXXRecordDecl *RD = Constructor->getParent(); 3858 3859 if (RD->isDependentContext()) 3860 return; 3861 3862 // Holds fields that are uninitialized. 3863 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3864 3865 // At the beginning, all fields are uninitialized. 3866 for (auto *I : RD->decls()) { 3867 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3868 UninitializedFields.insert(FD); 3869 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3870 UninitializedFields.insert(IFD->getAnonField()); 3871 } 3872 } 3873 3874 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3875 for (auto I : RD->bases()) 3876 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3877 3878 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3879 return; 3880 3881 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3882 UninitializedFields, 3883 UninitializedBaseClasses); 3884 3885 for (const auto *FieldInit : Constructor->inits()) { 3886 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3887 break; 3888 3889 Expr *InitExpr = FieldInit->getInit(); 3890 if (!InitExpr) 3891 continue; 3892 3893 if (CXXDefaultInitExpr *Default = 3894 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3895 InitExpr = Default->getExpr(); 3896 if (!InitExpr) 3897 continue; 3898 // In class initializers will point to the constructor. 3899 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3900 FieldInit->getAnyMember(), 3901 FieldInit->getBaseClass()); 3902 } else { 3903 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3904 FieldInit->getAnyMember(), 3905 FieldInit->getBaseClass()); 3906 } 3907 } 3908 } 3909 } // namespace 3910 3911 /// Enter a new C++ default initializer scope. After calling this, the 3912 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3913 /// parsing or instantiating the initializer failed. 3914 void Sema::ActOnStartCXXInClassMemberInitializer() { 3915 // Create a synthetic function scope to represent the call to the constructor 3916 // that notionally surrounds a use of this initializer. 3917 PushFunctionScope(); 3918 } 3919 3920 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 3921 if (!D.isFunctionDeclarator()) 3922 return; 3923 auto &FTI = D.getFunctionTypeInfo(); 3924 if (!FTI.Params) 3925 return; 3926 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 3927 FTI.NumParams)) { 3928 auto *ParamDecl = cast<NamedDecl>(Param.Param); 3929 if (ParamDecl->getDeclName()) 3930 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 3931 } 3932 } 3933 3934 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 3935 if (ConstraintExpr.isInvalid()) 3936 return ExprError(); 3937 return CorrectDelayedTyposInExpr(ConstraintExpr); 3938 } 3939 3940 /// This is invoked after parsing an in-class initializer for a 3941 /// non-static C++ class member, and after instantiating an in-class initializer 3942 /// in a class template. Such actions are deferred until the class is complete. 3943 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3944 SourceLocation InitLoc, 3945 Expr *InitExpr) { 3946 // Pop the notional constructor scope we created earlier. 3947 PopFunctionScopeInfo(nullptr, D); 3948 3949 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3950 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3951 "must set init style when field is created"); 3952 3953 if (!InitExpr) { 3954 D->setInvalidDecl(); 3955 if (FD) 3956 FD->removeInClassInitializer(); 3957 return; 3958 } 3959 3960 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3961 FD->setInvalidDecl(); 3962 FD->removeInClassInitializer(); 3963 return; 3964 } 3965 3966 ExprResult Init = InitExpr; 3967 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3968 InitializedEntity Entity = 3969 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3970 InitializationKind Kind = 3971 FD->getInClassInitStyle() == ICIS_ListInit 3972 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 3973 InitExpr->getBeginLoc(), 3974 InitExpr->getEndLoc()) 3975 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 3976 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3977 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3978 if (Init.isInvalid()) { 3979 FD->setInvalidDecl(); 3980 return; 3981 } 3982 } 3983 3984 // C++11 [class.base.init]p7: 3985 // The initialization of each base and member constitutes a 3986 // full-expression. 3987 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 3988 if (Init.isInvalid()) { 3989 FD->setInvalidDecl(); 3990 return; 3991 } 3992 3993 InitExpr = Init.get(); 3994 3995 FD->setInClassInitializer(InitExpr); 3996 } 3997 3998 /// Find the direct and/or virtual base specifiers that 3999 /// correspond to the given base type, for use in base initialization 4000 /// within a constructor. 4001 static bool FindBaseInitializer(Sema &SemaRef, 4002 CXXRecordDecl *ClassDecl, 4003 QualType BaseType, 4004 const CXXBaseSpecifier *&DirectBaseSpec, 4005 const CXXBaseSpecifier *&VirtualBaseSpec) { 4006 // First, check for a direct base class. 4007 DirectBaseSpec = nullptr; 4008 for (const auto &Base : ClassDecl->bases()) { 4009 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 4010 // We found a direct base of this type. That's what we're 4011 // initializing. 4012 DirectBaseSpec = &Base; 4013 break; 4014 } 4015 } 4016 4017 // Check for a virtual base class. 4018 // FIXME: We might be able to short-circuit this if we know in advance that 4019 // there are no virtual bases. 4020 VirtualBaseSpec = nullptr; 4021 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 4022 // We haven't found a base yet; search the class hierarchy for a 4023 // virtual base class. 4024 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 4025 /*DetectVirtual=*/false); 4026 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 4027 SemaRef.Context.getTypeDeclType(ClassDecl), 4028 BaseType, Paths)) { 4029 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 4030 Path != Paths.end(); ++Path) { 4031 if (Path->back().Base->isVirtual()) { 4032 VirtualBaseSpec = Path->back().Base; 4033 break; 4034 } 4035 } 4036 } 4037 } 4038 4039 return DirectBaseSpec || VirtualBaseSpec; 4040 } 4041 4042 /// Handle a C++ member initializer using braced-init-list syntax. 4043 MemInitResult 4044 Sema::ActOnMemInitializer(Decl *ConstructorD, 4045 Scope *S, 4046 CXXScopeSpec &SS, 4047 IdentifierInfo *MemberOrBase, 4048 ParsedType TemplateTypeTy, 4049 const DeclSpec &DS, 4050 SourceLocation IdLoc, 4051 Expr *InitList, 4052 SourceLocation EllipsisLoc) { 4053 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4054 DS, IdLoc, InitList, 4055 EllipsisLoc); 4056 } 4057 4058 /// Handle a C++ member initializer using parentheses syntax. 4059 MemInitResult 4060 Sema::ActOnMemInitializer(Decl *ConstructorD, 4061 Scope *S, 4062 CXXScopeSpec &SS, 4063 IdentifierInfo *MemberOrBase, 4064 ParsedType TemplateTypeTy, 4065 const DeclSpec &DS, 4066 SourceLocation IdLoc, 4067 SourceLocation LParenLoc, 4068 ArrayRef<Expr *> Args, 4069 SourceLocation RParenLoc, 4070 SourceLocation EllipsisLoc) { 4071 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4072 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4073 DS, IdLoc, List, EllipsisLoc); 4074 } 4075 4076 namespace { 4077 4078 // Callback to only accept typo corrections that can be a valid C++ member 4079 // intializer: either a non-static field member or a base class. 4080 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4081 public: 4082 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4083 : ClassDecl(ClassDecl) {} 4084 4085 bool ValidateCandidate(const TypoCorrection &candidate) override { 4086 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4087 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4088 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4089 return isa<TypeDecl>(ND); 4090 } 4091 return false; 4092 } 4093 4094 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4095 return std::make_unique<MemInitializerValidatorCCC>(*this); 4096 } 4097 4098 private: 4099 CXXRecordDecl *ClassDecl; 4100 }; 4101 4102 } 4103 4104 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4105 CXXScopeSpec &SS, 4106 ParsedType TemplateTypeTy, 4107 IdentifierInfo *MemberOrBase) { 4108 if (SS.getScopeRep() || TemplateTypeTy) 4109 return nullptr; 4110 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 4111 if (Result.empty()) 4112 return nullptr; 4113 ValueDecl *Member; 4114 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 4115 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) 4116 return Member; 4117 return nullptr; 4118 } 4119 4120 /// Handle a C++ member initializer. 4121 MemInitResult 4122 Sema::BuildMemInitializer(Decl *ConstructorD, 4123 Scope *S, 4124 CXXScopeSpec &SS, 4125 IdentifierInfo *MemberOrBase, 4126 ParsedType TemplateTypeTy, 4127 const DeclSpec &DS, 4128 SourceLocation IdLoc, 4129 Expr *Init, 4130 SourceLocation EllipsisLoc) { 4131 ExprResult Res = CorrectDelayedTyposInExpr(Init); 4132 if (!Res.isUsable()) 4133 return true; 4134 Init = Res.get(); 4135 4136 if (!ConstructorD) 4137 return true; 4138 4139 AdjustDeclIfTemplate(ConstructorD); 4140 4141 CXXConstructorDecl *Constructor 4142 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4143 if (!Constructor) { 4144 // The user wrote a constructor initializer on a function that is 4145 // not a C++ constructor. Ignore the error for now, because we may 4146 // have more member initializers coming; we'll diagnose it just 4147 // once in ActOnMemInitializers. 4148 return true; 4149 } 4150 4151 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4152 4153 // C++ [class.base.init]p2: 4154 // Names in a mem-initializer-id are looked up in the scope of the 4155 // constructor's class and, if not found in that scope, are looked 4156 // up in the scope containing the constructor's definition. 4157 // [Note: if the constructor's class contains a member with the 4158 // same name as a direct or virtual base class of the class, a 4159 // mem-initializer-id naming the member or base class and composed 4160 // of a single identifier refers to the class member. A 4161 // mem-initializer-id for the hidden base class may be specified 4162 // using a qualified name. ] 4163 4164 // Look for a member, first. 4165 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4166 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4167 if (EllipsisLoc.isValid()) 4168 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4169 << MemberOrBase 4170 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4171 4172 return BuildMemberInitializer(Member, Init, IdLoc); 4173 } 4174 // It didn't name a member, so see if it names a class. 4175 QualType BaseType; 4176 TypeSourceInfo *TInfo = nullptr; 4177 4178 if (TemplateTypeTy) { 4179 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4180 if (BaseType.isNull()) 4181 return true; 4182 } else if (DS.getTypeSpecType() == TST_decltype) { 4183 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4184 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4185 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4186 return true; 4187 } else { 4188 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4189 LookupParsedName(R, S, &SS); 4190 4191 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4192 if (!TyD) { 4193 if (R.isAmbiguous()) return true; 4194 4195 // We don't want access-control diagnostics here. 4196 R.suppressDiagnostics(); 4197 4198 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4199 bool NotUnknownSpecialization = false; 4200 DeclContext *DC = computeDeclContext(SS, false); 4201 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4202 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4203 4204 if (!NotUnknownSpecialization) { 4205 // When the scope specifier can refer to a member of an unknown 4206 // specialization, we take it as a type name. 4207 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4208 SS.getWithLocInContext(Context), 4209 *MemberOrBase, IdLoc); 4210 if (BaseType.isNull()) 4211 return true; 4212 4213 TInfo = Context.CreateTypeSourceInfo(BaseType); 4214 DependentNameTypeLoc TL = 4215 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4216 if (!TL.isNull()) { 4217 TL.setNameLoc(IdLoc); 4218 TL.setElaboratedKeywordLoc(SourceLocation()); 4219 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4220 } 4221 4222 R.clear(); 4223 R.setLookupName(MemberOrBase); 4224 } 4225 } 4226 4227 // If no results were found, try to correct typos. 4228 TypoCorrection Corr; 4229 MemInitializerValidatorCCC CCC(ClassDecl); 4230 if (R.empty() && BaseType.isNull() && 4231 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4232 CCC, CTK_ErrorRecovery, ClassDecl))) { 4233 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4234 // We have found a non-static data member with a similar 4235 // name to what was typed; complain and initialize that 4236 // member. 4237 diagnoseTypo(Corr, 4238 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4239 << MemberOrBase << true); 4240 return BuildMemberInitializer(Member, Init, IdLoc); 4241 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4242 const CXXBaseSpecifier *DirectBaseSpec; 4243 const CXXBaseSpecifier *VirtualBaseSpec; 4244 if (FindBaseInitializer(*this, ClassDecl, 4245 Context.getTypeDeclType(Type), 4246 DirectBaseSpec, VirtualBaseSpec)) { 4247 // We have found a direct or virtual base class with a 4248 // similar name to what was typed; complain and initialize 4249 // that base class. 4250 diagnoseTypo(Corr, 4251 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4252 << MemberOrBase << false, 4253 PDiag() /*Suppress note, we provide our own.*/); 4254 4255 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4256 : VirtualBaseSpec; 4257 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4258 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4259 4260 TyD = Type; 4261 } 4262 } 4263 } 4264 4265 if (!TyD && BaseType.isNull()) { 4266 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4267 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4268 return true; 4269 } 4270 } 4271 4272 if (BaseType.isNull()) { 4273 BaseType = Context.getTypeDeclType(TyD); 4274 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4275 if (SS.isSet()) { 4276 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4277 BaseType); 4278 TInfo = Context.CreateTypeSourceInfo(BaseType); 4279 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4280 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4281 TL.setElaboratedKeywordLoc(SourceLocation()); 4282 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4283 } 4284 } 4285 } 4286 4287 if (!TInfo) 4288 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4289 4290 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4291 } 4292 4293 MemInitResult 4294 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4295 SourceLocation IdLoc) { 4296 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4297 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4298 assert((DirectMember || IndirectMember) && 4299 "Member must be a FieldDecl or IndirectFieldDecl"); 4300 4301 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4302 return true; 4303 4304 if (Member->isInvalidDecl()) 4305 return true; 4306 4307 MultiExprArg Args; 4308 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4309 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4310 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4311 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4312 } else { 4313 // Template instantiation doesn't reconstruct ParenListExprs for us. 4314 Args = Init; 4315 } 4316 4317 SourceRange InitRange = Init->getSourceRange(); 4318 4319 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4320 // Can't check initialization for a member of dependent type or when 4321 // any of the arguments are type-dependent expressions. 4322 DiscardCleanupsInEvaluationContext(); 4323 } else { 4324 bool InitList = false; 4325 if (isa<InitListExpr>(Init)) { 4326 InitList = true; 4327 Args = Init; 4328 } 4329 4330 // Initialize the member. 4331 InitializedEntity MemberEntity = 4332 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4333 : InitializedEntity::InitializeMember(IndirectMember, 4334 nullptr); 4335 InitializationKind Kind = 4336 InitList ? InitializationKind::CreateDirectList( 4337 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4338 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4339 InitRange.getEnd()); 4340 4341 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4342 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4343 nullptr); 4344 if (MemberInit.isInvalid()) 4345 return true; 4346 4347 // C++11 [class.base.init]p7: 4348 // The initialization of each base and member constitutes a 4349 // full-expression. 4350 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4351 /*DiscardedValue*/ false); 4352 if (MemberInit.isInvalid()) 4353 return true; 4354 4355 Init = MemberInit.get(); 4356 } 4357 4358 if (DirectMember) { 4359 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4360 InitRange.getBegin(), Init, 4361 InitRange.getEnd()); 4362 } else { 4363 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4364 InitRange.getBegin(), Init, 4365 InitRange.getEnd()); 4366 } 4367 } 4368 4369 MemInitResult 4370 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4371 CXXRecordDecl *ClassDecl) { 4372 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4373 if (!LangOpts.CPlusPlus11) 4374 return Diag(NameLoc, diag::err_delegating_ctor) 4375 << TInfo->getTypeLoc().getLocalSourceRange(); 4376 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4377 4378 bool InitList = true; 4379 MultiExprArg Args = Init; 4380 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4381 InitList = false; 4382 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4383 } 4384 4385 SourceRange InitRange = Init->getSourceRange(); 4386 // Initialize the object. 4387 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4388 QualType(ClassDecl->getTypeForDecl(), 0)); 4389 InitializationKind Kind = 4390 InitList ? InitializationKind::CreateDirectList( 4391 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4392 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4393 InitRange.getEnd()); 4394 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4395 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4396 Args, nullptr); 4397 if (DelegationInit.isInvalid()) 4398 return true; 4399 4400 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4401 "Delegating constructor with no target?"); 4402 4403 // C++11 [class.base.init]p7: 4404 // The initialization of each base and member constitutes a 4405 // full-expression. 4406 DelegationInit = ActOnFinishFullExpr( 4407 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4408 if (DelegationInit.isInvalid()) 4409 return true; 4410 4411 // If we are in a dependent context, template instantiation will 4412 // perform this type-checking again. Just save the arguments that we 4413 // received in a ParenListExpr. 4414 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4415 // of the information that we have about the base 4416 // initializer. However, deconstructing the ASTs is a dicey process, 4417 // and this approach is far more likely to get the corner cases right. 4418 if (CurContext->isDependentContext()) 4419 DelegationInit = Init; 4420 4421 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4422 DelegationInit.getAs<Expr>(), 4423 InitRange.getEnd()); 4424 } 4425 4426 MemInitResult 4427 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4428 Expr *Init, CXXRecordDecl *ClassDecl, 4429 SourceLocation EllipsisLoc) { 4430 SourceLocation BaseLoc 4431 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4432 4433 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4434 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4435 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4436 4437 // C++ [class.base.init]p2: 4438 // [...] Unless the mem-initializer-id names a nonstatic data 4439 // member of the constructor's class or a direct or virtual base 4440 // of that class, the mem-initializer is ill-formed. A 4441 // mem-initializer-list can initialize a base class using any 4442 // name that denotes that base class type. 4443 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4444 4445 SourceRange InitRange = Init->getSourceRange(); 4446 if (EllipsisLoc.isValid()) { 4447 // This is a pack expansion. 4448 if (!BaseType->containsUnexpandedParameterPack()) { 4449 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4450 << SourceRange(BaseLoc, InitRange.getEnd()); 4451 4452 EllipsisLoc = SourceLocation(); 4453 } 4454 } else { 4455 // Check for any unexpanded parameter packs. 4456 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4457 return true; 4458 4459 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4460 return true; 4461 } 4462 4463 // Check for direct and virtual base classes. 4464 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4465 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4466 if (!Dependent) { 4467 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4468 BaseType)) 4469 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4470 4471 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4472 VirtualBaseSpec); 4473 4474 // C++ [base.class.init]p2: 4475 // Unless the mem-initializer-id names a nonstatic data member of the 4476 // constructor's class or a direct or virtual base of that class, the 4477 // mem-initializer is ill-formed. 4478 if (!DirectBaseSpec && !VirtualBaseSpec) { 4479 // If the class has any dependent bases, then it's possible that 4480 // one of those types will resolve to the same type as 4481 // BaseType. Therefore, just treat this as a dependent base 4482 // class initialization. FIXME: Should we try to check the 4483 // initialization anyway? It seems odd. 4484 if (ClassDecl->hasAnyDependentBases()) 4485 Dependent = true; 4486 else 4487 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4488 << BaseType << Context.getTypeDeclType(ClassDecl) 4489 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4490 } 4491 } 4492 4493 if (Dependent) { 4494 DiscardCleanupsInEvaluationContext(); 4495 4496 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4497 /*IsVirtual=*/false, 4498 InitRange.getBegin(), Init, 4499 InitRange.getEnd(), EllipsisLoc); 4500 } 4501 4502 // C++ [base.class.init]p2: 4503 // If a mem-initializer-id is ambiguous because it designates both 4504 // a direct non-virtual base class and an inherited virtual base 4505 // class, the mem-initializer is ill-formed. 4506 if (DirectBaseSpec && VirtualBaseSpec) 4507 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4508 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4509 4510 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4511 if (!BaseSpec) 4512 BaseSpec = VirtualBaseSpec; 4513 4514 // Initialize the base. 4515 bool InitList = true; 4516 MultiExprArg Args = Init; 4517 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4518 InitList = false; 4519 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4520 } 4521 4522 InitializedEntity BaseEntity = 4523 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4524 InitializationKind Kind = 4525 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4526 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4527 InitRange.getEnd()); 4528 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4529 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4530 if (BaseInit.isInvalid()) 4531 return true; 4532 4533 // C++11 [class.base.init]p7: 4534 // The initialization of each base and member constitutes a 4535 // full-expression. 4536 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4537 /*DiscardedValue*/ false); 4538 if (BaseInit.isInvalid()) 4539 return true; 4540 4541 // If we are in a dependent context, template instantiation will 4542 // perform this type-checking again. Just save the arguments that we 4543 // received in a ParenListExpr. 4544 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4545 // of the information that we have about the base 4546 // initializer. However, deconstructing the ASTs is a dicey process, 4547 // and this approach is far more likely to get the corner cases right. 4548 if (CurContext->isDependentContext()) 4549 BaseInit = Init; 4550 4551 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4552 BaseSpec->isVirtual(), 4553 InitRange.getBegin(), 4554 BaseInit.getAs<Expr>(), 4555 InitRange.getEnd(), EllipsisLoc); 4556 } 4557 4558 // Create a static_cast\<T&&>(expr). 4559 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4560 if (T.isNull()) T = E->getType(); 4561 QualType TargetType = SemaRef.BuildReferenceType( 4562 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4563 SourceLocation ExprLoc = E->getBeginLoc(); 4564 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4565 TargetType, ExprLoc); 4566 4567 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4568 SourceRange(ExprLoc, ExprLoc), 4569 E->getSourceRange()).get(); 4570 } 4571 4572 /// ImplicitInitializerKind - How an implicit base or member initializer should 4573 /// initialize its base or member. 4574 enum ImplicitInitializerKind { 4575 IIK_Default, 4576 IIK_Copy, 4577 IIK_Move, 4578 IIK_Inherit 4579 }; 4580 4581 static bool 4582 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4583 ImplicitInitializerKind ImplicitInitKind, 4584 CXXBaseSpecifier *BaseSpec, 4585 bool IsInheritedVirtualBase, 4586 CXXCtorInitializer *&CXXBaseInit) { 4587 InitializedEntity InitEntity 4588 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4589 IsInheritedVirtualBase); 4590 4591 ExprResult BaseInit; 4592 4593 switch (ImplicitInitKind) { 4594 case IIK_Inherit: 4595 case IIK_Default: { 4596 InitializationKind InitKind 4597 = InitializationKind::CreateDefault(Constructor->getLocation()); 4598 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4599 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4600 break; 4601 } 4602 4603 case IIK_Move: 4604 case IIK_Copy: { 4605 bool Moving = ImplicitInitKind == IIK_Move; 4606 ParmVarDecl *Param = Constructor->getParamDecl(0); 4607 QualType ParamType = Param->getType().getNonReferenceType(); 4608 4609 Expr *CopyCtorArg = 4610 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4611 SourceLocation(), Param, false, 4612 Constructor->getLocation(), ParamType, 4613 VK_LValue, nullptr); 4614 4615 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4616 4617 // Cast to the base class to avoid ambiguities. 4618 QualType ArgTy = 4619 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4620 ParamType.getQualifiers()); 4621 4622 if (Moving) { 4623 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4624 } 4625 4626 CXXCastPath BasePath; 4627 BasePath.push_back(BaseSpec); 4628 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4629 CK_UncheckedDerivedToBase, 4630 Moving ? VK_XValue : VK_LValue, 4631 &BasePath).get(); 4632 4633 InitializationKind InitKind 4634 = InitializationKind::CreateDirect(Constructor->getLocation(), 4635 SourceLocation(), SourceLocation()); 4636 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4637 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4638 break; 4639 } 4640 } 4641 4642 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4643 if (BaseInit.isInvalid()) 4644 return true; 4645 4646 CXXBaseInit = 4647 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4648 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4649 SourceLocation()), 4650 BaseSpec->isVirtual(), 4651 SourceLocation(), 4652 BaseInit.getAs<Expr>(), 4653 SourceLocation(), 4654 SourceLocation()); 4655 4656 return false; 4657 } 4658 4659 static bool RefersToRValueRef(Expr *MemRef) { 4660 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4661 return Referenced->getType()->isRValueReferenceType(); 4662 } 4663 4664 static bool 4665 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4666 ImplicitInitializerKind ImplicitInitKind, 4667 FieldDecl *Field, IndirectFieldDecl *Indirect, 4668 CXXCtorInitializer *&CXXMemberInit) { 4669 if (Field->isInvalidDecl()) 4670 return true; 4671 4672 SourceLocation Loc = Constructor->getLocation(); 4673 4674 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4675 bool Moving = ImplicitInitKind == IIK_Move; 4676 ParmVarDecl *Param = Constructor->getParamDecl(0); 4677 QualType ParamType = Param->getType().getNonReferenceType(); 4678 4679 // Suppress copying zero-width bitfields. 4680 if (Field->isZeroLengthBitField(SemaRef.Context)) 4681 return false; 4682 4683 Expr *MemberExprBase = 4684 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4685 SourceLocation(), Param, false, 4686 Loc, ParamType, VK_LValue, nullptr); 4687 4688 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4689 4690 if (Moving) { 4691 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4692 } 4693 4694 // Build a reference to this field within the parameter. 4695 CXXScopeSpec SS; 4696 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4697 Sema::LookupMemberName); 4698 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4699 : cast<ValueDecl>(Field), AS_public); 4700 MemberLookup.resolveKind(); 4701 ExprResult CtorArg 4702 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4703 ParamType, Loc, 4704 /*IsArrow=*/false, 4705 SS, 4706 /*TemplateKWLoc=*/SourceLocation(), 4707 /*FirstQualifierInScope=*/nullptr, 4708 MemberLookup, 4709 /*TemplateArgs=*/nullptr, 4710 /*S*/nullptr); 4711 if (CtorArg.isInvalid()) 4712 return true; 4713 4714 // C++11 [class.copy]p15: 4715 // - if a member m has rvalue reference type T&&, it is direct-initialized 4716 // with static_cast<T&&>(x.m); 4717 if (RefersToRValueRef(CtorArg.get())) { 4718 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4719 } 4720 4721 InitializedEntity Entity = 4722 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4723 /*Implicit*/ true) 4724 : InitializedEntity::InitializeMember(Field, nullptr, 4725 /*Implicit*/ true); 4726 4727 // Direct-initialize to use the copy constructor. 4728 InitializationKind InitKind = 4729 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4730 4731 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4732 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4733 ExprResult MemberInit = 4734 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4735 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4736 if (MemberInit.isInvalid()) 4737 return true; 4738 4739 if (Indirect) 4740 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4741 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4742 else 4743 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4744 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4745 return false; 4746 } 4747 4748 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4749 "Unhandled implicit init kind!"); 4750 4751 QualType FieldBaseElementType = 4752 SemaRef.Context.getBaseElementType(Field->getType()); 4753 4754 if (FieldBaseElementType->isRecordType()) { 4755 InitializedEntity InitEntity = 4756 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4757 /*Implicit*/ true) 4758 : InitializedEntity::InitializeMember(Field, nullptr, 4759 /*Implicit*/ true); 4760 InitializationKind InitKind = 4761 InitializationKind::CreateDefault(Loc); 4762 4763 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4764 ExprResult MemberInit = 4765 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4766 4767 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4768 if (MemberInit.isInvalid()) 4769 return true; 4770 4771 if (Indirect) 4772 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4773 Indirect, Loc, 4774 Loc, 4775 MemberInit.get(), 4776 Loc); 4777 else 4778 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4779 Field, Loc, Loc, 4780 MemberInit.get(), 4781 Loc); 4782 return false; 4783 } 4784 4785 if (!Field->getParent()->isUnion()) { 4786 if (FieldBaseElementType->isReferenceType()) { 4787 SemaRef.Diag(Constructor->getLocation(), 4788 diag::err_uninitialized_member_in_ctor) 4789 << (int)Constructor->isImplicit() 4790 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4791 << 0 << Field->getDeclName(); 4792 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4793 return true; 4794 } 4795 4796 if (FieldBaseElementType.isConstQualified()) { 4797 SemaRef.Diag(Constructor->getLocation(), 4798 diag::err_uninitialized_member_in_ctor) 4799 << (int)Constructor->isImplicit() 4800 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4801 << 1 << Field->getDeclName(); 4802 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4803 return true; 4804 } 4805 } 4806 4807 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4808 // ARC and Weak: 4809 // Default-initialize Objective-C pointers to NULL. 4810 CXXMemberInit 4811 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4812 Loc, Loc, 4813 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4814 Loc); 4815 return false; 4816 } 4817 4818 // Nothing to initialize. 4819 CXXMemberInit = nullptr; 4820 return false; 4821 } 4822 4823 namespace { 4824 struct BaseAndFieldInfo { 4825 Sema &S; 4826 CXXConstructorDecl *Ctor; 4827 bool AnyErrorsInInits; 4828 ImplicitInitializerKind IIK; 4829 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4830 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4831 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4832 4833 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4834 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4835 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4836 if (Ctor->getInheritedConstructor()) 4837 IIK = IIK_Inherit; 4838 else if (Generated && Ctor->isCopyConstructor()) 4839 IIK = IIK_Copy; 4840 else if (Generated && Ctor->isMoveConstructor()) 4841 IIK = IIK_Move; 4842 else 4843 IIK = IIK_Default; 4844 } 4845 4846 bool isImplicitCopyOrMove() const { 4847 switch (IIK) { 4848 case IIK_Copy: 4849 case IIK_Move: 4850 return true; 4851 4852 case IIK_Default: 4853 case IIK_Inherit: 4854 return false; 4855 } 4856 4857 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4858 } 4859 4860 bool addFieldInitializer(CXXCtorInitializer *Init) { 4861 AllToInit.push_back(Init); 4862 4863 // Check whether this initializer makes the field "used". 4864 if (Init->getInit()->HasSideEffects(S.Context)) 4865 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4866 4867 return false; 4868 } 4869 4870 bool isInactiveUnionMember(FieldDecl *Field) { 4871 RecordDecl *Record = Field->getParent(); 4872 if (!Record->isUnion()) 4873 return false; 4874 4875 if (FieldDecl *Active = 4876 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4877 return Active != Field->getCanonicalDecl(); 4878 4879 // In an implicit copy or move constructor, ignore any in-class initializer. 4880 if (isImplicitCopyOrMove()) 4881 return true; 4882 4883 // If there's no explicit initialization, the field is active only if it 4884 // has an in-class initializer... 4885 if (Field->hasInClassInitializer()) 4886 return false; 4887 // ... or it's an anonymous struct or union whose class has an in-class 4888 // initializer. 4889 if (!Field->isAnonymousStructOrUnion()) 4890 return true; 4891 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4892 return !FieldRD->hasInClassInitializer(); 4893 } 4894 4895 /// Determine whether the given field is, or is within, a union member 4896 /// that is inactive (because there was an initializer given for a different 4897 /// member of the union, or because the union was not initialized at all). 4898 bool isWithinInactiveUnionMember(FieldDecl *Field, 4899 IndirectFieldDecl *Indirect) { 4900 if (!Indirect) 4901 return isInactiveUnionMember(Field); 4902 4903 for (auto *C : Indirect->chain()) { 4904 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4905 if (Field && isInactiveUnionMember(Field)) 4906 return true; 4907 } 4908 return false; 4909 } 4910 }; 4911 } 4912 4913 /// Determine whether the given type is an incomplete or zero-lenfgth 4914 /// array type. 4915 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4916 if (T->isIncompleteArrayType()) 4917 return true; 4918 4919 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4920 if (!ArrayT->getSize()) 4921 return true; 4922 4923 T = ArrayT->getElementType(); 4924 } 4925 4926 return false; 4927 } 4928 4929 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4930 FieldDecl *Field, 4931 IndirectFieldDecl *Indirect = nullptr) { 4932 if (Field->isInvalidDecl()) 4933 return false; 4934 4935 // Overwhelmingly common case: we have a direct initializer for this field. 4936 if (CXXCtorInitializer *Init = 4937 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4938 return Info.addFieldInitializer(Init); 4939 4940 // C++11 [class.base.init]p8: 4941 // if the entity is a non-static data member that has a 4942 // brace-or-equal-initializer and either 4943 // -- the constructor's class is a union and no other variant member of that 4944 // union is designated by a mem-initializer-id or 4945 // -- the constructor's class is not a union, and, if the entity is a member 4946 // of an anonymous union, no other member of that union is designated by 4947 // a mem-initializer-id, 4948 // the entity is initialized as specified in [dcl.init]. 4949 // 4950 // We also apply the same rules to handle anonymous structs within anonymous 4951 // unions. 4952 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4953 return false; 4954 4955 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4956 ExprResult DIE = 4957 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4958 if (DIE.isInvalid()) 4959 return true; 4960 4961 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4962 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4963 4964 CXXCtorInitializer *Init; 4965 if (Indirect) 4966 Init = new (SemaRef.Context) 4967 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4968 SourceLocation(), DIE.get(), SourceLocation()); 4969 else 4970 Init = new (SemaRef.Context) 4971 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4972 SourceLocation(), DIE.get(), SourceLocation()); 4973 return Info.addFieldInitializer(Init); 4974 } 4975 4976 // Don't initialize incomplete or zero-length arrays. 4977 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4978 return false; 4979 4980 // Don't try to build an implicit initializer if there were semantic 4981 // errors in any of the initializers (and therefore we might be 4982 // missing some that the user actually wrote). 4983 if (Info.AnyErrorsInInits) 4984 return false; 4985 4986 CXXCtorInitializer *Init = nullptr; 4987 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4988 Indirect, Init)) 4989 return true; 4990 4991 if (!Init) 4992 return false; 4993 4994 return Info.addFieldInitializer(Init); 4995 } 4996 4997 bool 4998 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4999 CXXCtorInitializer *Initializer) { 5000 assert(Initializer->isDelegatingInitializer()); 5001 Constructor->setNumCtorInitializers(1); 5002 CXXCtorInitializer **initializer = 5003 new (Context) CXXCtorInitializer*[1]; 5004 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 5005 Constructor->setCtorInitializers(initializer); 5006 5007 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 5008 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 5009 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 5010 } 5011 5012 DelegatingCtorDecls.push_back(Constructor); 5013 5014 DiagnoseUninitializedFields(*this, Constructor); 5015 5016 return false; 5017 } 5018 5019 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 5020 ArrayRef<CXXCtorInitializer *> Initializers) { 5021 if (Constructor->isDependentContext()) { 5022 // Just store the initializers as written, they will be checked during 5023 // instantiation. 5024 if (!Initializers.empty()) { 5025 Constructor->setNumCtorInitializers(Initializers.size()); 5026 CXXCtorInitializer **baseOrMemberInitializers = 5027 new (Context) CXXCtorInitializer*[Initializers.size()]; 5028 memcpy(baseOrMemberInitializers, Initializers.data(), 5029 Initializers.size() * sizeof(CXXCtorInitializer*)); 5030 Constructor->setCtorInitializers(baseOrMemberInitializers); 5031 } 5032 5033 // Let template instantiation know whether we had errors. 5034 if (AnyErrors) 5035 Constructor->setInvalidDecl(); 5036 5037 return false; 5038 } 5039 5040 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 5041 5042 // We need to build the initializer AST according to order of construction 5043 // and not what user specified in the Initializers list. 5044 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 5045 if (!ClassDecl) 5046 return true; 5047 5048 bool HadError = false; 5049 5050 for (unsigned i = 0; i < Initializers.size(); i++) { 5051 CXXCtorInitializer *Member = Initializers[i]; 5052 5053 if (Member->isBaseInitializer()) 5054 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5055 else { 5056 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5057 5058 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5059 for (auto *C : F->chain()) { 5060 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5061 if (FD && FD->getParent()->isUnion()) 5062 Info.ActiveUnionMember.insert(std::make_pair( 5063 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5064 } 5065 } else if (FieldDecl *FD = Member->getMember()) { 5066 if (FD->getParent()->isUnion()) 5067 Info.ActiveUnionMember.insert(std::make_pair( 5068 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5069 } 5070 } 5071 } 5072 5073 // Keep track of the direct virtual bases. 5074 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5075 for (auto &I : ClassDecl->bases()) { 5076 if (I.isVirtual()) 5077 DirectVBases.insert(&I); 5078 } 5079 5080 // Push virtual bases before others. 5081 for (auto &VBase : ClassDecl->vbases()) { 5082 if (CXXCtorInitializer *Value 5083 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5084 // [class.base.init]p7, per DR257: 5085 // A mem-initializer where the mem-initializer-id names a virtual base 5086 // class is ignored during execution of a constructor of any class that 5087 // is not the most derived class. 5088 if (ClassDecl->isAbstract()) { 5089 // FIXME: Provide a fixit to remove the base specifier. This requires 5090 // tracking the location of the associated comma for a base specifier. 5091 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5092 << VBase.getType() << ClassDecl; 5093 DiagnoseAbstractType(ClassDecl); 5094 } 5095 5096 Info.AllToInit.push_back(Value); 5097 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5098 // [class.base.init]p8, per DR257: 5099 // If a given [...] base class is not named by a mem-initializer-id 5100 // [...] and the entity is not a virtual base class of an abstract 5101 // class, then [...] the entity is default-initialized. 5102 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5103 CXXCtorInitializer *CXXBaseInit; 5104 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5105 &VBase, IsInheritedVirtualBase, 5106 CXXBaseInit)) { 5107 HadError = true; 5108 continue; 5109 } 5110 5111 Info.AllToInit.push_back(CXXBaseInit); 5112 } 5113 } 5114 5115 // Non-virtual bases. 5116 for (auto &Base : ClassDecl->bases()) { 5117 // Virtuals are in the virtual base list and already constructed. 5118 if (Base.isVirtual()) 5119 continue; 5120 5121 if (CXXCtorInitializer *Value 5122 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5123 Info.AllToInit.push_back(Value); 5124 } else if (!AnyErrors) { 5125 CXXCtorInitializer *CXXBaseInit; 5126 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5127 &Base, /*IsInheritedVirtualBase=*/false, 5128 CXXBaseInit)) { 5129 HadError = true; 5130 continue; 5131 } 5132 5133 Info.AllToInit.push_back(CXXBaseInit); 5134 } 5135 } 5136 5137 // Fields. 5138 for (auto *Mem : ClassDecl->decls()) { 5139 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5140 // C++ [class.bit]p2: 5141 // A declaration for a bit-field that omits the identifier declares an 5142 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5143 // initialized. 5144 if (F->isUnnamedBitfield()) 5145 continue; 5146 5147 // If we're not generating the implicit copy/move constructor, then we'll 5148 // handle anonymous struct/union fields based on their individual 5149 // indirect fields. 5150 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5151 continue; 5152 5153 if (CollectFieldInitializer(*this, Info, F)) 5154 HadError = true; 5155 continue; 5156 } 5157 5158 // Beyond this point, we only consider default initialization. 5159 if (Info.isImplicitCopyOrMove()) 5160 continue; 5161 5162 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5163 if (F->getType()->isIncompleteArrayType()) { 5164 assert(ClassDecl->hasFlexibleArrayMember() && 5165 "Incomplete array type is not valid"); 5166 continue; 5167 } 5168 5169 // Initialize each field of an anonymous struct individually. 5170 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5171 HadError = true; 5172 5173 continue; 5174 } 5175 } 5176 5177 unsigned NumInitializers = Info.AllToInit.size(); 5178 if (NumInitializers > 0) { 5179 Constructor->setNumCtorInitializers(NumInitializers); 5180 CXXCtorInitializer **baseOrMemberInitializers = 5181 new (Context) CXXCtorInitializer*[NumInitializers]; 5182 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5183 NumInitializers * sizeof(CXXCtorInitializer*)); 5184 Constructor->setCtorInitializers(baseOrMemberInitializers); 5185 5186 // Constructors implicitly reference the base and member 5187 // destructors. 5188 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5189 Constructor->getParent()); 5190 } 5191 5192 return HadError; 5193 } 5194 5195 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5196 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5197 const RecordDecl *RD = RT->getDecl(); 5198 if (RD->isAnonymousStructOrUnion()) { 5199 for (auto *Field : RD->fields()) 5200 PopulateKeysForFields(Field, IdealInits); 5201 return; 5202 } 5203 } 5204 IdealInits.push_back(Field->getCanonicalDecl()); 5205 } 5206 5207 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5208 return Context.getCanonicalType(BaseType).getTypePtr(); 5209 } 5210 5211 static const void *GetKeyForMember(ASTContext &Context, 5212 CXXCtorInitializer *Member) { 5213 if (!Member->isAnyMemberInitializer()) 5214 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5215 5216 return Member->getAnyMember()->getCanonicalDecl(); 5217 } 5218 5219 static void DiagnoseBaseOrMemInitializerOrder( 5220 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5221 ArrayRef<CXXCtorInitializer *> Inits) { 5222 if (Constructor->getDeclContext()->isDependentContext()) 5223 return; 5224 5225 // Don't check initializers order unless the warning is enabled at the 5226 // location of at least one initializer. 5227 bool ShouldCheckOrder = false; 5228 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5229 CXXCtorInitializer *Init = Inits[InitIndex]; 5230 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5231 Init->getSourceLocation())) { 5232 ShouldCheckOrder = true; 5233 break; 5234 } 5235 } 5236 if (!ShouldCheckOrder) 5237 return; 5238 5239 // Build the list of bases and members in the order that they'll 5240 // actually be initialized. The explicit initializers should be in 5241 // this same order but may be missing things. 5242 SmallVector<const void*, 32> IdealInitKeys; 5243 5244 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5245 5246 // 1. Virtual bases. 5247 for (const auto &VBase : ClassDecl->vbases()) 5248 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5249 5250 // 2. Non-virtual bases. 5251 for (const auto &Base : ClassDecl->bases()) { 5252 if (Base.isVirtual()) 5253 continue; 5254 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5255 } 5256 5257 // 3. Direct fields. 5258 for (auto *Field : ClassDecl->fields()) { 5259 if (Field->isUnnamedBitfield()) 5260 continue; 5261 5262 PopulateKeysForFields(Field, IdealInitKeys); 5263 } 5264 5265 unsigned NumIdealInits = IdealInitKeys.size(); 5266 unsigned IdealIndex = 0; 5267 5268 CXXCtorInitializer *PrevInit = nullptr; 5269 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5270 CXXCtorInitializer *Init = Inits[InitIndex]; 5271 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 5272 5273 // Scan forward to try to find this initializer in the idealized 5274 // initializers list. 5275 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5276 if (InitKey == IdealInitKeys[IdealIndex]) 5277 break; 5278 5279 // If we didn't find this initializer, it must be because we 5280 // scanned past it on a previous iteration. That can only 5281 // happen if we're out of order; emit a warning. 5282 if (IdealIndex == NumIdealInits && PrevInit) { 5283 Sema::SemaDiagnosticBuilder D = 5284 SemaRef.Diag(PrevInit->getSourceLocation(), 5285 diag::warn_initializer_out_of_order); 5286 5287 if (PrevInit->isAnyMemberInitializer()) 5288 D << 0 << PrevInit->getAnyMember()->getDeclName(); 5289 else 5290 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 5291 5292 if (Init->isAnyMemberInitializer()) 5293 D << 0 << Init->getAnyMember()->getDeclName(); 5294 else 5295 D << 1 << Init->getTypeSourceInfo()->getType(); 5296 5297 // Move back to the initializer's location in the ideal list. 5298 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5299 if (InitKey == IdealInitKeys[IdealIndex]) 5300 break; 5301 5302 assert(IdealIndex < NumIdealInits && 5303 "initializer not found in initializer list"); 5304 } 5305 5306 PrevInit = Init; 5307 } 5308 } 5309 5310 namespace { 5311 bool CheckRedundantInit(Sema &S, 5312 CXXCtorInitializer *Init, 5313 CXXCtorInitializer *&PrevInit) { 5314 if (!PrevInit) { 5315 PrevInit = Init; 5316 return false; 5317 } 5318 5319 if (FieldDecl *Field = Init->getAnyMember()) 5320 S.Diag(Init->getSourceLocation(), 5321 diag::err_multiple_mem_initialization) 5322 << Field->getDeclName() 5323 << Init->getSourceRange(); 5324 else { 5325 const Type *BaseClass = Init->getBaseClass(); 5326 assert(BaseClass && "neither field nor base"); 5327 S.Diag(Init->getSourceLocation(), 5328 diag::err_multiple_base_initialization) 5329 << QualType(BaseClass, 0) 5330 << Init->getSourceRange(); 5331 } 5332 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5333 << 0 << PrevInit->getSourceRange(); 5334 5335 return true; 5336 } 5337 5338 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5339 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5340 5341 bool CheckRedundantUnionInit(Sema &S, 5342 CXXCtorInitializer *Init, 5343 RedundantUnionMap &Unions) { 5344 FieldDecl *Field = Init->getAnyMember(); 5345 RecordDecl *Parent = Field->getParent(); 5346 NamedDecl *Child = Field; 5347 5348 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5349 if (Parent->isUnion()) { 5350 UnionEntry &En = Unions[Parent]; 5351 if (En.first && En.first != Child) { 5352 S.Diag(Init->getSourceLocation(), 5353 diag::err_multiple_mem_union_initialization) 5354 << Field->getDeclName() 5355 << Init->getSourceRange(); 5356 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5357 << 0 << En.second->getSourceRange(); 5358 return true; 5359 } 5360 if (!En.first) { 5361 En.first = Child; 5362 En.second = Init; 5363 } 5364 if (!Parent->isAnonymousStructOrUnion()) 5365 return false; 5366 } 5367 5368 Child = Parent; 5369 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5370 } 5371 5372 return false; 5373 } 5374 } 5375 5376 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5377 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5378 SourceLocation ColonLoc, 5379 ArrayRef<CXXCtorInitializer*> MemInits, 5380 bool AnyErrors) { 5381 if (!ConstructorDecl) 5382 return; 5383 5384 AdjustDeclIfTemplate(ConstructorDecl); 5385 5386 CXXConstructorDecl *Constructor 5387 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5388 5389 if (!Constructor) { 5390 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5391 return; 5392 } 5393 5394 // Mapping for the duplicate initializers check. 5395 // For member initializers, this is keyed with a FieldDecl*. 5396 // For base initializers, this is keyed with a Type*. 5397 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5398 5399 // Mapping for the inconsistent anonymous-union initializers check. 5400 RedundantUnionMap MemberUnions; 5401 5402 bool HadError = false; 5403 for (unsigned i = 0; i < MemInits.size(); i++) { 5404 CXXCtorInitializer *Init = MemInits[i]; 5405 5406 // Set the source order index. 5407 Init->setSourceOrder(i); 5408 5409 if (Init->isAnyMemberInitializer()) { 5410 const void *Key = GetKeyForMember(Context, Init); 5411 if (CheckRedundantInit(*this, Init, Members[Key]) || 5412 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5413 HadError = true; 5414 } else if (Init->isBaseInitializer()) { 5415 const void *Key = GetKeyForMember(Context, Init); 5416 if (CheckRedundantInit(*this, Init, Members[Key])) 5417 HadError = true; 5418 } else { 5419 assert(Init->isDelegatingInitializer()); 5420 // This must be the only initializer 5421 if (MemInits.size() != 1) { 5422 Diag(Init->getSourceLocation(), 5423 diag::err_delegating_initializer_alone) 5424 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5425 // We will treat this as being the only initializer. 5426 } 5427 SetDelegatingInitializer(Constructor, MemInits[i]); 5428 // Return immediately as the initializer is set. 5429 return; 5430 } 5431 } 5432 5433 if (HadError) 5434 return; 5435 5436 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5437 5438 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5439 5440 DiagnoseUninitializedFields(*this, Constructor); 5441 } 5442 5443 void 5444 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5445 CXXRecordDecl *ClassDecl) { 5446 // Ignore dependent contexts. Also ignore unions, since their members never 5447 // have destructors implicitly called. 5448 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5449 return; 5450 5451 // FIXME: all the access-control diagnostics are positioned on the 5452 // field/base declaration. That's probably good; that said, the 5453 // user might reasonably want to know why the destructor is being 5454 // emitted, and we currently don't say. 5455 5456 // Non-static data members. 5457 for (auto *Field : ClassDecl->fields()) { 5458 if (Field->isInvalidDecl()) 5459 continue; 5460 5461 // Don't destroy incomplete or zero-length arrays. 5462 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5463 continue; 5464 5465 QualType FieldType = Context.getBaseElementType(Field->getType()); 5466 5467 const RecordType* RT = FieldType->getAs<RecordType>(); 5468 if (!RT) 5469 continue; 5470 5471 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5472 if (FieldClassDecl->isInvalidDecl()) 5473 continue; 5474 if (FieldClassDecl->hasIrrelevantDestructor()) 5475 continue; 5476 // The destructor for an implicit anonymous union member is never invoked. 5477 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5478 continue; 5479 5480 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5481 assert(Dtor && "No dtor found for FieldClassDecl!"); 5482 CheckDestructorAccess(Field->getLocation(), Dtor, 5483 PDiag(diag::err_access_dtor_field) 5484 << Field->getDeclName() 5485 << FieldType); 5486 5487 MarkFunctionReferenced(Location, Dtor); 5488 DiagnoseUseOfDecl(Dtor, Location); 5489 } 5490 5491 // We only potentially invoke the destructors of potentially constructed 5492 // subobjects. 5493 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5494 5495 // If the destructor exists and has already been marked used in the MS ABI, 5496 // then virtual base destructors have already been checked and marked used. 5497 // Skip checking them again to avoid duplicate diagnostics. 5498 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5499 CXXDestructorDecl *Dtor = ClassDecl->getDestructor(); 5500 if (Dtor && Dtor->isUsed()) 5501 VisitVirtualBases = false; 5502 } 5503 5504 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5505 5506 // Bases. 5507 for (const auto &Base : ClassDecl->bases()) { 5508 // Bases are always records in a well-formed non-dependent class. 5509 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5510 5511 // Remember direct virtual bases. 5512 if (Base.isVirtual()) { 5513 if (!VisitVirtualBases) 5514 continue; 5515 DirectVirtualBases.insert(RT); 5516 } 5517 5518 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5519 // If our base class is invalid, we probably can't get its dtor anyway. 5520 if (BaseClassDecl->isInvalidDecl()) 5521 continue; 5522 if (BaseClassDecl->hasIrrelevantDestructor()) 5523 continue; 5524 5525 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5526 assert(Dtor && "No dtor found for BaseClassDecl!"); 5527 5528 // FIXME: caret should be on the start of the class name 5529 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5530 PDiag(diag::err_access_dtor_base) 5531 << Base.getType() << Base.getSourceRange(), 5532 Context.getTypeDeclType(ClassDecl)); 5533 5534 MarkFunctionReferenced(Location, Dtor); 5535 DiagnoseUseOfDecl(Dtor, Location); 5536 } 5537 5538 if (VisitVirtualBases) 5539 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl, 5540 &DirectVirtualBases); 5541 } 5542 5543 void Sema::MarkVirtualBaseDestructorsReferenced( 5544 SourceLocation Location, CXXRecordDecl *ClassDecl, 5545 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) { 5546 // Virtual bases. 5547 for (const auto &VBase : ClassDecl->vbases()) { 5548 // Bases are always records in a well-formed non-dependent class. 5549 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5550 5551 // Ignore already visited direct virtual bases. 5552 if (DirectVirtualBases && DirectVirtualBases->count(RT)) 5553 continue; 5554 5555 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5556 // If our base class is invalid, we probably can't get its dtor anyway. 5557 if (BaseClassDecl->isInvalidDecl()) 5558 continue; 5559 if (BaseClassDecl->hasIrrelevantDestructor()) 5560 continue; 5561 5562 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5563 assert(Dtor && "No dtor found for BaseClassDecl!"); 5564 if (CheckDestructorAccess( 5565 ClassDecl->getLocation(), Dtor, 5566 PDiag(diag::err_access_dtor_vbase) 5567 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5568 Context.getTypeDeclType(ClassDecl)) == 5569 AR_accessible) { 5570 CheckDerivedToBaseConversion( 5571 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5572 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5573 SourceRange(), DeclarationName(), nullptr); 5574 } 5575 5576 MarkFunctionReferenced(Location, Dtor); 5577 DiagnoseUseOfDecl(Dtor, Location); 5578 } 5579 } 5580 5581 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5582 if (!CDtorDecl) 5583 return; 5584 5585 if (CXXConstructorDecl *Constructor 5586 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5587 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5588 DiagnoseUninitializedFields(*this, Constructor); 5589 } 5590 } 5591 5592 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5593 if (!getLangOpts().CPlusPlus) 5594 return false; 5595 5596 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5597 if (!RD) 5598 return false; 5599 5600 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5601 // class template specialization here, but doing so breaks a lot of code. 5602 5603 // We can't answer whether something is abstract until it has a 5604 // definition. If it's currently being defined, we'll walk back 5605 // over all the declarations when we have a full definition. 5606 const CXXRecordDecl *Def = RD->getDefinition(); 5607 if (!Def || Def->isBeingDefined()) 5608 return false; 5609 5610 return RD->isAbstract(); 5611 } 5612 5613 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5614 TypeDiagnoser &Diagnoser) { 5615 if (!isAbstractType(Loc, T)) 5616 return false; 5617 5618 T = Context.getBaseElementType(T); 5619 Diagnoser.diagnose(*this, Loc, T); 5620 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5621 return true; 5622 } 5623 5624 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5625 // Check if we've already emitted the list of pure virtual functions 5626 // for this class. 5627 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5628 return; 5629 5630 // If the diagnostic is suppressed, don't emit the notes. We're only 5631 // going to emit them once, so try to attach them to a diagnostic we're 5632 // actually going to show. 5633 if (Diags.isLastDiagnosticIgnored()) 5634 return; 5635 5636 CXXFinalOverriderMap FinalOverriders; 5637 RD->getFinalOverriders(FinalOverriders); 5638 5639 // Keep a set of seen pure methods so we won't diagnose the same method 5640 // more than once. 5641 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5642 5643 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5644 MEnd = FinalOverriders.end(); 5645 M != MEnd; 5646 ++M) { 5647 for (OverridingMethods::iterator SO = M->second.begin(), 5648 SOEnd = M->second.end(); 5649 SO != SOEnd; ++SO) { 5650 // C++ [class.abstract]p4: 5651 // A class is abstract if it contains or inherits at least one 5652 // pure virtual function for which the final overrider is pure 5653 // virtual. 5654 5655 // 5656 if (SO->second.size() != 1) 5657 continue; 5658 5659 if (!SO->second.front().Method->isPure()) 5660 continue; 5661 5662 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5663 continue; 5664 5665 Diag(SO->second.front().Method->getLocation(), 5666 diag::note_pure_virtual_function) 5667 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5668 } 5669 } 5670 5671 if (!PureVirtualClassDiagSet) 5672 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5673 PureVirtualClassDiagSet->insert(RD); 5674 } 5675 5676 namespace { 5677 struct AbstractUsageInfo { 5678 Sema &S; 5679 CXXRecordDecl *Record; 5680 CanQualType AbstractType; 5681 bool Invalid; 5682 5683 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5684 : S(S), Record(Record), 5685 AbstractType(S.Context.getCanonicalType( 5686 S.Context.getTypeDeclType(Record))), 5687 Invalid(false) {} 5688 5689 void DiagnoseAbstractType() { 5690 if (Invalid) return; 5691 S.DiagnoseAbstractType(Record); 5692 Invalid = true; 5693 } 5694 5695 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5696 }; 5697 5698 struct CheckAbstractUsage { 5699 AbstractUsageInfo &Info; 5700 const NamedDecl *Ctx; 5701 5702 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5703 : Info(Info), Ctx(Ctx) {} 5704 5705 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5706 switch (TL.getTypeLocClass()) { 5707 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5708 #define TYPELOC(CLASS, PARENT) \ 5709 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5710 #include "clang/AST/TypeLocNodes.def" 5711 } 5712 } 5713 5714 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5715 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5716 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5717 if (!TL.getParam(I)) 5718 continue; 5719 5720 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5721 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5722 } 5723 } 5724 5725 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5726 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5727 } 5728 5729 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5730 // Visit the type parameters from a permissive context. 5731 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5732 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5733 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5734 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5735 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5736 // TODO: other template argument types? 5737 } 5738 } 5739 5740 // Visit pointee types from a permissive context. 5741 #define CheckPolymorphic(Type) \ 5742 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5743 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5744 } 5745 CheckPolymorphic(PointerTypeLoc) 5746 CheckPolymorphic(ReferenceTypeLoc) 5747 CheckPolymorphic(MemberPointerTypeLoc) 5748 CheckPolymorphic(BlockPointerTypeLoc) 5749 CheckPolymorphic(AtomicTypeLoc) 5750 5751 /// Handle all the types we haven't given a more specific 5752 /// implementation for above. 5753 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5754 // Every other kind of type that we haven't called out already 5755 // that has an inner type is either (1) sugar or (2) contains that 5756 // inner type in some way as a subobject. 5757 if (TypeLoc Next = TL.getNextTypeLoc()) 5758 return Visit(Next, Sel); 5759 5760 // If there's no inner type and we're in a permissive context, 5761 // don't diagnose. 5762 if (Sel == Sema::AbstractNone) return; 5763 5764 // Check whether the type matches the abstract type. 5765 QualType T = TL.getType(); 5766 if (T->isArrayType()) { 5767 Sel = Sema::AbstractArrayType; 5768 T = Info.S.Context.getBaseElementType(T); 5769 } 5770 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5771 if (CT != Info.AbstractType) return; 5772 5773 // It matched; do some magic. 5774 if (Sel == Sema::AbstractArrayType) { 5775 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5776 << T << TL.getSourceRange(); 5777 } else { 5778 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5779 << Sel << T << TL.getSourceRange(); 5780 } 5781 Info.DiagnoseAbstractType(); 5782 } 5783 }; 5784 5785 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5786 Sema::AbstractDiagSelID Sel) { 5787 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5788 } 5789 5790 } 5791 5792 /// Check for invalid uses of an abstract type in a method declaration. 5793 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5794 CXXMethodDecl *MD) { 5795 // No need to do the check on definitions, which require that 5796 // the return/param types be complete. 5797 if (MD->doesThisDeclarationHaveABody()) 5798 return; 5799 5800 // For safety's sake, just ignore it if we don't have type source 5801 // information. This should never happen for non-implicit methods, 5802 // but... 5803 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5804 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5805 } 5806 5807 /// Check for invalid uses of an abstract type within a class definition. 5808 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5809 CXXRecordDecl *RD) { 5810 for (auto *D : RD->decls()) { 5811 if (D->isImplicit()) continue; 5812 5813 // Methods and method templates. 5814 if (isa<CXXMethodDecl>(D)) { 5815 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5816 } else if (isa<FunctionTemplateDecl>(D)) { 5817 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5818 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5819 5820 // Fields and static variables. 5821 } else if (isa<FieldDecl>(D)) { 5822 FieldDecl *FD = cast<FieldDecl>(D); 5823 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5824 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5825 } else if (isa<VarDecl>(D)) { 5826 VarDecl *VD = cast<VarDecl>(D); 5827 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5828 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5829 5830 // Nested classes and class templates. 5831 } else if (isa<CXXRecordDecl>(D)) { 5832 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5833 } else if (isa<ClassTemplateDecl>(D)) { 5834 CheckAbstractClassUsage(Info, 5835 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5836 } 5837 } 5838 } 5839 5840 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5841 Attr *ClassAttr = getDLLAttr(Class); 5842 if (!ClassAttr) 5843 return; 5844 5845 assert(ClassAttr->getKind() == attr::DLLExport); 5846 5847 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5848 5849 if (TSK == TSK_ExplicitInstantiationDeclaration) 5850 // Don't go any further if this is just an explicit instantiation 5851 // declaration. 5852 return; 5853 5854 // Add a context note to explain how we got to any diagnostics produced below. 5855 struct MarkingClassDllexported { 5856 Sema &S; 5857 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class, 5858 SourceLocation AttrLoc) 5859 : S(S) { 5860 Sema::CodeSynthesisContext Ctx; 5861 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported; 5862 Ctx.PointOfInstantiation = AttrLoc; 5863 Ctx.Entity = Class; 5864 S.pushCodeSynthesisContext(Ctx); 5865 } 5866 ~MarkingClassDllexported() { 5867 S.popCodeSynthesisContext(); 5868 } 5869 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); 5870 5871 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5872 S.MarkVTableUsed(Class->getLocation(), Class, true); 5873 5874 for (Decl *Member : Class->decls()) { 5875 // Defined static variables that are members of an exported base 5876 // class must be marked export too. 5877 auto *VD = dyn_cast<VarDecl>(Member); 5878 if (VD && Member->getAttr<DLLExportAttr>() && 5879 VD->getStorageClass() == SC_Static && 5880 TSK == TSK_ImplicitInstantiation) 5881 S.MarkVariableReferenced(VD->getLocation(), VD); 5882 5883 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5884 if (!MD) 5885 continue; 5886 5887 if (Member->getAttr<DLLExportAttr>()) { 5888 if (MD->isUserProvided()) { 5889 // Instantiate non-default class member functions ... 5890 5891 // .. except for certain kinds of template specializations. 5892 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5893 continue; 5894 5895 S.MarkFunctionReferenced(Class->getLocation(), MD); 5896 5897 // The function will be passed to the consumer when its definition is 5898 // encountered. 5899 } else if (MD->isExplicitlyDefaulted()) { 5900 // Synthesize and instantiate explicitly defaulted methods. 5901 S.MarkFunctionReferenced(Class->getLocation(), MD); 5902 5903 if (TSK != TSK_ExplicitInstantiationDefinition) { 5904 // Except for explicit instantiation defs, we will not see the 5905 // definition again later, so pass it to the consumer now. 5906 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5907 } 5908 } else if (!MD->isTrivial() || 5909 MD->isCopyAssignmentOperator() || 5910 MD->isMoveAssignmentOperator()) { 5911 // Synthesize and instantiate non-trivial implicit methods, and the copy 5912 // and move assignment operators. The latter are exported even if they 5913 // are trivial, because the address of an operator can be taken and 5914 // should compare equal across libraries. 5915 S.MarkFunctionReferenced(Class->getLocation(), MD); 5916 5917 // There is no later point when we will see the definition of this 5918 // function, so pass it to the consumer now. 5919 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5920 } 5921 } 5922 } 5923 } 5924 5925 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5926 CXXRecordDecl *Class) { 5927 // Only the MS ABI has default constructor closures, so we don't need to do 5928 // this semantic checking anywhere else. 5929 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5930 return; 5931 5932 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5933 for (Decl *Member : Class->decls()) { 5934 // Look for exported default constructors. 5935 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5936 if (!CD || !CD->isDefaultConstructor()) 5937 continue; 5938 auto *Attr = CD->getAttr<DLLExportAttr>(); 5939 if (!Attr) 5940 continue; 5941 5942 // If the class is non-dependent, mark the default arguments as ODR-used so 5943 // that we can properly codegen the constructor closure. 5944 if (!Class->isDependentContext()) { 5945 for (ParmVarDecl *PD : CD->parameters()) { 5946 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5947 S.DiscardCleanupsInEvaluationContext(); 5948 } 5949 } 5950 5951 if (LastExportedDefaultCtor) { 5952 S.Diag(LastExportedDefaultCtor->getLocation(), 5953 diag::err_attribute_dll_ambiguous_default_ctor) 5954 << Class; 5955 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5956 << CD->getDeclName(); 5957 return; 5958 } 5959 LastExportedDefaultCtor = CD; 5960 } 5961 } 5962 5963 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, 5964 CXXRecordDecl *Class) { 5965 bool ErrorReported = false; 5966 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 5967 ClassTemplateDecl *TD) { 5968 if (ErrorReported) 5969 return; 5970 S.Diag(TD->getLocation(), 5971 diag::err_cuda_device_builtin_surftex_cls_template) 5972 << /*surface*/ 0 << TD; 5973 ErrorReported = true; 5974 }; 5975 5976 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 5977 if (!TD) { 5978 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 5979 if (!SD) { 5980 S.Diag(Class->getLocation(), 5981 diag::err_cuda_device_builtin_surftex_ref_decl) 5982 << /*surface*/ 0 << Class; 5983 S.Diag(Class->getLocation(), 5984 diag::note_cuda_device_builtin_surftex_should_be_template_class) 5985 << Class; 5986 return; 5987 } 5988 TD = SD->getSpecializedTemplate(); 5989 } 5990 5991 TemplateParameterList *Params = TD->getTemplateParameters(); 5992 unsigned N = Params->size(); 5993 5994 if (N != 2) { 5995 reportIllegalClassTemplate(S, TD); 5996 S.Diag(TD->getLocation(), 5997 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 5998 << TD << 2; 5999 } 6000 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6001 reportIllegalClassTemplate(S, TD); 6002 S.Diag(TD->getLocation(), 6003 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6004 << TD << /*1st*/ 0 << /*type*/ 0; 6005 } 6006 if (N > 1) { 6007 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6008 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6009 reportIllegalClassTemplate(S, TD); 6010 S.Diag(TD->getLocation(), 6011 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6012 << TD << /*2nd*/ 1 << /*integer*/ 1; 6013 } 6014 } 6015 } 6016 6017 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, 6018 CXXRecordDecl *Class) { 6019 bool ErrorReported = false; 6020 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6021 ClassTemplateDecl *TD) { 6022 if (ErrorReported) 6023 return; 6024 S.Diag(TD->getLocation(), 6025 diag::err_cuda_device_builtin_surftex_cls_template) 6026 << /*texture*/ 1 << TD; 6027 ErrorReported = true; 6028 }; 6029 6030 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6031 if (!TD) { 6032 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6033 if (!SD) { 6034 S.Diag(Class->getLocation(), 6035 diag::err_cuda_device_builtin_surftex_ref_decl) 6036 << /*texture*/ 1 << Class; 6037 S.Diag(Class->getLocation(), 6038 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6039 << Class; 6040 return; 6041 } 6042 TD = SD->getSpecializedTemplate(); 6043 } 6044 6045 TemplateParameterList *Params = TD->getTemplateParameters(); 6046 unsigned N = Params->size(); 6047 6048 if (N != 3) { 6049 reportIllegalClassTemplate(S, TD); 6050 S.Diag(TD->getLocation(), 6051 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6052 << TD << 3; 6053 } 6054 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6055 reportIllegalClassTemplate(S, TD); 6056 S.Diag(TD->getLocation(), 6057 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6058 << TD << /*1st*/ 0 << /*type*/ 0; 6059 } 6060 if (N > 1) { 6061 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6062 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6063 reportIllegalClassTemplate(S, TD); 6064 S.Diag(TD->getLocation(), 6065 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6066 << TD << /*2nd*/ 1 << /*integer*/ 1; 6067 } 6068 } 6069 if (N > 2) { 6070 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2)); 6071 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6072 reportIllegalClassTemplate(S, TD); 6073 S.Diag(TD->getLocation(), 6074 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6075 << TD << /*3rd*/ 2 << /*integer*/ 1; 6076 } 6077 } 6078 } 6079 6080 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 6081 // Mark any compiler-generated routines with the implicit code_seg attribute. 6082 for (auto *Method : Class->methods()) { 6083 if (Method->isUserProvided()) 6084 continue; 6085 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 6086 Method->addAttr(A); 6087 } 6088 } 6089 6090 /// Check class-level dllimport/dllexport attribute. 6091 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 6092 Attr *ClassAttr = getDLLAttr(Class); 6093 6094 // MSVC inherits DLL attributes to partial class template specializations. 6095 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) { 6096 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 6097 if (Attr *TemplateAttr = 6098 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 6099 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 6100 A->setInherited(true); 6101 ClassAttr = A; 6102 } 6103 } 6104 } 6105 6106 if (!ClassAttr) 6107 return; 6108 6109 if (!Class->isExternallyVisible()) { 6110 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 6111 << Class << ClassAttr; 6112 return; 6113 } 6114 6115 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6116 !ClassAttr->isInherited()) { 6117 // Diagnose dll attributes on members of class with dll attribute. 6118 for (Decl *Member : Class->decls()) { 6119 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 6120 continue; 6121 InheritableAttr *MemberAttr = getDLLAttr(Member); 6122 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 6123 continue; 6124 6125 Diag(MemberAttr->getLocation(), 6126 diag::err_attribute_dll_member_of_dll_class) 6127 << MemberAttr << ClassAttr; 6128 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 6129 Member->setInvalidDecl(); 6130 } 6131 } 6132 6133 if (Class->getDescribedClassTemplate()) 6134 // Don't inherit dll attribute until the template is instantiated. 6135 return; 6136 6137 // The class is either imported or exported. 6138 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 6139 6140 // Check if this was a dllimport attribute propagated from a derived class to 6141 // a base class template specialization. We don't apply these attributes to 6142 // static data members. 6143 const bool PropagatedImport = 6144 !ClassExported && 6145 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 6146 6147 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6148 6149 // Ignore explicit dllexport on explicit class template instantiation 6150 // declarations, except in MinGW mode. 6151 if (ClassExported && !ClassAttr->isInherited() && 6152 TSK == TSK_ExplicitInstantiationDeclaration && 6153 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 6154 Class->dropAttr<DLLExportAttr>(); 6155 return; 6156 } 6157 6158 // Force declaration of implicit members so they can inherit the attribute. 6159 ForceDeclarationOfImplicitMembers(Class); 6160 6161 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 6162 // seem to be true in practice? 6163 6164 for (Decl *Member : Class->decls()) { 6165 VarDecl *VD = dyn_cast<VarDecl>(Member); 6166 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 6167 6168 // Only methods and static fields inherit the attributes. 6169 if (!VD && !MD) 6170 continue; 6171 6172 if (MD) { 6173 // Don't process deleted methods. 6174 if (MD->isDeleted()) 6175 continue; 6176 6177 if (MD->isInlined()) { 6178 // MinGW does not import or export inline methods. But do it for 6179 // template instantiations. 6180 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6181 TSK != TSK_ExplicitInstantiationDeclaration && 6182 TSK != TSK_ExplicitInstantiationDefinition) 6183 continue; 6184 6185 // MSVC versions before 2015 don't export the move assignment operators 6186 // and move constructor, so don't attempt to import/export them if 6187 // we have a definition. 6188 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 6189 if ((MD->isMoveAssignmentOperator() || 6190 (Ctor && Ctor->isMoveConstructor())) && 6191 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 6192 continue; 6193 6194 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 6195 // operator is exported anyway. 6196 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6197 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 6198 continue; 6199 } 6200 } 6201 6202 // Don't apply dllimport attributes to static data members of class template 6203 // instantiations when the attribute is propagated from a derived class. 6204 if (VD && PropagatedImport) 6205 continue; 6206 6207 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6208 continue; 6209 6210 if (!getDLLAttr(Member)) { 6211 InheritableAttr *NewAttr = nullptr; 6212 6213 // Do not export/import inline function when -fno-dllexport-inlines is 6214 // passed. But add attribute for later local static var check. 6215 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6216 TSK != TSK_ExplicitInstantiationDeclaration && 6217 TSK != TSK_ExplicitInstantiationDefinition) { 6218 if (ClassExported) { 6219 NewAttr = ::new (getASTContext()) 6220 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6221 } else { 6222 NewAttr = ::new (getASTContext()) 6223 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6224 } 6225 } else { 6226 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6227 } 6228 6229 NewAttr->setInherited(true); 6230 Member->addAttr(NewAttr); 6231 6232 if (MD) { 6233 // Propagate DLLAttr to friend re-declarations of MD that have already 6234 // been constructed. 6235 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6236 FD = FD->getPreviousDecl()) { 6237 if (FD->getFriendObjectKind() == Decl::FOK_None) 6238 continue; 6239 assert(!getDLLAttr(FD) && 6240 "friend re-decl should not already have a DLLAttr"); 6241 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6242 NewAttr->setInherited(true); 6243 FD->addAttr(NewAttr); 6244 } 6245 } 6246 } 6247 } 6248 6249 if (ClassExported) 6250 DelayedDllExportClasses.push_back(Class); 6251 } 6252 6253 /// Perform propagation of DLL attributes from a derived class to a 6254 /// templated base class for MS compatibility. 6255 void Sema::propagateDLLAttrToBaseClassTemplate( 6256 CXXRecordDecl *Class, Attr *ClassAttr, 6257 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6258 if (getDLLAttr( 6259 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6260 // If the base class template has a DLL attribute, don't try to change it. 6261 return; 6262 } 6263 6264 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6265 if (!getDLLAttr(BaseTemplateSpec) && 6266 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6267 TSK == TSK_ImplicitInstantiation)) { 6268 // The template hasn't been instantiated yet (or it has, but only as an 6269 // explicit instantiation declaration or implicit instantiation, which means 6270 // we haven't codegenned any members yet), so propagate the attribute. 6271 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6272 NewAttr->setInherited(true); 6273 BaseTemplateSpec->addAttr(NewAttr); 6274 6275 // If this was an import, mark that we propagated it from a derived class to 6276 // a base class template specialization. 6277 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6278 ImportAttr->setPropagatedToBaseTemplate(); 6279 6280 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6281 // needs to be run again to work see the new attribute. Otherwise this will 6282 // get run whenever the template is instantiated. 6283 if (TSK != TSK_Undeclared) 6284 checkClassLevelDLLAttribute(BaseTemplateSpec); 6285 6286 return; 6287 } 6288 6289 if (getDLLAttr(BaseTemplateSpec)) { 6290 // The template has already been specialized or instantiated with an 6291 // attribute, explicitly or through propagation. We should not try to change 6292 // it. 6293 return; 6294 } 6295 6296 // The template was previously instantiated or explicitly specialized without 6297 // a dll attribute, It's too late for us to add an attribute, so warn that 6298 // this is unsupported. 6299 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6300 << BaseTemplateSpec->isExplicitSpecialization(); 6301 Diag(ClassAttr->getLocation(), diag::note_attribute); 6302 if (BaseTemplateSpec->isExplicitSpecialization()) { 6303 Diag(BaseTemplateSpec->getLocation(), 6304 diag::note_template_class_explicit_specialization_was_here) 6305 << BaseTemplateSpec; 6306 } else { 6307 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6308 diag::note_template_class_instantiation_was_here) 6309 << BaseTemplateSpec; 6310 } 6311 } 6312 6313 /// Determine the kind of defaulting that would be done for a given function. 6314 /// 6315 /// If the function is both a default constructor and a copy / move constructor 6316 /// (due to having a default argument for the first parameter), this picks 6317 /// CXXDefaultConstructor. 6318 /// 6319 /// FIXME: Check that case is properly handled by all callers. 6320 Sema::DefaultedFunctionKind 6321 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6322 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6323 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6324 if (Ctor->isDefaultConstructor()) 6325 return Sema::CXXDefaultConstructor; 6326 6327 if (Ctor->isCopyConstructor()) 6328 return Sema::CXXCopyConstructor; 6329 6330 if (Ctor->isMoveConstructor()) 6331 return Sema::CXXMoveConstructor; 6332 } 6333 6334 if (MD->isCopyAssignmentOperator()) 6335 return Sema::CXXCopyAssignment; 6336 6337 if (MD->isMoveAssignmentOperator()) 6338 return Sema::CXXMoveAssignment; 6339 6340 if (isa<CXXDestructorDecl>(FD)) 6341 return Sema::CXXDestructor; 6342 } 6343 6344 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6345 case OO_EqualEqual: 6346 return DefaultedComparisonKind::Equal; 6347 6348 case OO_ExclaimEqual: 6349 return DefaultedComparisonKind::NotEqual; 6350 6351 case OO_Spaceship: 6352 // No point allowing this if <=> doesn't exist in the current language mode. 6353 if (!getLangOpts().CPlusPlus20) 6354 break; 6355 return DefaultedComparisonKind::ThreeWay; 6356 6357 case OO_Less: 6358 case OO_LessEqual: 6359 case OO_Greater: 6360 case OO_GreaterEqual: 6361 // No point allowing this if <=> doesn't exist in the current language mode. 6362 if (!getLangOpts().CPlusPlus20) 6363 break; 6364 return DefaultedComparisonKind::Relational; 6365 6366 default: 6367 break; 6368 } 6369 6370 // Not defaultable. 6371 return DefaultedFunctionKind(); 6372 } 6373 6374 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, 6375 SourceLocation DefaultLoc) { 6376 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD); 6377 if (DFK.isComparison()) 6378 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison()); 6379 6380 switch (DFK.asSpecialMember()) { 6381 case Sema::CXXDefaultConstructor: 6382 S.DefineImplicitDefaultConstructor(DefaultLoc, 6383 cast<CXXConstructorDecl>(FD)); 6384 break; 6385 case Sema::CXXCopyConstructor: 6386 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6387 break; 6388 case Sema::CXXCopyAssignment: 6389 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6390 break; 6391 case Sema::CXXDestructor: 6392 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD)); 6393 break; 6394 case Sema::CXXMoveConstructor: 6395 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6396 break; 6397 case Sema::CXXMoveAssignment: 6398 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6399 break; 6400 case Sema::CXXInvalid: 6401 llvm_unreachable("Invalid special member."); 6402 } 6403 } 6404 6405 /// Determine whether a type is permitted to be passed or returned in 6406 /// registers, per C++ [class.temporary]p3. 6407 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6408 TargetInfo::CallingConvKind CCK) { 6409 if (D->isDependentType() || D->isInvalidDecl()) 6410 return false; 6411 6412 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6413 // The PS4 platform ABI follows the behavior of Clang 3.2. 6414 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6415 return !D->hasNonTrivialDestructorForCall() && 6416 !D->hasNonTrivialCopyConstructorForCall(); 6417 6418 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6419 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6420 bool DtorIsTrivialForCall = false; 6421 6422 // If a class has at least one non-deleted, trivial copy constructor, it 6423 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6424 // 6425 // Note: This permits classes with non-trivial copy or move ctors to be 6426 // passed in registers, so long as they *also* have a trivial copy ctor, 6427 // which is non-conforming. 6428 if (D->needsImplicitCopyConstructor()) { 6429 if (!D->defaultedCopyConstructorIsDeleted()) { 6430 if (D->hasTrivialCopyConstructor()) 6431 CopyCtorIsTrivial = true; 6432 if (D->hasTrivialCopyConstructorForCall()) 6433 CopyCtorIsTrivialForCall = true; 6434 } 6435 } else { 6436 for (const CXXConstructorDecl *CD : D->ctors()) { 6437 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6438 if (CD->isTrivial()) 6439 CopyCtorIsTrivial = true; 6440 if (CD->isTrivialForCall()) 6441 CopyCtorIsTrivialForCall = true; 6442 } 6443 } 6444 } 6445 6446 if (D->needsImplicitDestructor()) { 6447 if (!D->defaultedDestructorIsDeleted() && 6448 D->hasTrivialDestructorForCall()) 6449 DtorIsTrivialForCall = true; 6450 } else if (const auto *DD = D->getDestructor()) { 6451 if (!DD->isDeleted() && DD->isTrivialForCall()) 6452 DtorIsTrivialForCall = true; 6453 } 6454 6455 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6456 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6457 return true; 6458 6459 // If a class has a destructor, we'd really like to pass it indirectly 6460 // because it allows us to elide copies. Unfortunately, MSVC makes that 6461 // impossible for small types, which it will pass in a single register or 6462 // stack slot. Most objects with dtors are large-ish, so handle that early. 6463 // We can't call out all large objects as being indirect because there are 6464 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6465 // how we pass large POD types. 6466 6467 // Note: This permits small classes with nontrivial destructors to be 6468 // passed in registers, which is non-conforming. 6469 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6470 uint64_t TypeSize = isAArch64 ? 128 : 64; 6471 6472 if (CopyCtorIsTrivial && 6473 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6474 return true; 6475 return false; 6476 } 6477 6478 // Per C++ [class.temporary]p3, the relevant condition is: 6479 // each copy constructor, move constructor, and destructor of X is 6480 // either trivial or deleted, and X has at least one non-deleted copy 6481 // or move constructor 6482 bool HasNonDeletedCopyOrMove = false; 6483 6484 if (D->needsImplicitCopyConstructor() && 6485 !D->defaultedCopyConstructorIsDeleted()) { 6486 if (!D->hasTrivialCopyConstructorForCall()) 6487 return false; 6488 HasNonDeletedCopyOrMove = true; 6489 } 6490 6491 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6492 !D->defaultedMoveConstructorIsDeleted()) { 6493 if (!D->hasTrivialMoveConstructorForCall()) 6494 return false; 6495 HasNonDeletedCopyOrMove = true; 6496 } 6497 6498 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6499 !D->hasTrivialDestructorForCall()) 6500 return false; 6501 6502 for (const CXXMethodDecl *MD : D->methods()) { 6503 if (MD->isDeleted()) 6504 continue; 6505 6506 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6507 if (CD && CD->isCopyOrMoveConstructor()) 6508 HasNonDeletedCopyOrMove = true; 6509 else if (!isa<CXXDestructorDecl>(MD)) 6510 continue; 6511 6512 if (!MD->isTrivialForCall()) 6513 return false; 6514 } 6515 6516 return HasNonDeletedCopyOrMove; 6517 } 6518 6519 /// Report an error regarding overriding, along with any relevant 6520 /// overridden methods. 6521 /// 6522 /// \param DiagID the primary error to report. 6523 /// \param MD the overriding method. 6524 static bool 6525 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, 6526 llvm::function_ref<bool(const CXXMethodDecl *)> Report) { 6527 bool IssuedDiagnostic = false; 6528 for (const CXXMethodDecl *O : MD->overridden_methods()) { 6529 if (Report(O)) { 6530 if (!IssuedDiagnostic) { 6531 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6532 IssuedDiagnostic = true; 6533 } 6534 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 6535 } 6536 } 6537 return IssuedDiagnostic; 6538 } 6539 6540 /// Perform semantic checks on a class definition that has been 6541 /// completing, introducing implicitly-declared members, checking for 6542 /// abstract types, etc. 6543 /// 6544 /// \param S The scope in which the class was parsed. Null if we didn't just 6545 /// parse a class definition. 6546 /// \param Record The completed class. 6547 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6548 if (!Record) 6549 return; 6550 6551 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6552 AbstractUsageInfo Info(*this, Record); 6553 CheckAbstractClassUsage(Info, Record); 6554 } 6555 6556 // If this is not an aggregate type and has no user-declared constructor, 6557 // complain about any non-static data members of reference or const scalar 6558 // type, since they will never get initializers. 6559 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6560 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6561 !Record->isLambda()) { 6562 bool Complained = false; 6563 for (const auto *F : Record->fields()) { 6564 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6565 continue; 6566 6567 if (F->getType()->isReferenceType() || 6568 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6569 if (!Complained) { 6570 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6571 << Record->getTagKind() << Record; 6572 Complained = true; 6573 } 6574 6575 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6576 << F->getType()->isReferenceType() 6577 << F->getDeclName(); 6578 } 6579 } 6580 } 6581 6582 if (Record->getIdentifier()) { 6583 // C++ [class.mem]p13: 6584 // If T is the name of a class, then each of the following shall have a 6585 // name different from T: 6586 // - every member of every anonymous union that is a member of class T. 6587 // 6588 // C++ [class.mem]p14: 6589 // In addition, if class T has a user-declared constructor (12.1), every 6590 // non-static data member of class T shall have a name different from T. 6591 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6592 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6593 ++I) { 6594 NamedDecl *D = (*I)->getUnderlyingDecl(); 6595 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6596 Record->hasUserDeclaredConstructor()) || 6597 isa<IndirectFieldDecl>(D)) { 6598 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6599 << D->getDeclName(); 6600 break; 6601 } 6602 } 6603 } 6604 6605 // Warn if the class has virtual methods but non-virtual public destructor. 6606 if (Record->isPolymorphic() && !Record->isDependentType()) { 6607 CXXDestructorDecl *dtor = Record->getDestructor(); 6608 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6609 !Record->hasAttr<FinalAttr>()) 6610 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6611 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6612 } 6613 6614 if (Record->isAbstract()) { 6615 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6616 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6617 << FA->isSpelledAsSealed(); 6618 DiagnoseAbstractType(Record); 6619 } 6620 } 6621 6622 // Warn if the class has a final destructor but is not itself marked final. 6623 if (!Record->hasAttr<FinalAttr>()) { 6624 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6625 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6626 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6627 << FA->isSpelledAsSealed() 6628 << FixItHint::CreateInsertion( 6629 getLocForEndOfToken(Record->getLocation()), 6630 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6631 Diag(Record->getLocation(), 6632 diag::note_final_dtor_non_final_class_silence) 6633 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6634 } 6635 } 6636 } 6637 6638 // See if trivial_abi has to be dropped. 6639 if (Record->hasAttr<TrivialABIAttr>()) 6640 checkIllFormedTrivialABIStruct(*Record); 6641 6642 // Set HasTrivialSpecialMemberForCall if the record has attribute 6643 // "trivial_abi". 6644 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6645 6646 if (HasTrivialABI) 6647 Record->setHasTrivialSpecialMemberForCall(); 6648 6649 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6650 // We check these last because they can depend on the properties of the 6651 // primary comparison functions (==, <=>). 6652 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6653 6654 // Perform checks that can't be done until we know all the properties of a 6655 // member function (whether it's defaulted, deleted, virtual, overriding, 6656 // ...). 6657 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) { 6658 // A static function cannot override anything. 6659 if (MD->getStorageClass() == SC_Static) { 6660 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD, 6661 [](const CXXMethodDecl *) { return true; })) 6662 return; 6663 } 6664 6665 // A deleted function cannot override a non-deleted function and vice 6666 // versa. 6667 if (ReportOverrides(*this, 6668 MD->isDeleted() ? diag::err_deleted_override 6669 : diag::err_non_deleted_override, 6670 MD, [&](const CXXMethodDecl *V) { 6671 return MD->isDeleted() != V->isDeleted(); 6672 })) { 6673 if (MD->isDefaulted() && MD->isDeleted()) 6674 // Explain why this defaulted function was deleted. 6675 DiagnoseDeletedDefaultedFunction(MD); 6676 return; 6677 } 6678 6679 // A consteval function cannot override a non-consteval function and vice 6680 // versa. 6681 if (ReportOverrides(*this, 6682 MD->isConsteval() ? diag::err_consteval_override 6683 : diag::err_non_consteval_override, 6684 MD, [&](const CXXMethodDecl *V) { 6685 return MD->isConsteval() != V->isConsteval(); 6686 })) { 6687 if (MD->isDefaulted() && MD->isDeleted()) 6688 // Explain why this defaulted function was deleted. 6689 DiagnoseDeletedDefaultedFunction(MD); 6690 return; 6691 } 6692 }; 6693 6694 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool { 6695 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6696 return false; 6697 6698 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6699 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6700 DFK.asComparison() == DefaultedComparisonKind::Relational) { 6701 DefaultedSecondaryComparisons.push_back(FD); 6702 return true; 6703 } 6704 6705 CheckExplicitlyDefaultedFunction(S, FD); 6706 return false; 6707 }; 6708 6709 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6710 // Check whether the explicitly-defaulted members are valid. 6711 bool Incomplete = CheckForDefaultedFunction(M); 6712 6713 // Skip the rest of the checks for a member of a dependent class. 6714 if (Record->isDependentType()) 6715 return; 6716 6717 // For an explicitly defaulted or deleted special member, we defer 6718 // determining triviality until the class is complete. That time is now! 6719 CXXSpecialMember CSM = getSpecialMember(M); 6720 if (!M->isImplicit() && !M->isUserProvided()) { 6721 if (CSM != CXXInvalid) { 6722 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6723 // Inform the class that we've finished declaring this member. 6724 Record->finishedDefaultedOrDeletedMember(M); 6725 M->setTrivialForCall( 6726 HasTrivialABI || 6727 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6728 Record->setTrivialForCallFlags(M); 6729 } 6730 } 6731 6732 // Set triviality for the purpose of calls if this is a user-provided 6733 // copy/move constructor or destructor. 6734 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6735 CSM == CXXDestructor) && M->isUserProvided()) { 6736 M->setTrivialForCall(HasTrivialABI); 6737 Record->setTrivialForCallFlags(M); 6738 } 6739 6740 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6741 M->hasAttr<DLLExportAttr>()) { 6742 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6743 M->isTrivial() && 6744 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6745 CSM == CXXDestructor)) 6746 M->dropAttr<DLLExportAttr>(); 6747 6748 if (M->hasAttr<DLLExportAttr>()) { 6749 // Define after any fields with in-class initializers have been parsed. 6750 DelayedDllExportMemberFunctions.push_back(M); 6751 } 6752 } 6753 6754 // Define defaulted constexpr virtual functions that override a base class 6755 // function right away. 6756 // FIXME: We can defer doing this until the vtable is marked as used. 6757 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6758 DefineDefaultedFunction(*this, M, M->getLocation()); 6759 6760 if (!Incomplete) 6761 CheckCompletedMemberFunction(M); 6762 }; 6763 6764 // Check the destructor before any other member function. We need to 6765 // determine whether it's trivial in order to determine whether the claas 6766 // type is a literal type, which is a prerequisite for determining whether 6767 // other special member functions are valid and whether they're implicitly 6768 // 'constexpr'. 6769 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6770 CompleteMemberFunction(Dtor); 6771 6772 bool HasMethodWithOverrideControl = false, 6773 HasOverridingMethodWithoutOverrideControl = false; 6774 for (auto *D : Record->decls()) { 6775 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 6776 // FIXME: We could do this check for dependent types with non-dependent 6777 // bases. 6778 if (!Record->isDependentType()) { 6779 // See if a method overloads virtual methods in a base 6780 // class without overriding any. 6781 if (!M->isStatic()) 6782 DiagnoseHiddenVirtualMethods(M); 6783 if (M->hasAttr<OverrideAttr>()) 6784 HasMethodWithOverrideControl = true; 6785 else if (M->size_overridden_methods() > 0) 6786 HasOverridingMethodWithoutOverrideControl = true; 6787 } 6788 6789 if (!isa<CXXDestructorDecl>(M)) 6790 CompleteMemberFunction(M); 6791 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 6792 CheckForDefaultedFunction( 6793 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 6794 } 6795 } 6796 6797 if (HasOverridingMethodWithoutOverrideControl) { 6798 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl; 6799 for (auto *M : Record->methods()) 6800 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl); 6801 } 6802 6803 // Check the defaulted secondary comparisons after any other member functions. 6804 for (FunctionDecl *FD : DefaultedSecondaryComparisons) { 6805 CheckExplicitlyDefaultedFunction(S, FD); 6806 6807 // If this is a member function, we deferred checking it until now. 6808 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) 6809 CheckCompletedMemberFunction(MD); 6810 } 6811 6812 // ms_struct is a request to use the same ABI rules as MSVC. Check 6813 // whether this class uses any C++ features that are implemented 6814 // completely differently in MSVC, and if so, emit a diagnostic. 6815 // That diagnostic defaults to an error, but we allow projects to 6816 // map it down to a warning (or ignore it). It's a fairly common 6817 // practice among users of the ms_struct pragma to mass-annotate 6818 // headers, sweeping up a bunch of types that the project doesn't 6819 // really rely on MSVC-compatible layout for. We must therefore 6820 // support "ms_struct except for C++ stuff" as a secondary ABI. 6821 // Don't emit this diagnostic if the feature was enabled as a 6822 // language option (as opposed to via a pragma or attribute), as 6823 // the option -mms-bitfields otherwise essentially makes it impossible 6824 // to build C++ code, unless this diagnostic is turned off. 6825 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields && 6826 (Record->isPolymorphic() || Record->getNumBases())) { 6827 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6828 } 6829 6830 checkClassLevelDLLAttribute(Record); 6831 checkClassLevelCodeSegAttribute(Record); 6832 6833 bool ClangABICompat4 = 6834 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6835 TargetInfo::CallingConvKind CCK = 6836 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6837 bool CanPass = canPassInRegisters(*this, Record, CCK); 6838 6839 // Do not change ArgPassingRestrictions if it has already been set to 6840 // APK_CanNeverPassInRegs. 6841 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6842 Record->setArgPassingRestrictions(CanPass 6843 ? RecordDecl::APK_CanPassInRegs 6844 : RecordDecl::APK_CannotPassInRegs); 6845 6846 // If canPassInRegisters returns true despite the record having a non-trivial 6847 // destructor, the record is destructed in the callee. This happens only when 6848 // the record or one of its subobjects has a field annotated with trivial_abi 6849 // or a field qualified with ObjC __strong/__weak. 6850 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6851 Record->setParamDestroyedInCallee(true); 6852 else if (Record->hasNonTrivialDestructor()) 6853 Record->setParamDestroyedInCallee(CanPass); 6854 6855 if (getLangOpts().ForceEmitVTables) { 6856 // If we want to emit all the vtables, we need to mark it as used. This 6857 // is especially required for cases like vtable assumption loads. 6858 MarkVTableUsed(Record->getInnerLocStart(), Record); 6859 } 6860 6861 if (getLangOpts().CUDA) { 6862 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) 6863 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record); 6864 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>()) 6865 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record); 6866 } 6867 } 6868 6869 /// Look up the special member function that would be called by a special 6870 /// member function for a subobject of class type. 6871 /// 6872 /// \param Class The class type of the subobject. 6873 /// \param CSM The kind of special member function. 6874 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6875 /// \param ConstRHS True if this is a copy operation with a const object 6876 /// on its RHS, that is, if the argument to the outer special member 6877 /// function is 'const' and this is not a field marked 'mutable'. 6878 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6879 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6880 unsigned FieldQuals, bool ConstRHS) { 6881 unsigned LHSQuals = 0; 6882 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6883 LHSQuals = FieldQuals; 6884 6885 unsigned RHSQuals = FieldQuals; 6886 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6887 RHSQuals = 0; 6888 else if (ConstRHS) 6889 RHSQuals |= Qualifiers::Const; 6890 6891 return S.LookupSpecialMember(Class, CSM, 6892 RHSQuals & Qualifiers::Const, 6893 RHSQuals & Qualifiers::Volatile, 6894 false, 6895 LHSQuals & Qualifiers::Const, 6896 LHSQuals & Qualifiers::Volatile); 6897 } 6898 6899 class Sema::InheritedConstructorInfo { 6900 Sema &S; 6901 SourceLocation UseLoc; 6902 6903 /// A mapping from the base classes through which the constructor was 6904 /// inherited to the using shadow declaration in that base class (or a null 6905 /// pointer if the constructor was declared in that base class). 6906 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6907 InheritedFromBases; 6908 6909 public: 6910 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6911 ConstructorUsingShadowDecl *Shadow) 6912 : S(S), UseLoc(UseLoc) { 6913 bool DiagnosedMultipleConstructedBases = false; 6914 CXXRecordDecl *ConstructedBase = nullptr; 6915 UsingDecl *ConstructedBaseUsing = nullptr; 6916 6917 // Find the set of such base class subobjects and check that there's a 6918 // unique constructed subobject. 6919 for (auto *D : Shadow->redecls()) { 6920 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6921 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6922 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6923 6924 InheritedFromBases.insert( 6925 std::make_pair(DNominatedBase->getCanonicalDecl(), 6926 DShadow->getNominatedBaseClassShadowDecl())); 6927 if (DShadow->constructsVirtualBase()) 6928 InheritedFromBases.insert( 6929 std::make_pair(DConstructedBase->getCanonicalDecl(), 6930 DShadow->getConstructedBaseClassShadowDecl())); 6931 else 6932 assert(DNominatedBase == DConstructedBase); 6933 6934 // [class.inhctor.init]p2: 6935 // If the constructor was inherited from multiple base class subobjects 6936 // of type B, the program is ill-formed. 6937 if (!ConstructedBase) { 6938 ConstructedBase = DConstructedBase; 6939 ConstructedBaseUsing = D->getUsingDecl(); 6940 } else if (ConstructedBase != DConstructedBase && 6941 !Shadow->isInvalidDecl()) { 6942 if (!DiagnosedMultipleConstructedBases) { 6943 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6944 << Shadow->getTargetDecl(); 6945 S.Diag(ConstructedBaseUsing->getLocation(), 6946 diag::note_ambiguous_inherited_constructor_using) 6947 << ConstructedBase; 6948 DiagnosedMultipleConstructedBases = true; 6949 } 6950 S.Diag(D->getUsingDecl()->getLocation(), 6951 diag::note_ambiguous_inherited_constructor_using) 6952 << DConstructedBase; 6953 } 6954 } 6955 6956 if (DiagnosedMultipleConstructedBases) 6957 Shadow->setInvalidDecl(); 6958 } 6959 6960 /// Find the constructor to use for inherited construction of a base class, 6961 /// and whether that base class constructor inherits the constructor from a 6962 /// virtual base class (in which case it won't actually invoke it). 6963 std::pair<CXXConstructorDecl *, bool> 6964 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6965 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6966 if (It == InheritedFromBases.end()) 6967 return std::make_pair(nullptr, false); 6968 6969 // This is an intermediary class. 6970 if (It->second) 6971 return std::make_pair( 6972 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6973 It->second->constructsVirtualBase()); 6974 6975 // This is the base class from which the constructor was inherited. 6976 return std::make_pair(Ctor, false); 6977 } 6978 }; 6979 6980 /// Is the special member function which would be selected to perform the 6981 /// specified operation on the specified class type a constexpr constructor? 6982 static bool 6983 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6984 Sema::CXXSpecialMember CSM, unsigned Quals, 6985 bool ConstRHS, 6986 CXXConstructorDecl *InheritedCtor = nullptr, 6987 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6988 // If we're inheriting a constructor, see if we need to call it for this base 6989 // class. 6990 if (InheritedCtor) { 6991 assert(CSM == Sema::CXXDefaultConstructor); 6992 auto BaseCtor = 6993 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6994 if (BaseCtor) 6995 return BaseCtor->isConstexpr(); 6996 } 6997 6998 if (CSM == Sema::CXXDefaultConstructor) 6999 return ClassDecl->hasConstexprDefaultConstructor(); 7000 if (CSM == Sema::CXXDestructor) 7001 return ClassDecl->hasConstexprDestructor(); 7002 7003 Sema::SpecialMemberOverloadResult SMOR = 7004 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 7005 if (!SMOR.getMethod()) 7006 // A constructor we wouldn't select can't be "involved in initializing" 7007 // anything. 7008 return true; 7009 return SMOR.getMethod()->isConstexpr(); 7010 } 7011 7012 /// Determine whether the specified special member function would be constexpr 7013 /// if it were implicitly defined. 7014 static bool defaultedSpecialMemberIsConstexpr( 7015 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 7016 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 7017 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7018 if (!S.getLangOpts().CPlusPlus11) 7019 return false; 7020 7021 // C++11 [dcl.constexpr]p4: 7022 // In the definition of a constexpr constructor [...] 7023 bool Ctor = true; 7024 switch (CSM) { 7025 case Sema::CXXDefaultConstructor: 7026 if (Inherited) 7027 break; 7028 // Since default constructor lookup is essentially trivial (and cannot 7029 // involve, for instance, template instantiation), we compute whether a 7030 // defaulted default constructor is constexpr directly within CXXRecordDecl. 7031 // 7032 // This is important for performance; we need to know whether the default 7033 // constructor is constexpr to determine whether the type is a literal type. 7034 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 7035 7036 case Sema::CXXCopyConstructor: 7037 case Sema::CXXMoveConstructor: 7038 // For copy or move constructors, we need to perform overload resolution. 7039 break; 7040 7041 case Sema::CXXCopyAssignment: 7042 case Sema::CXXMoveAssignment: 7043 if (!S.getLangOpts().CPlusPlus14) 7044 return false; 7045 // In C++1y, we need to perform overload resolution. 7046 Ctor = false; 7047 break; 7048 7049 case Sema::CXXDestructor: 7050 return ClassDecl->defaultedDestructorIsConstexpr(); 7051 7052 case Sema::CXXInvalid: 7053 return false; 7054 } 7055 7056 // -- if the class is a non-empty union, or for each non-empty anonymous 7057 // union member of a non-union class, exactly one non-static data member 7058 // shall be initialized; [DR1359] 7059 // 7060 // If we squint, this is guaranteed, since exactly one non-static data member 7061 // will be initialized (if the constructor isn't deleted), we just don't know 7062 // which one. 7063 if (Ctor && ClassDecl->isUnion()) 7064 return CSM == Sema::CXXDefaultConstructor 7065 ? ClassDecl->hasInClassInitializer() || 7066 !ClassDecl->hasVariantMembers() 7067 : true; 7068 7069 // -- the class shall not have any virtual base classes; 7070 if (Ctor && ClassDecl->getNumVBases()) 7071 return false; 7072 7073 // C++1y [class.copy]p26: 7074 // -- [the class] is a literal type, and 7075 if (!Ctor && !ClassDecl->isLiteral()) 7076 return false; 7077 7078 // -- every constructor involved in initializing [...] base class 7079 // sub-objects shall be a constexpr constructor; 7080 // -- the assignment operator selected to copy/move each direct base 7081 // class is a constexpr function, and 7082 for (const auto &B : ClassDecl->bases()) { 7083 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 7084 if (!BaseType) continue; 7085 7086 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7087 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 7088 InheritedCtor, Inherited)) 7089 return false; 7090 } 7091 7092 // -- every constructor involved in initializing non-static data members 7093 // [...] shall be a constexpr constructor; 7094 // -- every non-static data member and base class sub-object shall be 7095 // initialized 7096 // -- for each non-static data member of X that is of class type (or array 7097 // thereof), the assignment operator selected to copy/move that member is 7098 // a constexpr function 7099 for (const auto *F : ClassDecl->fields()) { 7100 if (F->isInvalidDecl()) 7101 continue; 7102 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 7103 continue; 7104 QualType BaseType = S.Context.getBaseElementType(F->getType()); 7105 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 7106 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7107 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 7108 BaseType.getCVRQualifiers(), 7109 ConstArg && !F->isMutable())) 7110 return false; 7111 } else if (CSM == Sema::CXXDefaultConstructor) { 7112 return false; 7113 } 7114 } 7115 7116 // All OK, it's constexpr! 7117 return true; 7118 } 7119 7120 namespace { 7121 /// RAII object to register a defaulted function as having its exception 7122 /// specification computed. 7123 struct ComputingExceptionSpec { 7124 Sema &S; 7125 7126 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 7127 : S(S) { 7128 Sema::CodeSynthesisContext Ctx; 7129 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 7130 Ctx.PointOfInstantiation = Loc; 7131 Ctx.Entity = FD; 7132 S.pushCodeSynthesisContext(Ctx); 7133 } 7134 ~ComputingExceptionSpec() { 7135 S.popCodeSynthesisContext(); 7136 } 7137 }; 7138 } 7139 7140 static Sema::ImplicitExceptionSpecification 7141 ComputeDefaultedSpecialMemberExceptionSpec( 7142 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 7143 Sema::InheritedConstructorInfo *ICI); 7144 7145 static Sema::ImplicitExceptionSpecification 7146 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 7147 FunctionDecl *FD, 7148 Sema::DefaultedComparisonKind DCK); 7149 7150 static Sema::ImplicitExceptionSpecification 7151 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 7152 auto DFK = S.getDefaultedFunctionKind(FD); 7153 if (DFK.isSpecialMember()) 7154 return ComputeDefaultedSpecialMemberExceptionSpec( 7155 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 7156 if (DFK.isComparison()) 7157 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 7158 DFK.asComparison()); 7159 7160 auto *CD = cast<CXXConstructorDecl>(FD); 7161 assert(CD->getInheritedConstructor() && 7162 "only defaulted functions and inherited constructors have implicit " 7163 "exception specs"); 7164 Sema::InheritedConstructorInfo ICI( 7165 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 7166 return ComputeDefaultedSpecialMemberExceptionSpec( 7167 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 7168 } 7169 7170 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 7171 CXXMethodDecl *MD) { 7172 FunctionProtoType::ExtProtoInfo EPI; 7173 7174 // Build an exception specification pointing back at this member. 7175 EPI.ExceptionSpec.Type = EST_Unevaluated; 7176 EPI.ExceptionSpec.SourceDecl = MD; 7177 7178 // Set the calling convention to the default for C++ instance methods. 7179 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 7180 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 7181 /*IsCXXMethod=*/true)); 7182 return EPI; 7183 } 7184 7185 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 7186 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 7187 if (FPT->getExceptionSpecType() != EST_Unevaluated) 7188 return; 7189 7190 // Evaluate the exception specification. 7191 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 7192 auto ESI = IES.getExceptionSpec(); 7193 7194 // Update the type of the special member to use it. 7195 UpdateExceptionSpec(FD, ESI); 7196 } 7197 7198 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 7199 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted"); 7200 7201 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 7202 if (!DefKind) { 7203 assert(FD->getDeclContext()->isDependentContext()); 7204 return; 7205 } 7206 7207 if (DefKind.isSpecialMember() 7208 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 7209 DefKind.asSpecialMember()) 7210 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 7211 FD->setInvalidDecl(); 7212 } 7213 7214 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7215 CXXSpecialMember CSM) { 7216 CXXRecordDecl *RD = MD->getParent(); 7217 7218 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 7219 "not an explicitly-defaulted special member"); 7220 7221 // Defer all checking for special members of a dependent type. 7222 if (RD->isDependentType()) 7223 return false; 7224 7225 // Whether this was the first-declared instance of the constructor. 7226 // This affects whether we implicitly add an exception spec and constexpr. 7227 bool First = MD == MD->getCanonicalDecl(); 7228 7229 bool HadError = false; 7230 7231 // C++11 [dcl.fct.def.default]p1: 7232 // A function that is explicitly defaulted shall 7233 // -- be a special member function [...] (checked elsewhere), 7234 // -- have the same type (except for ref-qualifiers, and except that a 7235 // copy operation can take a non-const reference) as an implicit 7236 // declaration, and 7237 // -- not have default arguments. 7238 // C++2a changes the second bullet to instead delete the function if it's 7239 // defaulted on its first declaration, unless it's "an assignment operator, 7240 // and its return type differs or its parameter type is not a reference". 7241 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First; 7242 bool ShouldDeleteForTypeMismatch = false; 7243 unsigned ExpectedParams = 1; 7244 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 7245 ExpectedParams = 0; 7246 if (MD->getNumParams() != ExpectedParams) { 7247 // This checks for default arguments: a copy or move constructor with a 7248 // default argument is classified as a default constructor, and assignment 7249 // operations and destructors can't have default arguments. 7250 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 7251 << CSM << MD->getSourceRange(); 7252 HadError = true; 7253 } else if (MD->isVariadic()) { 7254 if (DeleteOnTypeMismatch) 7255 ShouldDeleteForTypeMismatch = true; 7256 else { 7257 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 7258 << CSM << MD->getSourceRange(); 7259 HadError = true; 7260 } 7261 } 7262 7263 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 7264 7265 bool CanHaveConstParam = false; 7266 if (CSM == CXXCopyConstructor) 7267 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 7268 else if (CSM == CXXCopyAssignment) 7269 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 7270 7271 QualType ReturnType = Context.VoidTy; 7272 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 7273 // Check for return type matching. 7274 ReturnType = Type->getReturnType(); 7275 7276 QualType DeclType = Context.getTypeDeclType(RD); 7277 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 7278 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 7279 7280 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 7281 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 7282 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 7283 HadError = true; 7284 } 7285 7286 // A defaulted special member cannot have cv-qualifiers. 7287 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 7288 if (DeleteOnTypeMismatch) 7289 ShouldDeleteForTypeMismatch = true; 7290 else { 7291 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 7292 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 7293 HadError = true; 7294 } 7295 } 7296 } 7297 7298 // Check for parameter type matching. 7299 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 7300 bool HasConstParam = false; 7301 if (ExpectedParams && ArgType->isReferenceType()) { 7302 // Argument must be reference to possibly-const T. 7303 QualType ReferentType = ArgType->getPointeeType(); 7304 HasConstParam = ReferentType.isConstQualified(); 7305 7306 if (ReferentType.isVolatileQualified()) { 7307 if (DeleteOnTypeMismatch) 7308 ShouldDeleteForTypeMismatch = true; 7309 else { 7310 Diag(MD->getLocation(), 7311 diag::err_defaulted_special_member_volatile_param) << CSM; 7312 HadError = true; 7313 } 7314 } 7315 7316 if (HasConstParam && !CanHaveConstParam) { 7317 if (DeleteOnTypeMismatch) 7318 ShouldDeleteForTypeMismatch = true; 7319 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7320 Diag(MD->getLocation(), 7321 diag::err_defaulted_special_member_copy_const_param) 7322 << (CSM == CXXCopyAssignment); 7323 // FIXME: Explain why this special member can't be const. 7324 HadError = true; 7325 } else { 7326 Diag(MD->getLocation(), 7327 diag::err_defaulted_special_member_move_const_param) 7328 << (CSM == CXXMoveAssignment); 7329 HadError = true; 7330 } 7331 } 7332 } else if (ExpectedParams) { 7333 // A copy assignment operator can take its argument by value, but a 7334 // defaulted one cannot. 7335 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 7336 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7337 HadError = true; 7338 } 7339 7340 // C++11 [dcl.fct.def.default]p2: 7341 // An explicitly-defaulted function may be declared constexpr only if it 7342 // would have been implicitly declared as constexpr, 7343 // Do not apply this rule to members of class templates, since core issue 1358 7344 // makes such functions always instantiate to constexpr functions. For 7345 // functions which cannot be constexpr (for non-constructors in C++11 and for 7346 // destructors in C++14 and C++17), this is checked elsewhere. 7347 // 7348 // FIXME: This should not apply if the member is deleted. 7349 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7350 HasConstParam); 7351 if ((getLangOpts().CPlusPlus20 || 7352 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7353 : isa<CXXConstructorDecl>(MD))) && 7354 MD->isConstexpr() && !Constexpr && 7355 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7356 Diag(MD->getBeginLoc(), MD->isConsteval() 7357 ? diag::err_incorrect_defaulted_consteval 7358 : diag::err_incorrect_defaulted_constexpr) 7359 << CSM; 7360 // FIXME: Explain why the special member can't be constexpr. 7361 HadError = true; 7362 } 7363 7364 if (First) { 7365 // C++2a [dcl.fct.def.default]p3: 7366 // If a function is explicitly defaulted on its first declaration, it is 7367 // implicitly considered to be constexpr if the implicit declaration 7368 // would be. 7369 MD->setConstexprKind(Constexpr ? (MD->isConsteval() 7370 ? ConstexprSpecKind::Consteval 7371 : ConstexprSpecKind::Constexpr) 7372 : ConstexprSpecKind::Unspecified); 7373 7374 if (!Type->hasExceptionSpec()) { 7375 // C++2a [except.spec]p3: 7376 // If a declaration of a function does not have a noexcept-specifier 7377 // [and] is defaulted on its first declaration, [...] the exception 7378 // specification is as specified below 7379 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7380 EPI.ExceptionSpec.Type = EST_Unevaluated; 7381 EPI.ExceptionSpec.SourceDecl = MD; 7382 MD->setType(Context.getFunctionType(ReturnType, 7383 llvm::makeArrayRef(&ArgType, 7384 ExpectedParams), 7385 EPI)); 7386 } 7387 } 7388 7389 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7390 if (First) { 7391 SetDeclDeleted(MD, MD->getLocation()); 7392 if (!inTemplateInstantiation() && !HadError) { 7393 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7394 if (ShouldDeleteForTypeMismatch) { 7395 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7396 } else { 7397 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7398 } 7399 } 7400 if (ShouldDeleteForTypeMismatch && !HadError) { 7401 Diag(MD->getLocation(), 7402 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7403 } 7404 } else { 7405 // C++11 [dcl.fct.def.default]p4: 7406 // [For a] user-provided explicitly-defaulted function [...] if such a 7407 // function is implicitly defined as deleted, the program is ill-formed. 7408 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7409 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 7410 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7411 HadError = true; 7412 } 7413 } 7414 7415 return HadError; 7416 } 7417 7418 namespace { 7419 /// Helper class for building and checking a defaulted comparison. 7420 /// 7421 /// Defaulted functions are built in two phases: 7422 /// 7423 /// * First, the set of operations that the function will perform are 7424 /// identified, and some of them are checked. If any of the checked 7425 /// operations is invalid in certain ways, the comparison function is 7426 /// defined as deleted and no body is built. 7427 /// * Then, if the function is not defined as deleted, the body is built. 7428 /// 7429 /// This is accomplished by performing two visitation steps over the eventual 7430 /// body of the function. 7431 template<typename Derived, typename ResultList, typename Result, 7432 typename Subobject> 7433 class DefaultedComparisonVisitor { 7434 public: 7435 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7436 7437 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7438 DefaultedComparisonKind DCK) 7439 : S(S), RD(RD), FD(FD), DCK(DCK) { 7440 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7441 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7442 // UnresolvedSet to avoid this copy. 7443 Fns.assign(Info->getUnqualifiedLookups().begin(), 7444 Info->getUnqualifiedLookups().end()); 7445 } 7446 } 7447 7448 ResultList visit() { 7449 // The type of an lvalue naming a parameter of this function. 7450 QualType ParamLvalType = 7451 FD->getParamDecl(0)->getType().getNonReferenceType(); 7452 7453 ResultList Results; 7454 7455 switch (DCK) { 7456 case DefaultedComparisonKind::None: 7457 llvm_unreachable("not a defaulted comparison"); 7458 7459 case DefaultedComparisonKind::Equal: 7460 case DefaultedComparisonKind::ThreeWay: 7461 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7462 return Results; 7463 7464 case DefaultedComparisonKind::NotEqual: 7465 case DefaultedComparisonKind::Relational: 7466 Results.add(getDerived().visitExpandedSubobject( 7467 ParamLvalType, getDerived().getCompleteObject())); 7468 return Results; 7469 } 7470 llvm_unreachable(""); 7471 } 7472 7473 protected: 7474 Derived &getDerived() { return static_cast<Derived&>(*this); } 7475 7476 /// Visit the expanded list of subobjects of the given type, as specified in 7477 /// C++2a [class.compare.default]. 7478 /// 7479 /// \return \c true if the ResultList object said we're done, \c false if not. 7480 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7481 Qualifiers Quals) { 7482 // C++2a [class.compare.default]p4: 7483 // The direct base class subobjects of C 7484 for (CXXBaseSpecifier &Base : Record->bases()) 7485 if (Results.add(getDerived().visitSubobject( 7486 S.Context.getQualifiedType(Base.getType(), Quals), 7487 getDerived().getBase(&Base)))) 7488 return true; 7489 7490 // followed by the non-static data members of C 7491 for (FieldDecl *Field : Record->fields()) { 7492 // Recursively expand anonymous structs. 7493 if (Field->isAnonymousStructOrUnion()) { 7494 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7495 Quals)) 7496 return true; 7497 continue; 7498 } 7499 7500 // Figure out the type of an lvalue denoting this field. 7501 Qualifiers FieldQuals = Quals; 7502 if (Field->isMutable()) 7503 FieldQuals.removeConst(); 7504 QualType FieldType = 7505 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7506 7507 if (Results.add(getDerived().visitSubobject( 7508 FieldType, getDerived().getField(Field)))) 7509 return true; 7510 } 7511 7512 // form a list of subobjects. 7513 return false; 7514 } 7515 7516 Result visitSubobject(QualType Type, Subobject Subobj) { 7517 // In that list, any subobject of array type is recursively expanded 7518 const ArrayType *AT = S.Context.getAsArrayType(Type); 7519 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7520 return getDerived().visitSubobjectArray(CAT->getElementType(), 7521 CAT->getSize(), Subobj); 7522 return getDerived().visitExpandedSubobject(Type, Subobj); 7523 } 7524 7525 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7526 Subobject Subobj) { 7527 return getDerived().visitSubobject(Type, Subobj); 7528 } 7529 7530 protected: 7531 Sema &S; 7532 CXXRecordDecl *RD; 7533 FunctionDecl *FD; 7534 DefaultedComparisonKind DCK; 7535 UnresolvedSet<16> Fns; 7536 }; 7537 7538 /// Information about a defaulted comparison, as determined by 7539 /// DefaultedComparisonAnalyzer. 7540 struct DefaultedComparisonInfo { 7541 bool Deleted = false; 7542 bool Constexpr = true; 7543 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7544 7545 static DefaultedComparisonInfo deleted() { 7546 DefaultedComparisonInfo Deleted; 7547 Deleted.Deleted = true; 7548 return Deleted; 7549 } 7550 7551 bool add(const DefaultedComparisonInfo &R) { 7552 Deleted |= R.Deleted; 7553 Constexpr &= R.Constexpr; 7554 Category = commonComparisonType(Category, R.Category); 7555 return Deleted; 7556 } 7557 }; 7558 7559 /// An element in the expanded list of subobjects of a defaulted comparison, as 7560 /// specified in C++2a [class.compare.default]p4. 7561 struct DefaultedComparisonSubobject { 7562 enum { CompleteObject, Member, Base } Kind; 7563 NamedDecl *Decl; 7564 SourceLocation Loc; 7565 }; 7566 7567 /// A visitor over the notional body of a defaulted comparison that determines 7568 /// whether that body would be deleted or constexpr. 7569 class DefaultedComparisonAnalyzer 7570 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7571 DefaultedComparisonInfo, 7572 DefaultedComparisonInfo, 7573 DefaultedComparisonSubobject> { 7574 public: 7575 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7576 7577 private: 7578 DiagnosticKind Diagnose; 7579 7580 public: 7581 using Base = DefaultedComparisonVisitor; 7582 using Result = DefaultedComparisonInfo; 7583 using Subobject = DefaultedComparisonSubobject; 7584 7585 friend Base; 7586 7587 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7588 DefaultedComparisonKind DCK, 7589 DiagnosticKind Diagnose = NoDiagnostics) 7590 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7591 7592 Result visit() { 7593 if ((DCK == DefaultedComparisonKind::Equal || 7594 DCK == DefaultedComparisonKind::ThreeWay) && 7595 RD->hasVariantMembers()) { 7596 // C++2a [class.compare.default]p2 [P2002R0]: 7597 // A defaulted comparison operator function for class C is defined as 7598 // deleted if [...] C has variant members. 7599 if (Diagnose == ExplainDeleted) { 7600 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7601 << FD << RD->isUnion() << RD; 7602 } 7603 return Result::deleted(); 7604 } 7605 7606 return Base::visit(); 7607 } 7608 7609 private: 7610 Subobject getCompleteObject() { 7611 return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()}; 7612 } 7613 7614 Subobject getBase(CXXBaseSpecifier *Base) { 7615 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7616 Base->getBaseTypeLoc()}; 7617 } 7618 7619 Subobject getField(FieldDecl *Field) { 7620 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7621 } 7622 7623 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7624 // C++2a [class.compare.default]p2 [P2002R0]: 7625 // A defaulted <=> or == operator function for class C is defined as 7626 // deleted if any non-static data member of C is of reference type 7627 if (Type->isReferenceType()) { 7628 if (Diagnose == ExplainDeleted) { 7629 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7630 << FD << RD; 7631 } 7632 return Result::deleted(); 7633 } 7634 7635 // [...] Let xi be an lvalue denoting the ith element [...] 7636 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7637 Expr *Args[] = {&Xi, &Xi}; 7638 7639 // All operators start by trying to apply that same operator recursively. 7640 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7641 assert(OO != OO_None && "not an overloaded operator!"); 7642 return visitBinaryOperator(OO, Args, Subobj); 7643 } 7644 7645 Result 7646 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7647 Subobject Subobj, 7648 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7649 // Note that there is no need to consider rewritten candidates here if 7650 // we've already found there is no viable 'operator<=>' candidate (and are 7651 // considering synthesizing a '<=>' from '==' and '<'). 7652 OverloadCandidateSet CandidateSet( 7653 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7654 OverloadCandidateSet::OperatorRewriteInfo( 7655 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7656 7657 /// C++2a [class.compare.default]p1 [P2002R0]: 7658 /// [...] the defaulted function itself is never a candidate for overload 7659 /// resolution [...] 7660 CandidateSet.exclude(FD); 7661 7662 if (Args[0]->getType()->isOverloadableType()) 7663 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7664 else { 7665 // FIXME: We determine whether this is a valid expression by checking to 7666 // see if there's a viable builtin operator candidate for it. That isn't 7667 // really what the rules ask us to do, but should give the right results. 7668 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet); 7669 } 7670 7671 Result R; 7672 7673 OverloadCandidateSet::iterator Best; 7674 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7675 case OR_Success: { 7676 // C++2a [class.compare.secondary]p2 [P2002R0]: 7677 // The operator function [...] is defined as deleted if [...] the 7678 // candidate selected by overload resolution is not a rewritten 7679 // candidate. 7680 if ((DCK == DefaultedComparisonKind::NotEqual || 7681 DCK == DefaultedComparisonKind::Relational) && 7682 !Best->RewriteKind) { 7683 if (Diagnose == ExplainDeleted) { 7684 S.Diag(Best->Function->getLocation(), 7685 diag::note_defaulted_comparison_not_rewritten_callee) 7686 << FD; 7687 } 7688 return Result::deleted(); 7689 } 7690 7691 // Throughout C++2a [class.compare]: if overload resolution does not 7692 // result in a usable function, the candidate function is defined as 7693 // deleted. This requires that we selected an accessible function. 7694 // 7695 // Note that this only considers the access of the function when named 7696 // within the type of the subobject, and not the access path for any 7697 // derived-to-base conversion. 7698 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7699 if (ArgClass && Best->FoundDecl.getDecl() && 7700 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7701 QualType ObjectType = Subobj.Kind == Subobject::Member 7702 ? Args[0]->getType() 7703 : S.Context.getRecordType(RD); 7704 if (!S.isMemberAccessibleForDeletion( 7705 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7706 Diagnose == ExplainDeleted 7707 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7708 << FD << Subobj.Kind << Subobj.Decl 7709 : S.PDiag())) 7710 return Result::deleted(); 7711 } 7712 7713 // C++2a [class.compare.default]p3 [P2002R0]: 7714 // A defaulted comparison function is constexpr-compatible if [...] 7715 // no overlod resolution performed [...] results in a non-constexpr 7716 // function. 7717 if (FunctionDecl *BestFD = Best->Function) { 7718 assert(!BestFD->isDeleted() && "wrong overload resolution result"); 7719 // If it's not constexpr, explain why not. 7720 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 7721 if (Subobj.Kind != Subobject::CompleteObject) 7722 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7723 << Subobj.Kind << Subobj.Decl; 7724 S.Diag(BestFD->getLocation(), 7725 diag::note_defaulted_comparison_not_constexpr_here); 7726 // Bail out after explaining; we don't want any more notes. 7727 return Result::deleted(); 7728 } 7729 R.Constexpr &= BestFD->isConstexpr(); 7730 } 7731 7732 if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) { 7733 if (auto *BestFD = Best->Function) { 7734 // If any callee has an undeduced return type, deduce it now. 7735 // FIXME: It's not clear how a failure here should be handled. For 7736 // now, we produce an eager diagnostic, because that is forward 7737 // compatible with most (all?) other reasonable options. 7738 if (BestFD->getReturnType()->isUndeducedType() && 7739 S.DeduceReturnType(BestFD, FD->getLocation(), 7740 /*Diagnose=*/false)) { 7741 // Don't produce a duplicate error when asked to explain why the 7742 // comparison is deleted: we diagnosed that when initially checking 7743 // the defaulted operator. 7744 if (Diagnose == NoDiagnostics) { 7745 S.Diag( 7746 FD->getLocation(), 7747 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) 7748 << Subobj.Kind << Subobj.Decl; 7749 S.Diag( 7750 Subobj.Loc, 7751 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) 7752 << Subobj.Kind << Subobj.Decl; 7753 S.Diag(BestFD->getLocation(), 7754 diag::note_defaulted_comparison_cannot_deduce_callee) 7755 << Subobj.Kind << Subobj.Decl; 7756 } 7757 return Result::deleted(); 7758 } 7759 if (auto *Info = S.Context.CompCategories.lookupInfoForType( 7760 BestFD->getCallResultType())) { 7761 R.Category = Info->Kind; 7762 } else { 7763 if (Diagnose == ExplainDeleted) { 7764 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 7765 << Subobj.Kind << Subobj.Decl 7766 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 7767 S.Diag(BestFD->getLocation(), 7768 diag::note_defaulted_comparison_cannot_deduce_callee) 7769 << Subobj.Kind << Subobj.Decl; 7770 } 7771 return Result::deleted(); 7772 } 7773 } else { 7774 Optional<ComparisonCategoryType> Cat = 7775 getComparisonCategoryForBuiltinCmp(Args[0]->getType()); 7776 assert(Cat && "no category for builtin comparison?"); 7777 R.Category = *Cat; 7778 } 7779 } 7780 7781 // Note that we might be rewriting to a different operator. That call is 7782 // not considered until we come to actually build the comparison function. 7783 break; 7784 } 7785 7786 case OR_Ambiguous: 7787 if (Diagnose == ExplainDeleted) { 7788 unsigned Kind = 0; 7789 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 7790 Kind = OO == OO_EqualEqual ? 1 : 2; 7791 CandidateSet.NoteCandidates( 7792 PartialDiagnosticAt( 7793 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 7794 << FD << Kind << Subobj.Kind << Subobj.Decl), 7795 S, OCD_AmbiguousCandidates, Args); 7796 } 7797 R = Result::deleted(); 7798 break; 7799 7800 case OR_Deleted: 7801 if (Diagnose == ExplainDeleted) { 7802 if ((DCK == DefaultedComparisonKind::NotEqual || 7803 DCK == DefaultedComparisonKind::Relational) && 7804 !Best->RewriteKind) { 7805 S.Diag(Best->Function->getLocation(), 7806 diag::note_defaulted_comparison_not_rewritten_callee) 7807 << FD; 7808 } else { 7809 S.Diag(Subobj.Loc, 7810 diag::note_defaulted_comparison_calls_deleted) 7811 << FD << Subobj.Kind << Subobj.Decl; 7812 S.NoteDeletedFunction(Best->Function); 7813 } 7814 } 7815 R = Result::deleted(); 7816 break; 7817 7818 case OR_No_Viable_Function: 7819 // If there's no usable candidate, we're done unless we can rewrite a 7820 // '<=>' in terms of '==' and '<'. 7821 if (OO == OO_Spaceship && 7822 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 7823 // For any kind of comparison category return type, we need a usable 7824 // '==' and a usable '<'. 7825 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 7826 &CandidateSet))) 7827 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 7828 break; 7829 } 7830 7831 if (Diagnose == ExplainDeleted) { 7832 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 7833 << FD << Subobj.Kind << Subobj.Decl; 7834 7835 // For a three-way comparison, list both the candidates for the 7836 // original operator and the candidates for the synthesized operator. 7837 if (SpaceshipCandidates) { 7838 SpaceshipCandidates->NoteCandidates( 7839 S, Args, 7840 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 7841 Args, FD->getLocation())); 7842 S.Diag(Subobj.Loc, 7843 diag::note_defaulted_comparison_no_viable_function_synthesized) 7844 << (OO == OO_EqualEqual ? 0 : 1); 7845 } 7846 7847 CandidateSet.NoteCandidates( 7848 S, Args, 7849 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 7850 FD->getLocation())); 7851 } 7852 R = Result::deleted(); 7853 break; 7854 } 7855 7856 return R; 7857 } 7858 }; 7859 7860 /// A list of statements. 7861 struct StmtListResult { 7862 bool IsInvalid = false; 7863 llvm::SmallVector<Stmt*, 16> Stmts; 7864 7865 bool add(const StmtResult &S) { 7866 IsInvalid |= S.isInvalid(); 7867 if (IsInvalid) 7868 return true; 7869 Stmts.push_back(S.get()); 7870 return false; 7871 } 7872 }; 7873 7874 /// A visitor over the notional body of a defaulted comparison that synthesizes 7875 /// the actual body. 7876 class DefaultedComparisonSynthesizer 7877 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 7878 StmtListResult, StmtResult, 7879 std::pair<ExprResult, ExprResult>> { 7880 SourceLocation Loc; 7881 unsigned ArrayDepth = 0; 7882 7883 public: 7884 using Base = DefaultedComparisonVisitor; 7885 using ExprPair = std::pair<ExprResult, ExprResult>; 7886 7887 friend Base; 7888 7889 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7890 DefaultedComparisonKind DCK, 7891 SourceLocation BodyLoc) 7892 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 7893 7894 /// Build a suitable function body for this defaulted comparison operator. 7895 StmtResult build() { 7896 Sema::CompoundScopeRAII CompoundScope(S); 7897 7898 StmtListResult Stmts = visit(); 7899 if (Stmts.IsInvalid) 7900 return StmtError(); 7901 7902 ExprResult RetVal; 7903 switch (DCK) { 7904 case DefaultedComparisonKind::None: 7905 llvm_unreachable("not a defaulted comparison"); 7906 7907 case DefaultedComparisonKind::Equal: { 7908 // C++2a [class.eq]p3: 7909 // [...] compar[e] the corresponding elements [...] until the first 7910 // index i where xi == yi yields [...] false. If no such index exists, 7911 // V is true. Otherwise, V is false. 7912 // 7913 // Join the comparisons with '&&'s and return the result. Use a right 7914 // fold (traversing the conditions right-to-left), because that 7915 // short-circuits more naturally. 7916 auto OldStmts = std::move(Stmts.Stmts); 7917 Stmts.Stmts.clear(); 7918 ExprResult CmpSoFar; 7919 // Finish a particular comparison chain. 7920 auto FinishCmp = [&] { 7921 if (Expr *Prior = CmpSoFar.get()) { 7922 // Convert the last expression to 'return ...;' 7923 if (RetVal.isUnset() && Stmts.Stmts.empty()) 7924 RetVal = CmpSoFar; 7925 // Convert any prior comparison to 'if (!(...)) return false;' 7926 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 7927 return true; 7928 CmpSoFar = ExprResult(); 7929 } 7930 return false; 7931 }; 7932 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 7933 Expr *E = dyn_cast<Expr>(EAsStmt); 7934 if (!E) { 7935 // Found an array comparison. 7936 if (FinishCmp() || Stmts.add(EAsStmt)) 7937 return StmtError(); 7938 continue; 7939 } 7940 7941 if (CmpSoFar.isUnset()) { 7942 CmpSoFar = E; 7943 continue; 7944 } 7945 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 7946 if (CmpSoFar.isInvalid()) 7947 return StmtError(); 7948 } 7949 if (FinishCmp()) 7950 return StmtError(); 7951 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 7952 // If no such index exists, V is true. 7953 if (RetVal.isUnset()) 7954 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 7955 break; 7956 } 7957 7958 case DefaultedComparisonKind::ThreeWay: { 7959 // Per C++2a [class.spaceship]p3, as a fallback add: 7960 // return static_cast<R>(std::strong_ordering::equal); 7961 QualType StrongOrdering = S.CheckComparisonCategoryType( 7962 ComparisonCategoryType::StrongOrdering, Loc, 7963 Sema::ComparisonCategoryUsage::DefaultedOperator); 7964 if (StrongOrdering.isNull()) 7965 return StmtError(); 7966 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 7967 .getValueInfo(ComparisonCategoryResult::Equal) 7968 ->VD; 7969 RetVal = getDecl(EqualVD); 7970 if (RetVal.isInvalid()) 7971 return StmtError(); 7972 RetVal = buildStaticCastToR(RetVal.get()); 7973 break; 7974 } 7975 7976 case DefaultedComparisonKind::NotEqual: 7977 case DefaultedComparisonKind::Relational: 7978 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 7979 break; 7980 } 7981 7982 // Build the final return statement. 7983 if (RetVal.isInvalid()) 7984 return StmtError(); 7985 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 7986 if (ReturnStmt.isInvalid()) 7987 return StmtError(); 7988 Stmts.Stmts.push_back(ReturnStmt.get()); 7989 7990 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 7991 } 7992 7993 private: 7994 ExprResult getDecl(ValueDecl *VD) { 7995 return S.BuildDeclarationNameExpr( 7996 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 7997 } 7998 7999 ExprResult getParam(unsigned I) { 8000 ParmVarDecl *PD = FD->getParamDecl(I); 8001 return getDecl(PD); 8002 } 8003 8004 ExprPair getCompleteObject() { 8005 unsigned Param = 0; 8006 ExprResult LHS; 8007 if (isa<CXXMethodDecl>(FD)) { 8008 // LHS is '*this'. 8009 LHS = S.ActOnCXXThis(Loc); 8010 if (!LHS.isInvalid()) 8011 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 8012 } else { 8013 LHS = getParam(Param++); 8014 } 8015 ExprResult RHS = getParam(Param++); 8016 assert(Param == FD->getNumParams()); 8017 return {LHS, RHS}; 8018 } 8019 8020 ExprPair getBase(CXXBaseSpecifier *Base) { 8021 ExprPair Obj = getCompleteObject(); 8022 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8023 return {ExprError(), ExprError()}; 8024 CXXCastPath Path = {Base}; 8025 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 8026 CK_DerivedToBase, VK_LValue, &Path), 8027 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 8028 CK_DerivedToBase, VK_LValue, &Path)}; 8029 } 8030 8031 ExprPair getField(FieldDecl *Field) { 8032 ExprPair Obj = getCompleteObject(); 8033 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8034 return {ExprError(), ExprError()}; 8035 8036 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 8037 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 8038 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 8039 CXXScopeSpec(), Field, Found, NameInfo), 8040 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 8041 CXXScopeSpec(), Field, Found, NameInfo)}; 8042 } 8043 8044 // FIXME: When expanding a subobject, register a note in the code synthesis 8045 // stack to say which subobject we're comparing. 8046 8047 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 8048 if (Cond.isInvalid()) 8049 return StmtError(); 8050 8051 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 8052 if (NotCond.isInvalid()) 8053 return StmtError(); 8054 8055 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 8056 assert(!False.isInvalid() && "should never fail"); 8057 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 8058 if (ReturnFalse.isInvalid()) 8059 return StmtError(); 8060 8061 return S.ActOnIfStmt(Loc, false, Loc, nullptr, 8062 S.ActOnCondition(nullptr, Loc, NotCond.get(), 8063 Sema::ConditionKind::Boolean), 8064 Loc, ReturnFalse.get(), SourceLocation(), nullptr); 8065 } 8066 8067 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 8068 ExprPair Subobj) { 8069 QualType SizeType = S.Context.getSizeType(); 8070 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 8071 8072 // Build 'size_t i$n = 0'. 8073 IdentifierInfo *IterationVarName = nullptr; 8074 { 8075 SmallString<8> Str; 8076 llvm::raw_svector_ostream OS(Str); 8077 OS << "i" << ArrayDepth; 8078 IterationVarName = &S.Context.Idents.get(OS.str()); 8079 } 8080 VarDecl *IterationVar = VarDecl::Create( 8081 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 8082 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 8083 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8084 IterationVar->setInit( 8085 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8086 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 8087 8088 auto IterRef = [&] { 8089 ExprResult Ref = S.BuildDeclarationNameExpr( 8090 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 8091 IterationVar); 8092 assert(!Ref.isInvalid() && "can't reference our own variable?"); 8093 return Ref.get(); 8094 }; 8095 8096 // Build 'i$n != Size'. 8097 ExprResult Cond = S.CreateBuiltinBinOp( 8098 Loc, BO_NE, IterRef(), 8099 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 8100 assert(!Cond.isInvalid() && "should never fail"); 8101 8102 // Build '++i$n'. 8103 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 8104 assert(!Inc.isInvalid() && "should never fail"); 8105 8106 // Build 'a[i$n]' and 'b[i$n]'. 8107 auto Index = [&](ExprResult E) { 8108 if (E.isInvalid()) 8109 return ExprError(); 8110 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 8111 }; 8112 Subobj.first = Index(Subobj.first); 8113 Subobj.second = Index(Subobj.second); 8114 8115 // Compare the array elements. 8116 ++ArrayDepth; 8117 StmtResult Substmt = visitSubobject(Type, Subobj); 8118 --ArrayDepth; 8119 8120 if (Substmt.isInvalid()) 8121 return StmtError(); 8122 8123 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 8124 // For outer levels or for an 'operator<=>' we already have a suitable 8125 // statement that returns as necessary. 8126 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 8127 assert(DCK == DefaultedComparisonKind::Equal && 8128 "should have non-expression statement"); 8129 Substmt = buildIfNotCondReturnFalse(ElemCmp); 8130 if (Substmt.isInvalid()) 8131 return StmtError(); 8132 } 8133 8134 // Build 'for (...) ...' 8135 return S.ActOnForStmt(Loc, Loc, Init, 8136 S.ActOnCondition(nullptr, Loc, Cond.get(), 8137 Sema::ConditionKind::Boolean), 8138 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 8139 Substmt.get()); 8140 } 8141 8142 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 8143 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8144 return StmtError(); 8145 8146 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 8147 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); 8148 ExprResult Op; 8149 if (Type->isOverloadableType()) 8150 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(), 8151 Obj.second.get(), /*PerformADL=*/true, 8152 /*AllowRewrittenCandidates=*/true, FD); 8153 else 8154 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get()); 8155 if (Op.isInvalid()) 8156 return StmtError(); 8157 8158 switch (DCK) { 8159 case DefaultedComparisonKind::None: 8160 llvm_unreachable("not a defaulted comparison"); 8161 8162 case DefaultedComparisonKind::Equal: 8163 // Per C++2a [class.eq]p2, each comparison is individually contextually 8164 // converted to bool. 8165 Op = S.PerformContextuallyConvertToBool(Op.get()); 8166 if (Op.isInvalid()) 8167 return StmtError(); 8168 return Op.get(); 8169 8170 case DefaultedComparisonKind::ThreeWay: { 8171 // Per C++2a [class.spaceship]p3, form: 8172 // if (R cmp = static_cast<R>(op); cmp != 0) 8173 // return cmp; 8174 QualType R = FD->getReturnType(); 8175 Op = buildStaticCastToR(Op.get()); 8176 if (Op.isInvalid()) 8177 return StmtError(); 8178 8179 // R cmp = ...; 8180 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 8181 VarDecl *VD = 8182 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 8183 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 8184 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 8185 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 8186 8187 // cmp != 0 8188 ExprResult VDRef = getDecl(VD); 8189 if (VDRef.isInvalid()) 8190 return StmtError(); 8191 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 8192 Expr *Zero = 8193 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 8194 ExprResult Comp; 8195 if (VDRef.get()->getType()->isOverloadableType()) 8196 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true, 8197 true, FD); 8198 else 8199 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero); 8200 if (Comp.isInvalid()) 8201 return StmtError(); 8202 Sema::ConditionResult Cond = S.ActOnCondition( 8203 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 8204 if (Cond.isInvalid()) 8205 return StmtError(); 8206 8207 // return cmp; 8208 VDRef = getDecl(VD); 8209 if (VDRef.isInvalid()) 8210 return StmtError(); 8211 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 8212 if (ReturnStmt.isInvalid()) 8213 return StmtError(); 8214 8215 // if (...) 8216 return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc, 8217 ReturnStmt.get(), 8218 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr); 8219 } 8220 8221 case DefaultedComparisonKind::NotEqual: 8222 case DefaultedComparisonKind::Relational: 8223 // C++2a [class.compare.secondary]p2: 8224 // Otherwise, the operator function yields x @ y. 8225 return Op.get(); 8226 } 8227 llvm_unreachable(""); 8228 } 8229 8230 /// Build "static_cast<R>(E)". 8231 ExprResult buildStaticCastToR(Expr *E) { 8232 QualType R = FD->getReturnType(); 8233 assert(!R->isUndeducedType() && "type should have been deduced already"); 8234 8235 // Don't bother forming a no-op cast in the common case. 8236 if (E->isRValue() && S.Context.hasSameType(E->getType(), R)) 8237 return E; 8238 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 8239 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 8240 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 8241 } 8242 }; 8243 } 8244 8245 /// Perform the unqualified lookups that might be needed to form a defaulted 8246 /// comparison function for the given operator. 8247 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 8248 UnresolvedSetImpl &Operators, 8249 OverloadedOperatorKind Op) { 8250 auto Lookup = [&](OverloadedOperatorKind OO) { 8251 Self.LookupOverloadedOperatorName(OO, S, Operators); 8252 }; 8253 8254 // Every defaulted operator looks up itself. 8255 Lookup(Op); 8256 // ... and the rewritten form of itself, if any. 8257 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 8258 Lookup(ExtraOp); 8259 8260 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 8261 // synthesize a three-way comparison from '<' and '=='. In a dependent 8262 // context, we also need to look up '==' in case we implicitly declare a 8263 // defaulted 'operator=='. 8264 if (Op == OO_Spaceship) { 8265 Lookup(OO_ExclaimEqual); 8266 Lookup(OO_Less); 8267 Lookup(OO_EqualEqual); 8268 } 8269 } 8270 8271 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 8272 DefaultedComparisonKind DCK) { 8273 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison"); 8274 8275 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 8276 assert(RD && "defaulted comparison is not defaulted in a class"); 8277 8278 // Perform any unqualified lookups we're going to need to default this 8279 // function. 8280 if (S) { 8281 UnresolvedSet<32> Operators; 8282 lookupOperatorsForDefaultedComparison(*this, S, Operators, 8283 FD->getOverloadedOperator()); 8284 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 8285 Context, Operators.pairs())); 8286 } 8287 8288 // C++2a [class.compare.default]p1: 8289 // A defaulted comparison operator function for some class C shall be a 8290 // non-template function declared in the member-specification of C that is 8291 // -- a non-static const member of C having one parameter of type 8292 // const C&, or 8293 // -- a friend of C having two parameters of type const C& or two 8294 // parameters of type C. 8295 QualType ExpectedParmType1 = Context.getRecordType(RD); 8296 QualType ExpectedParmType2 = 8297 Context.getLValueReferenceType(ExpectedParmType1.withConst()); 8298 if (isa<CXXMethodDecl>(FD)) 8299 ExpectedParmType1 = ExpectedParmType2; 8300 for (const ParmVarDecl *Param : FD->parameters()) { 8301 if (!Param->getType()->isDependentType() && 8302 !Context.hasSameType(Param->getType(), ExpectedParmType1) && 8303 !Context.hasSameType(Param->getType(), ExpectedParmType2)) { 8304 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8305 // corresponding defaulted 'operator<=>' already. 8306 if (!FD->isImplicit()) { 8307 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 8308 << (int)DCK << Param->getType() << ExpectedParmType1 8309 << !isa<CXXMethodDecl>(FD) 8310 << ExpectedParmType2 << Param->getSourceRange(); 8311 } 8312 return true; 8313 } 8314 } 8315 if (FD->getNumParams() == 2 && 8316 !Context.hasSameType(FD->getParamDecl(0)->getType(), 8317 FD->getParamDecl(1)->getType())) { 8318 if (!FD->isImplicit()) { 8319 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 8320 << (int)DCK 8321 << FD->getParamDecl(0)->getType() 8322 << FD->getParamDecl(0)->getSourceRange() 8323 << FD->getParamDecl(1)->getType() 8324 << FD->getParamDecl(1)->getSourceRange(); 8325 } 8326 return true; 8327 } 8328 8329 // ... non-static const member ... 8330 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 8331 assert(!MD->isStatic() && "comparison function cannot be a static member"); 8332 if (!MD->isConst()) { 8333 SourceLocation InsertLoc; 8334 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 8335 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 8336 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8337 // corresponding defaulted 'operator<=>' already. 8338 if (!MD->isImplicit()) { 8339 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 8340 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 8341 } 8342 8343 // Add the 'const' to the type to recover. 8344 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 8345 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8346 EPI.TypeQuals.addConst(); 8347 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8348 FPT->getParamTypes(), EPI)); 8349 } 8350 } else { 8351 // A non-member function declared in a class must be a friend. 8352 assert(FD->getFriendObjectKind() && "expected a friend declaration"); 8353 } 8354 8355 // C++2a [class.eq]p1, [class.rel]p1: 8356 // A [defaulted comparison other than <=>] shall have a declared return 8357 // type bool. 8358 if (DCK != DefaultedComparisonKind::ThreeWay && 8359 !FD->getDeclaredReturnType()->isDependentType() && 8360 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8361 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8362 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8363 << FD->getReturnTypeSourceRange(); 8364 return true; 8365 } 8366 // C++2a [class.spaceship]p2 [P2002R0]: 8367 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8368 // R shall not contain a placeholder type. 8369 if (DCK == DefaultedComparisonKind::ThreeWay && 8370 FD->getDeclaredReturnType()->getContainedDeducedType() && 8371 !Context.hasSameType(FD->getDeclaredReturnType(), 8372 Context.getAutoDeductType())) { 8373 Diag(FD->getLocation(), 8374 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8375 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8376 << FD->getReturnTypeSourceRange(); 8377 return true; 8378 } 8379 8380 // For a defaulted function in a dependent class, defer all remaining checks 8381 // until instantiation. 8382 if (RD->isDependentType()) 8383 return false; 8384 8385 // Determine whether the function should be defined as deleted. 8386 DefaultedComparisonInfo Info = 8387 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8388 8389 bool First = FD == FD->getCanonicalDecl(); 8390 8391 // If we want to delete the function, then do so; there's nothing else to 8392 // check in that case. 8393 if (Info.Deleted) { 8394 if (!First) { 8395 // C++11 [dcl.fct.def.default]p4: 8396 // [For a] user-provided explicitly-defaulted function [...] if such a 8397 // function is implicitly defined as deleted, the program is ill-formed. 8398 // 8399 // This is really just a consequence of the general rule that you can 8400 // only delete a function on its first declaration. 8401 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8402 << FD->isImplicit() << (int)DCK; 8403 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8404 DefaultedComparisonAnalyzer::ExplainDeleted) 8405 .visit(); 8406 return true; 8407 } 8408 8409 SetDeclDeleted(FD, FD->getLocation()); 8410 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8411 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8412 << (int)DCK; 8413 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8414 DefaultedComparisonAnalyzer::ExplainDeleted) 8415 .visit(); 8416 } 8417 return false; 8418 } 8419 8420 // C++2a [class.spaceship]p2: 8421 // The return type is deduced as the common comparison type of R0, R1, ... 8422 if (DCK == DefaultedComparisonKind::ThreeWay && 8423 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8424 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8425 if (RetLoc.isInvalid()) 8426 RetLoc = FD->getBeginLoc(); 8427 // FIXME: Should we really care whether we have the complete type and the 8428 // 'enumerator' constants here? A forward declaration seems sufficient. 8429 QualType Cat = CheckComparisonCategoryType( 8430 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8431 if (Cat.isNull()) 8432 return true; 8433 Context.adjustDeducedFunctionResultType( 8434 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8435 } 8436 8437 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8438 // An explicitly-defaulted function that is not defined as deleted may be 8439 // declared constexpr or consteval only if it is constexpr-compatible. 8440 // C++2a [class.compare.default]p3 [P2002R0]: 8441 // A defaulted comparison function is constexpr-compatible if it satisfies 8442 // the requirements for a constexpr function [...] 8443 // The only relevant requirements are that the parameter and return types are 8444 // literal types. The remaining conditions are checked by the analyzer. 8445 if (FD->isConstexpr()) { 8446 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8447 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8448 !Info.Constexpr) { 8449 Diag(FD->getBeginLoc(), 8450 diag::err_incorrect_defaulted_comparison_constexpr) 8451 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8452 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8453 DefaultedComparisonAnalyzer::ExplainConstexpr) 8454 .visit(); 8455 } 8456 } 8457 8458 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8459 // If a constexpr-compatible function is explicitly defaulted on its first 8460 // declaration, it is implicitly considered to be constexpr. 8461 // FIXME: Only applying this to the first declaration seems problematic, as 8462 // simple reorderings can affect the meaning of the program. 8463 if (First && !FD->isConstexpr() && Info.Constexpr) 8464 FD->setConstexprKind(ConstexprSpecKind::Constexpr); 8465 8466 // C++2a [except.spec]p3: 8467 // If a declaration of a function does not have a noexcept-specifier 8468 // [and] is defaulted on its first declaration, [...] the exception 8469 // specification is as specified below 8470 if (FD->getExceptionSpecType() == EST_None) { 8471 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8472 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8473 EPI.ExceptionSpec.Type = EST_Unevaluated; 8474 EPI.ExceptionSpec.SourceDecl = FD; 8475 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8476 FPT->getParamTypes(), EPI)); 8477 } 8478 8479 return false; 8480 } 8481 8482 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8483 FunctionDecl *Spaceship) { 8484 Sema::CodeSynthesisContext Ctx; 8485 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8486 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8487 Ctx.Entity = Spaceship; 8488 pushCodeSynthesisContext(Ctx); 8489 8490 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8491 EqualEqual->setImplicit(); 8492 8493 popCodeSynthesisContext(); 8494 } 8495 8496 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8497 DefaultedComparisonKind DCK) { 8498 assert(FD->isDefaulted() && !FD->isDeleted() && 8499 !FD->doesThisDeclarationHaveABody()); 8500 if (FD->willHaveBody() || FD->isInvalidDecl()) 8501 return; 8502 8503 SynthesizedFunctionScope Scope(*this, FD); 8504 8505 // Add a context note for diagnostics produced after this point. 8506 Scope.addContextNote(UseLoc); 8507 8508 { 8509 // Build and set up the function body. 8510 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8511 SourceLocation BodyLoc = 8512 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8513 StmtResult Body = 8514 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8515 if (Body.isInvalid()) { 8516 FD->setInvalidDecl(); 8517 return; 8518 } 8519 FD->setBody(Body.get()); 8520 FD->markUsed(Context); 8521 } 8522 8523 // The exception specification is needed because we are defining the 8524 // function. Note that this will reuse the body we just built. 8525 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8526 8527 if (ASTMutationListener *L = getASTMutationListener()) 8528 L->CompletedImplicitDefinition(FD); 8529 } 8530 8531 static Sema::ImplicitExceptionSpecification 8532 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8533 FunctionDecl *FD, 8534 Sema::DefaultedComparisonKind DCK) { 8535 ComputingExceptionSpec CES(S, FD, Loc); 8536 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8537 8538 if (FD->isInvalidDecl()) 8539 return ExceptSpec; 8540 8541 // The common case is that we just defined the comparison function. In that 8542 // case, just look at whether the body can throw. 8543 if (FD->hasBody()) { 8544 ExceptSpec.CalledStmt(FD->getBody()); 8545 } else { 8546 // Otherwise, build a body so we can check it. This should ideally only 8547 // happen when we're not actually marking the function referenced. (This is 8548 // only really important for efficiency: we don't want to build and throw 8549 // away bodies for comparison functions more than we strictly need to.) 8550 8551 // Pretend to synthesize the function body in an unevaluated context. 8552 // Note that we can't actually just go ahead and define the function here: 8553 // we are not permitted to mark its callees as referenced. 8554 Sema::SynthesizedFunctionScope Scope(S, FD); 8555 EnterExpressionEvaluationContext Context( 8556 S, Sema::ExpressionEvaluationContext::Unevaluated); 8557 8558 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8559 SourceLocation BodyLoc = 8560 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8561 StmtResult Body = 8562 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8563 if (!Body.isInvalid()) 8564 ExceptSpec.CalledStmt(Body.get()); 8565 8566 // FIXME: Can we hold onto this body and just transform it to potentially 8567 // evaluated when we're asked to define the function rather than rebuilding 8568 // it? Either that, or we should only build the bits of the body that we 8569 // need (the expressions, not the statements). 8570 } 8571 8572 return ExceptSpec; 8573 } 8574 8575 void Sema::CheckDelayedMemberExceptionSpecs() { 8576 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8577 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8578 8579 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8580 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8581 8582 // Perform any deferred checking of exception specifications for virtual 8583 // destructors. 8584 for (auto &Check : Overriding) 8585 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8586 8587 // Perform any deferred checking of exception specifications for befriended 8588 // special members. 8589 for (auto &Check : Equivalent) 8590 CheckEquivalentExceptionSpec(Check.second, Check.first); 8591 } 8592 8593 namespace { 8594 /// CRTP base class for visiting operations performed by a special member 8595 /// function (or inherited constructor). 8596 template<typename Derived> 8597 struct SpecialMemberVisitor { 8598 Sema &S; 8599 CXXMethodDecl *MD; 8600 Sema::CXXSpecialMember CSM; 8601 Sema::InheritedConstructorInfo *ICI; 8602 8603 // Properties of the special member, computed for convenience. 8604 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8605 8606 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8607 Sema::InheritedConstructorInfo *ICI) 8608 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8609 switch (CSM) { 8610 case Sema::CXXDefaultConstructor: 8611 case Sema::CXXCopyConstructor: 8612 case Sema::CXXMoveConstructor: 8613 IsConstructor = true; 8614 break; 8615 case Sema::CXXCopyAssignment: 8616 case Sema::CXXMoveAssignment: 8617 IsAssignment = true; 8618 break; 8619 case Sema::CXXDestructor: 8620 break; 8621 case Sema::CXXInvalid: 8622 llvm_unreachable("invalid special member kind"); 8623 } 8624 8625 if (MD->getNumParams()) { 8626 if (const ReferenceType *RT = 8627 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8628 ConstArg = RT->getPointeeType().isConstQualified(); 8629 } 8630 } 8631 8632 Derived &getDerived() { return static_cast<Derived&>(*this); } 8633 8634 /// Is this a "move" special member? 8635 bool isMove() const { 8636 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8637 } 8638 8639 /// Look up the corresponding special member in the given class. 8640 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8641 unsigned Quals, bool IsMutable) { 8642 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8643 ConstArg && !IsMutable); 8644 } 8645 8646 /// Look up the constructor for the specified base class to see if it's 8647 /// overridden due to this being an inherited constructor. 8648 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8649 if (!ICI) 8650 return {}; 8651 assert(CSM == Sema::CXXDefaultConstructor); 8652 auto *BaseCtor = 8653 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8654 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8655 return MD; 8656 return {}; 8657 } 8658 8659 /// A base or member subobject. 8660 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8661 8662 /// Get the location to use for a subobject in diagnostics. 8663 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8664 // FIXME: For an indirect virtual base, the direct base leading to 8665 // the indirect virtual base would be a more useful choice. 8666 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8667 return B->getBaseTypeLoc(); 8668 else 8669 return Subobj.get<FieldDecl*>()->getLocation(); 8670 } 8671 8672 enum BasesToVisit { 8673 /// Visit all non-virtual (direct) bases. 8674 VisitNonVirtualBases, 8675 /// Visit all direct bases, virtual or not. 8676 VisitDirectBases, 8677 /// Visit all non-virtual bases, and all virtual bases if the class 8678 /// is not abstract. 8679 VisitPotentiallyConstructedBases, 8680 /// Visit all direct or virtual bases. 8681 VisitAllBases 8682 }; 8683 8684 // Visit the bases and members of the class. 8685 bool visit(BasesToVisit Bases) { 8686 CXXRecordDecl *RD = MD->getParent(); 8687 8688 if (Bases == VisitPotentiallyConstructedBases) 8689 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8690 8691 for (auto &B : RD->bases()) 8692 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8693 getDerived().visitBase(&B)) 8694 return true; 8695 8696 if (Bases == VisitAllBases) 8697 for (auto &B : RD->vbases()) 8698 if (getDerived().visitBase(&B)) 8699 return true; 8700 8701 for (auto *F : RD->fields()) 8702 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8703 getDerived().visitField(F)) 8704 return true; 8705 8706 return false; 8707 } 8708 }; 8709 } 8710 8711 namespace { 8712 struct SpecialMemberDeletionInfo 8713 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8714 bool Diagnose; 8715 8716 SourceLocation Loc; 8717 8718 bool AllFieldsAreConst; 8719 8720 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 8721 Sema::CXXSpecialMember CSM, 8722 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 8723 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 8724 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 8725 8726 bool inUnion() const { return MD->getParent()->isUnion(); } 8727 8728 Sema::CXXSpecialMember getEffectiveCSM() { 8729 return ICI ? Sema::CXXInvalid : CSM; 8730 } 8731 8732 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 8733 8734 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 8735 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 8736 8737 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 8738 bool shouldDeleteForField(FieldDecl *FD); 8739 bool shouldDeleteForAllConstMembers(); 8740 8741 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 8742 unsigned Quals); 8743 bool shouldDeleteForSubobjectCall(Subobject Subobj, 8744 Sema::SpecialMemberOverloadResult SMOR, 8745 bool IsDtorCallInCtor); 8746 8747 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 8748 }; 8749 } 8750 8751 /// Is the given special member inaccessible when used on the given 8752 /// sub-object. 8753 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 8754 CXXMethodDecl *target) { 8755 /// If we're operating on a base class, the object type is the 8756 /// type of this special member. 8757 QualType objectTy; 8758 AccessSpecifier access = target->getAccess(); 8759 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 8760 objectTy = S.Context.getTypeDeclType(MD->getParent()); 8761 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 8762 8763 // If we're operating on a field, the object type is the type of the field. 8764 } else { 8765 objectTy = S.Context.getTypeDeclType(target->getParent()); 8766 } 8767 8768 return S.isMemberAccessibleForDeletion( 8769 target->getParent(), DeclAccessPair::make(target, access), objectTy); 8770 } 8771 8772 /// Check whether we should delete a special member due to the implicit 8773 /// definition containing a call to a special member of a subobject. 8774 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 8775 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 8776 bool IsDtorCallInCtor) { 8777 CXXMethodDecl *Decl = SMOR.getMethod(); 8778 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8779 8780 int DiagKind = -1; 8781 8782 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 8783 DiagKind = !Decl ? 0 : 1; 8784 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 8785 DiagKind = 2; 8786 else if (!isAccessible(Subobj, Decl)) 8787 DiagKind = 3; 8788 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 8789 !Decl->isTrivial()) { 8790 // A member of a union must have a trivial corresponding special member. 8791 // As a weird special case, a destructor call from a union's constructor 8792 // must be accessible and non-deleted, but need not be trivial. Such a 8793 // destructor is never actually called, but is semantically checked as 8794 // if it were. 8795 DiagKind = 4; 8796 } 8797 8798 if (DiagKind == -1) 8799 return false; 8800 8801 if (Diagnose) { 8802 if (Field) { 8803 S.Diag(Field->getLocation(), 8804 diag::note_deleted_special_member_class_subobject) 8805 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 8806 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 8807 } else { 8808 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 8809 S.Diag(Base->getBeginLoc(), 8810 diag::note_deleted_special_member_class_subobject) 8811 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8812 << Base->getType() << DiagKind << IsDtorCallInCtor 8813 << /*IsObjCPtr*/false; 8814 } 8815 8816 if (DiagKind == 1) 8817 S.NoteDeletedFunction(Decl); 8818 // FIXME: Explain inaccessibility if DiagKind == 3. 8819 } 8820 8821 return true; 8822 } 8823 8824 /// Check whether we should delete a special member function due to having a 8825 /// direct or virtual base class or non-static data member of class type M. 8826 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 8827 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 8828 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8829 bool IsMutable = Field && Field->isMutable(); 8830 8831 // C++11 [class.ctor]p5: 8832 // -- any direct or virtual base class, or non-static data member with no 8833 // brace-or-equal-initializer, has class type M (or array thereof) and 8834 // either M has no default constructor or overload resolution as applied 8835 // to M's default constructor results in an ambiguity or in a function 8836 // that is deleted or inaccessible 8837 // C++11 [class.copy]p11, C++11 [class.copy]p23: 8838 // -- a direct or virtual base class B that cannot be copied/moved because 8839 // overload resolution, as applied to B's corresponding special member, 8840 // results in an ambiguity or a function that is deleted or inaccessible 8841 // from the defaulted special member 8842 // C++11 [class.dtor]p5: 8843 // -- any direct or virtual base class [...] has a type with a destructor 8844 // that is deleted or inaccessible 8845 if (!(CSM == Sema::CXXDefaultConstructor && 8846 Field && Field->hasInClassInitializer()) && 8847 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 8848 false)) 8849 return true; 8850 8851 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 8852 // -- any direct or virtual base class or non-static data member has a 8853 // type with a destructor that is deleted or inaccessible 8854 if (IsConstructor) { 8855 Sema::SpecialMemberOverloadResult SMOR = 8856 S.LookupSpecialMember(Class, Sema::CXXDestructor, 8857 false, false, false, false, false); 8858 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 8859 return true; 8860 } 8861 8862 return false; 8863 } 8864 8865 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 8866 FieldDecl *FD, QualType FieldType) { 8867 // The defaulted special functions are defined as deleted if this is a variant 8868 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 8869 // type under ARC. 8870 if (!FieldType.hasNonTrivialObjCLifetime()) 8871 return false; 8872 8873 // Don't make the defaulted default constructor defined as deleted if the 8874 // member has an in-class initializer. 8875 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 8876 return false; 8877 8878 if (Diagnose) { 8879 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 8880 S.Diag(FD->getLocation(), 8881 diag::note_deleted_special_member_class_subobject) 8882 << getEffectiveCSM() << ParentClass << /*IsField*/true 8883 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 8884 } 8885 8886 return true; 8887 } 8888 8889 /// Check whether we should delete a special member function due to the class 8890 /// having a particular direct or virtual base class. 8891 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 8892 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 8893 // If program is correct, BaseClass cannot be null, but if it is, the error 8894 // must be reported elsewhere. 8895 if (!BaseClass) 8896 return false; 8897 // If we have an inheriting constructor, check whether we're calling an 8898 // inherited constructor instead of a default constructor. 8899 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 8900 if (auto *BaseCtor = SMOR.getMethod()) { 8901 // Note that we do not check access along this path; other than that, 8902 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 8903 // FIXME: Check that the base has a usable destructor! Sink this into 8904 // shouldDeleteForClassSubobject. 8905 if (BaseCtor->isDeleted() && Diagnose) { 8906 S.Diag(Base->getBeginLoc(), 8907 diag::note_deleted_special_member_class_subobject) 8908 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8909 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 8910 << /*IsObjCPtr*/false; 8911 S.NoteDeletedFunction(BaseCtor); 8912 } 8913 return BaseCtor->isDeleted(); 8914 } 8915 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 8916 } 8917 8918 /// Check whether we should delete a special member function due to the class 8919 /// having a particular non-static data member. 8920 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 8921 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 8922 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 8923 8924 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 8925 return true; 8926 8927 if (CSM == Sema::CXXDefaultConstructor) { 8928 // For a default constructor, all references must be initialized in-class 8929 // and, if a union, it must have a non-const member. 8930 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 8931 if (Diagnose) 8932 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8933 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 8934 return true; 8935 } 8936 // C++11 [class.ctor]p5: any non-variant non-static data member of 8937 // const-qualified type (or array thereof) with no 8938 // brace-or-equal-initializer does not have a user-provided default 8939 // constructor. 8940 if (!inUnion() && FieldType.isConstQualified() && 8941 !FD->hasInClassInitializer() && 8942 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 8943 if (Diagnose) 8944 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8945 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 8946 return true; 8947 } 8948 8949 if (inUnion() && !FieldType.isConstQualified()) 8950 AllFieldsAreConst = false; 8951 } else if (CSM == Sema::CXXCopyConstructor) { 8952 // For a copy constructor, data members must not be of rvalue reference 8953 // type. 8954 if (FieldType->isRValueReferenceType()) { 8955 if (Diagnose) 8956 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 8957 << MD->getParent() << FD << FieldType; 8958 return true; 8959 } 8960 } else if (IsAssignment) { 8961 // For an assignment operator, data members must not be of reference type. 8962 if (FieldType->isReferenceType()) { 8963 if (Diagnose) 8964 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 8965 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 8966 return true; 8967 } 8968 if (!FieldRecord && FieldType.isConstQualified()) { 8969 // C++11 [class.copy]p23: 8970 // -- a non-static data member of const non-class type (or array thereof) 8971 if (Diagnose) 8972 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 8973 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 8974 return true; 8975 } 8976 } 8977 8978 if (FieldRecord) { 8979 // Some additional restrictions exist on the variant members. 8980 if (!inUnion() && FieldRecord->isUnion() && 8981 FieldRecord->isAnonymousStructOrUnion()) { 8982 bool AllVariantFieldsAreConst = true; 8983 8984 // FIXME: Handle anonymous unions declared within anonymous unions. 8985 for (auto *UI : FieldRecord->fields()) { 8986 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 8987 8988 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 8989 return true; 8990 8991 if (!UnionFieldType.isConstQualified()) 8992 AllVariantFieldsAreConst = false; 8993 8994 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 8995 if (UnionFieldRecord && 8996 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 8997 UnionFieldType.getCVRQualifiers())) 8998 return true; 8999 } 9000 9001 // At least one member in each anonymous union must be non-const 9002 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 9003 !FieldRecord->field_empty()) { 9004 if (Diagnose) 9005 S.Diag(FieldRecord->getLocation(), 9006 diag::note_deleted_default_ctor_all_const) 9007 << !!ICI << MD->getParent() << /*anonymous union*/1; 9008 return true; 9009 } 9010 9011 // Don't check the implicit member of the anonymous union type. 9012 // This is technically non-conformant, but sanity demands it. 9013 return false; 9014 } 9015 9016 if (shouldDeleteForClassSubobject(FieldRecord, FD, 9017 FieldType.getCVRQualifiers())) 9018 return true; 9019 } 9020 9021 return false; 9022 } 9023 9024 /// C++11 [class.ctor] p5: 9025 /// A defaulted default constructor for a class X is defined as deleted if 9026 /// X is a union and all of its variant members are of const-qualified type. 9027 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 9028 // This is a silly definition, because it gives an empty union a deleted 9029 // default constructor. Don't do that. 9030 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 9031 bool AnyFields = false; 9032 for (auto *F : MD->getParent()->fields()) 9033 if ((AnyFields = !F->isUnnamedBitfield())) 9034 break; 9035 if (!AnyFields) 9036 return false; 9037 if (Diagnose) 9038 S.Diag(MD->getParent()->getLocation(), 9039 diag::note_deleted_default_ctor_all_const) 9040 << !!ICI << MD->getParent() << /*not anonymous union*/0; 9041 return true; 9042 } 9043 return false; 9044 } 9045 9046 /// Determine whether a defaulted special member function should be defined as 9047 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 9048 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 9049 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 9050 InheritedConstructorInfo *ICI, 9051 bool Diagnose) { 9052 if (MD->isInvalidDecl()) 9053 return false; 9054 CXXRecordDecl *RD = MD->getParent(); 9055 assert(!RD->isDependentType() && "do deletion after instantiation"); 9056 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 9057 return false; 9058 9059 // C++11 [expr.lambda.prim]p19: 9060 // The closure type associated with a lambda-expression has a 9061 // deleted (8.4.3) default constructor and a deleted copy 9062 // assignment operator. 9063 // C++2a adds back these operators if the lambda has no lambda-capture. 9064 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 9065 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 9066 if (Diagnose) 9067 Diag(RD->getLocation(), diag::note_lambda_decl); 9068 return true; 9069 } 9070 9071 // For an anonymous struct or union, the copy and assignment special members 9072 // will never be used, so skip the check. For an anonymous union declared at 9073 // namespace scope, the constructor and destructor are used. 9074 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 9075 RD->isAnonymousStructOrUnion()) 9076 return false; 9077 9078 // C++11 [class.copy]p7, p18: 9079 // If the class definition declares a move constructor or move assignment 9080 // operator, an implicitly declared copy constructor or copy assignment 9081 // operator is defined as deleted. 9082 if (MD->isImplicit() && 9083 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 9084 CXXMethodDecl *UserDeclaredMove = nullptr; 9085 9086 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 9087 // deletion of the corresponding copy operation, not both copy operations. 9088 // MSVC 2015 has adopted the standards conforming behavior. 9089 bool DeletesOnlyMatchingCopy = 9090 getLangOpts().MSVCCompat && 9091 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 9092 9093 if (RD->hasUserDeclaredMoveConstructor() && 9094 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 9095 if (!Diagnose) return true; 9096 9097 // Find any user-declared move constructor. 9098 for (auto *I : RD->ctors()) { 9099 if (I->isMoveConstructor()) { 9100 UserDeclaredMove = I; 9101 break; 9102 } 9103 } 9104 assert(UserDeclaredMove); 9105 } else if (RD->hasUserDeclaredMoveAssignment() && 9106 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 9107 if (!Diagnose) return true; 9108 9109 // Find any user-declared move assignment operator. 9110 for (auto *I : RD->methods()) { 9111 if (I->isMoveAssignmentOperator()) { 9112 UserDeclaredMove = I; 9113 break; 9114 } 9115 } 9116 assert(UserDeclaredMove); 9117 } 9118 9119 if (UserDeclaredMove) { 9120 Diag(UserDeclaredMove->getLocation(), 9121 diag::note_deleted_copy_user_declared_move) 9122 << (CSM == CXXCopyAssignment) << RD 9123 << UserDeclaredMove->isMoveAssignmentOperator(); 9124 return true; 9125 } 9126 } 9127 9128 // Do access control from the special member function 9129 ContextRAII MethodContext(*this, MD); 9130 9131 // C++11 [class.dtor]p5: 9132 // -- for a virtual destructor, lookup of the non-array deallocation function 9133 // results in an ambiguity or in a function that is deleted or inaccessible 9134 if (CSM == CXXDestructor && MD->isVirtual()) { 9135 FunctionDecl *OperatorDelete = nullptr; 9136 DeclarationName Name = 9137 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 9138 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 9139 OperatorDelete, /*Diagnose*/false)) { 9140 if (Diagnose) 9141 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 9142 return true; 9143 } 9144 } 9145 9146 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 9147 9148 // Per DR1611, do not consider virtual bases of constructors of abstract 9149 // classes, since we are not going to construct them. 9150 // Per DR1658, do not consider virtual bases of destructors of abstract 9151 // classes either. 9152 // Per DR2180, for assignment operators we only assign (and thus only 9153 // consider) direct bases. 9154 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 9155 : SMI.VisitPotentiallyConstructedBases)) 9156 return true; 9157 9158 if (SMI.shouldDeleteForAllConstMembers()) 9159 return true; 9160 9161 if (getLangOpts().CUDA) { 9162 // We should delete the special member in CUDA mode if target inference 9163 // failed. 9164 // For inherited constructors (non-null ICI), CSM may be passed so that MD 9165 // is treated as certain special member, which may not reflect what special 9166 // member MD really is. However inferCUDATargetForImplicitSpecialMember 9167 // expects CSM to match MD, therefore recalculate CSM. 9168 assert(ICI || CSM == getSpecialMember(MD)); 9169 auto RealCSM = CSM; 9170 if (ICI) 9171 RealCSM = getSpecialMember(MD); 9172 9173 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 9174 SMI.ConstArg, Diagnose); 9175 } 9176 9177 return false; 9178 } 9179 9180 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 9181 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 9182 assert(DFK && "not a defaultable function"); 9183 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted"); 9184 9185 if (DFK.isSpecialMember()) { 9186 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 9187 nullptr, /*Diagnose=*/true); 9188 } else { 9189 DefaultedComparisonAnalyzer( 9190 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 9191 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 9192 .visit(); 9193 } 9194 } 9195 9196 /// Perform lookup for a special member of the specified kind, and determine 9197 /// whether it is trivial. If the triviality can be determined without the 9198 /// lookup, skip it. This is intended for use when determining whether a 9199 /// special member of a containing object is trivial, and thus does not ever 9200 /// perform overload resolution for default constructors. 9201 /// 9202 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 9203 /// member that was most likely to be intended to be trivial, if any. 9204 /// 9205 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 9206 /// determine whether the special member is trivial. 9207 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 9208 Sema::CXXSpecialMember CSM, unsigned Quals, 9209 bool ConstRHS, 9210 Sema::TrivialABIHandling TAH, 9211 CXXMethodDecl **Selected) { 9212 if (Selected) 9213 *Selected = nullptr; 9214 9215 switch (CSM) { 9216 case Sema::CXXInvalid: 9217 llvm_unreachable("not a special member"); 9218 9219 case Sema::CXXDefaultConstructor: 9220 // C++11 [class.ctor]p5: 9221 // A default constructor is trivial if: 9222 // - all the [direct subobjects] have trivial default constructors 9223 // 9224 // Note, no overload resolution is performed in this case. 9225 if (RD->hasTrivialDefaultConstructor()) 9226 return true; 9227 9228 if (Selected) { 9229 // If there's a default constructor which could have been trivial, dig it 9230 // out. Otherwise, if there's any user-provided default constructor, point 9231 // to that as an example of why there's not a trivial one. 9232 CXXConstructorDecl *DefCtor = nullptr; 9233 if (RD->needsImplicitDefaultConstructor()) 9234 S.DeclareImplicitDefaultConstructor(RD); 9235 for (auto *CI : RD->ctors()) { 9236 if (!CI->isDefaultConstructor()) 9237 continue; 9238 DefCtor = CI; 9239 if (!DefCtor->isUserProvided()) 9240 break; 9241 } 9242 9243 *Selected = DefCtor; 9244 } 9245 9246 return false; 9247 9248 case Sema::CXXDestructor: 9249 // C++11 [class.dtor]p5: 9250 // A destructor is trivial if: 9251 // - all the direct [subobjects] have trivial destructors 9252 if (RD->hasTrivialDestructor() || 9253 (TAH == Sema::TAH_ConsiderTrivialABI && 9254 RD->hasTrivialDestructorForCall())) 9255 return true; 9256 9257 if (Selected) { 9258 if (RD->needsImplicitDestructor()) 9259 S.DeclareImplicitDestructor(RD); 9260 *Selected = RD->getDestructor(); 9261 } 9262 9263 return false; 9264 9265 case Sema::CXXCopyConstructor: 9266 // C++11 [class.copy]p12: 9267 // A copy constructor is trivial if: 9268 // - the constructor selected to copy each direct [subobject] is trivial 9269 if (RD->hasTrivialCopyConstructor() || 9270 (TAH == Sema::TAH_ConsiderTrivialABI && 9271 RD->hasTrivialCopyConstructorForCall())) { 9272 if (Quals == Qualifiers::Const) 9273 // We must either select the trivial copy constructor or reach an 9274 // ambiguity; no need to actually perform overload resolution. 9275 return true; 9276 } else if (!Selected) { 9277 return false; 9278 } 9279 // In C++98, we are not supposed to perform overload resolution here, but we 9280 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 9281 // cases like B as having a non-trivial copy constructor: 9282 // struct A { template<typename T> A(T&); }; 9283 // struct B { mutable A a; }; 9284 goto NeedOverloadResolution; 9285 9286 case Sema::CXXCopyAssignment: 9287 // C++11 [class.copy]p25: 9288 // A copy assignment operator is trivial if: 9289 // - the assignment operator selected to copy each direct [subobject] is 9290 // trivial 9291 if (RD->hasTrivialCopyAssignment()) { 9292 if (Quals == Qualifiers::Const) 9293 return true; 9294 } else if (!Selected) { 9295 return false; 9296 } 9297 // In C++98, we are not supposed to perform overload resolution here, but we 9298 // treat that as a language defect. 9299 goto NeedOverloadResolution; 9300 9301 case Sema::CXXMoveConstructor: 9302 case Sema::CXXMoveAssignment: 9303 NeedOverloadResolution: 9304 Sema::SpecialMemberOverloadResult SMOR = 9305 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 9306 9307 // The standard doesn't describe how to behave if the lookup is ambiguous. 9308 // We treat it as not making the member non-trivial, just like the standard 9309 // mandates for the default constructor. This should rarely matter, because 9310 // the member will also be deleted. 9311 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9312 return true; 9313 9314 if (!SMOR.getMethod()) { 9315 assert(SMOR.getKind() == 9316 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 9317 return false; 9318 } 9319 9320 // We deliberately don't check if we found a deleted special member. We're 9321 // not supposed to! 9322 if (Selected) 9323 *Selected = SMOR.getMethod(); 9324 9325 if (TAH == Sema::TAH_ConsiderTrivialABI && 9326 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 9327 return SMOR.getMethod()->isTrivialForCall(); 9328 return SMOR.getMethod()->isTrivial(); 9329 } 9330 9331 llvm_unreachable("unknown special method kind"); 9332 } 9333 9334 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 9335 for (auto *CI : RD->ctors()) 9336 if (!CI->isImplicit()) 9337 return CI; 9338 9339 // Look for constructor templates. 9340 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 9341 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 9342 if (CXXConstructorDecl *CD = 9343 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 9344 return CD; 9345 } 9346 9347 return nullptr; 9348 } 9349 9350 /// The kind of subobject we are checking for triviality. The values of this 9351 /// enumeration are used in diagnostics. 9352 enum TrivialSubobjectKind { 9353 /// The subobject is a base class. 9354 TSK_BaseClass, 9355 /// The subobject is a non-static data member. 9356 TSK_Field, 9357 /// The object is actually the complete object. 9358 TSK_CompleteObject 9359 }; 9360 9361 /// Check whether the special member selected for a given type would be trivial. 9362 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9363 QualType SubType, bool ConstRHS, 9364 Sema::CXXSpecialMember CSM, 9365 TrivialSubobjectKind Kind, 9366 Sema::TrivialABIHandling TAH, bool Diagnose) { 9367 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9368 if (!SubRD) 9369 return true; 9370 9371 CXXMethodDecl *Selected; 9372 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9373 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9374 return true; 9375 9376 if (Diagnose) { 9377 if (ConstRHS) 9378 SubType.addConst(); 9379 9380 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9381 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9382 << Kind << SubType.getUnqualifiedType(); 9383 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9384 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9385 } else if (!Selected) 9386 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9387 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9388 else if (Selected->isUserProvided()) { 9389 if (Kind == TSK_CompleteObject) 9390 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9391 << Kind << SubType.getUnqualifiedType() << CSM; 9392 else { 9393 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9394 << Kind << SubType.getUnqualifiedType() << CSM; 9395 S.Diag(Selected->getLocation(), diag::note_declared_at); 9396 } 9397 } else { 9398 if (Kind != TSK_CompleteObject) 9399 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9400 << Kind << SubType.getUnqualifiedType() << CSM; 9401 9402 // Explain why the defaulted or deleted special member isn't trivial. 9403 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9404 Diagnose); 9405 } 9406 } 9407 9408 return false; 9409 } 9410 9411 /// Check whether the members of a class type allow a special member to be 9412 /// trivial. 9413 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9414 Sema::CXXSpecialMember CSM, 9415 bool ConstArg, 9416 Sema::TrivialABIHandling TAH, 9417 bool Diagnose) { 9418 for (const auto *FI : RD->fields()) { 9419 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9420 continue; 9421 9422 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9423 9424 // Pretend anonymous struct or union members are members of this class. 9425 if (FI->isAnonymousStructOrUnion()) { 9426 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9427 CSM, ConstArg, TAH, Diagnose)) 9428 return false; 9429 continue; 9430 } 9431 9432 // C++11 [class.ctor]p5: 9433 // A default constructor is trivial if [...] 9434 // -- no non-static data member of its class has a 9435 // brace-or-equal-initializer 9436 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9437 if (Diagnose) 9438 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init) 9439 << FI; 9440 return false; 9441 } 9442 9443 // Objective C ARC 4.3.5: 9444 // [...] nontrivally ownership-qualified types are [...] not trivially 9445 // default constructible, copy constructible, move constructible, copy 9446 // assignable, move assignable, or destructible [...] 9447 if (FieldType.hasNonTrivialObjCLifetime()) { 9448 if (Diagnose) 9449 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9450 << RD << FieldType.getObjCLifetime(); 9451 return false; 9452 } 9453 9454 bool ConstRHS = ConstArg && !FI->isMutable(); 9455 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9456 CSM, TSK_Field, TAH, Diagnose)) 9457 return false; 9458 } 9459 9460 return true; 9461 } 9462 9463 /// Diagnose why the specified class does not have a trivial special member of 9464 /// the given kind. 9465 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9466 QualType Ty = Context.getRecordType(RD); 9467 9468 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9469 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9470 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9471 /*Diagnose*/true); 9472 } 9473 9474 /// Determine whether a defaulted or deleted special member function is trivial, 9475 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9476 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9477 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9478 TrivialABIHandling TAH, bool Diagnose) { 9479 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 9480 9481 CXXRecordDecl *RD = MD->getParent(); 9482 9483 bool ConstArg = false; 9484 9485 // C++11 [class.copy]p12, p25: [DR1593] 9486 // A [special member] is trivial if [...] its parameter-type-list is 9487 // equivalent to the parameter-type-list of an implicit declaration [...] 9488 switch (CSM) { 9489 case CXXDefaultConstructor: 9490 case CXXDestructor: 9491 // Trivial default constructors and destructors cannot have parameters. 9492 break; 9493 9494 case CXXCopyConstructor: 9495 case CXXCopyAssignment: { 9496 // Trivial copy operations always have const, non-volatile parameter types. 9497 ConstArg = true; 9498 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9499 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9500 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 9501 if (Diagnose) 9502 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9503 << Param0->getSourceRange() << Param0->getType() 9504 << Context.getLValueReferenceType( 9505 Context.getRecordType(RD).withConst()); 9506 return false; 9507 } 9508 break; 9509 } 9510 9511 case CXXMoveConstructor: 9512 case CXXMoveAssignment: { 9513 // Trivial move operations always have non-cv-qualified parameters. 9514 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9515 const RValueReferenceType *RT = 9516 Param0->getType()->getAs<RValueReferenceType>(); 9517 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9518 if (Diagnose) 9519 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9520 << Param0->getSourceRange() << Param0->getType() 9521 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9522 return false; 9523 } 9524 break; 9525 } 9526 9527 case CXXInvalid: 9528 llvm_unreachable("not a special member"); 9529 } 9530 9531 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9532 if (Diagnose) 9533 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9534 diag::note_nontrivial_default_arg) 9535 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9536 return false; 9537 } 9538 if (MD->isVariadic()) { 9539 if (Diagnose) 9540 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9541 return false; 9542 } 9543 9544 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9545 // A copy/move [constructor or assignment operator] is trivial if 9546 // -- the [member] selected to copy/move each direct base class subobject 9547 // is trivial 9548 // 9549 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9550 // A [default constructor or destructor] is trivial if 9551 // -- all the direct base classes have trivial [default constructors or 9552 // destructors] 9553 for (const auto &BI : RD->bases()) 9554 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9555 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9556 return false; 9557 9558 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9559 // A copy/move [constructor or assignment operator] for a class X is 9560 // trivial if 9561 // -- for each non-static data member of X that is of class type (or array 9562 // thereof), the constructor selected to copy/move that member is 9563 // trivial 9564 // 9565 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9566 // A [default constructor or destructor] is trivial if 9567 // -- for all of the non-static data members of its class that are of class 9568 // type (or array thereof), each such class has a trivial [default 9569 // constructor or destructor] 9570 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9571 return false; 9572 9573 // C++11 [class.dtor]p5: 9574 // A destructor is trivial if [...] 9575 // -- the destructor is not virtual 9576 if (CSM == CXXDestructor && MD->isVirtual()) { 9577 if (Diagnose) 9578 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9579 return false; 9580 } 9581 9582 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9583 // A [special member] for class X is trivial if [...] 9584 // -- class X has no virtual functions and no virtual base classes 9585 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9586 if (!Diagnose) 9587 return false; 9588 9589 if (RD->getNumVBases()) { 9590 // Check for virtual bases. We already know that the corresponding 9591 // member in all bases is trivial, so vbases must all be direct. 9592 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9593 assert(BS.isVirtual()); 9594 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9595 return false; 9596 } 9597 9598 // Must have a virtual method. 9599 for (const auto *MI : RD->methods()) { 9600 if (MI->isVirtual()) { 9601 SourceLocation MLoc = MI->getBeginLoc(); 9602 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9603 return false; 9604 } 9605 } 9606 9607 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 9608 } 9609 9610 // Looks like it's trivial! 9611 return true; 9612 } 9613 9614 namespace { 9615 struct FindHiddenVirtualMethod { 9616 Sema *S; 9617 CXXMethodDecl *Method; 9618 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9619 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9620 9621 private: 9622 /// Check whether any most overridden method from MD in Methods 9623 static bool CheckMostOverridenMethods( 9624 const CXXMethodDecl *MD, 9625 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9626 if (MD->size_overridden_methods() == 0) 9627 return Methods.count(MD->getCanonicalDecl()); 9628 for (const CXXMethodDecl *O : MD->overridden_methods()) 9629 if (CheckMostOverridenMethods(O, Methods)) 9630 return true; 9631 return false; 9632 } 9633 9634 public: 9635 /// Member lookup function that determines whether a given C++ 9636 /// method overloads virtual methods in a base class without overriding any, 9637 /// to be used with CXXRecordDecl::lookupInBases(). 9638 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9639 RecordDecl *BaseRecord = 9640 Specifier->getType()->castAs<RecordType>()->getDecl(); 9641 9642 DeclarationName Name = Method->getDeclName(); 9643 assert(Name.getNameKind() == DeclarationName::Identifier); 9644 9645 bool foundSameNameMethod = false; 9646 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9647 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 9648 Path.Decls = Path.Decls.slice(1)) { 9649 NamedDecl *D = Path.Decls.front(); 9650 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9651 MD = MD->getCanonicalDecl(); 9652 foundSameNameMethod = true; 9653 // Interested only in hidden virtual methods. 9654 if (!MD->isVirtual()) 9655 continue; 9656 // If the method we are checking overrides a method from its base 9657 // don't warn about the other overloaded methods. Clang deviates from 9658 // GCC by only diagnosing overloads of inherited virtual functions that 9659 // do not override any other virtual functions in the base. GCC's 9660 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9661 // function from a base class. These cases may be better served by a 9662 // warning (not specific to virtual functions) on call sites when the 9663 // call would select a different function from the base class, were it 9664 // visible. 9665 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9666 if (!S->IsOverload(Method, MD, false)) 9667 return true; 9668 // Collect the overload only if its hidden. 9669 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9670 overloadedMethods.push_back(MD); 9671 } 9672 } 9673 9674 if (foundSameNameMethod) 9675 OverloadedMethods.append(overloadedMethods.begin(), 9676 overloadedMethods.end()); 9677 return foundSameNameMethod; 9678 } 9679 }; 9680 } // end anonymous namespace 9681 9682 /// Add the most overriden methods from MD to Methods 9683 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9684 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9685 if (MD->size_overridden_methods() == 0) 9686 Methods.insert(MD->getCanonicalDecl()); 9687 else 9688 for (const CXXMethodDecl *O : MD->overridden_methods()) 9689 AddMostOverridenMethods(O, Methods); 9690 } 9691 9692 /// Check if a method overloads virtual methods in a base class without 9693 /// overriding any. 9694 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9695 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9696 if (!MD->getDeclName().isIdentifier()) 9697 return; 9698 9699 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9700 /*bool RecordPaths=*/false, 9701 /*bool DetectVirtual=*/false); 9702 FindHiddenVirtualMethod FHVM; 9703 FHVM.Method = MD; 9704 FHVM.S = this; 9705 9706 // Keep the base methods that were overridden or introduced in the subclass 9707 // by 'using' in a set. A base method not in this set is hidden. 9708 CXXRecordDecl *DC = MD->getParent(); 9709 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9710 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9711 NamedDecl *ND = *I; 9712 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9713 ND = shad->getTargetDecl(); 9714 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9715 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9716 } 9717 9718 if (DC->lookupInBases(FHVM, Paths)) 9719 OverloadedMethods = FHVM.OverloadedMethods; 9720 } 9721 9722 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 9723 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9724 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 9725 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 9726 PartialDiagnostic PD = PDiag( 9727 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 9728 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 9729 Diag(overloadedMD->getLocation(), PD); 9730 } 9731 } 9732 9733 /// Diagnose methods which overload virtual methods in a base class 9734 /// without overriding any. 9735 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 9736 if (MD->isInvalidDecl()) 9737 return; 9738 9739 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 9740 return; 9741 9742 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9743 FindHiddenVirtualMethods(MD, OverloadedMethods); 9744 if (!OverloadedMethods.empty()) { 9745 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 9746 << MD << (OverloadedMethods.size() > 1); 9747 9748 NoteHiddenVirtualMethods(MD, OverloadedMethods); 9749 } 9750 } 9751 9752 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 9753 auto PrintDiagAndRemoveAttr = [&](unsigned N) { 9754 // No diagnostics if this is a template instantiation. 9755 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) { 9756 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9757 diag::ext_cannot_use_trivial_abi) << &RD; 9758 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9759 diag::note_cannot_use_trivial_abi_reason) << &RD << N; 9760 } 9761 RD.dropAttr<TrivialABIAttr>(); 9762 }; 9763 9764 // Ill-formed if the copy and move constructors are deleted. 9765 auto HasNonDeletedCopyOrMoveConstructor = [&]() { 9766 // If the type is dependent, then assume it might have 9767 // implicit copy or move ctor because we won't know yet at this point. 9768 if (RD.isDependentType()) 9769 return true; 9770 if (RD.needsImplicitCopyConstructor() && 9771 !RD.defaultedCopyConstructorIsDeleted()) 9772 return true; 9773 if (RD.needsImplicitMoveConstructor() && 9774 !RD.defaultedMoveConstructorIsDeleted()) 9775 return true; 9776 for (const CXXConstructorDecl *CD : RD.ctors()) 9777 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted()) 9778 return true; 9779 return false; 9780 }; 9781 9782 if (!HasNonDeletedCopyOrMoveConstructor()) { 9783 PrintDiagAndRemoveAttr(0); 9784 return; 9785 } 9786 9787 // Ill-formed if the struct has virtual functions. 9788 if (RD.isPolymorphic()) { 9789 PrintDiagAndRemoveAttr(1); 9790 return; 9791 } 9792 9793 for (const auto &B : RD.bases()) { 9794 // Ill-formed if the base class is non-trivial for the purpose of calls or a 9795 // virtual base. 9796 if (!B.getType()->isDependentType() && 9797 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) { 9798 PrintDiagAndRemoveAttr(2); 9799 return; 9800 } 9801 9802 if (B.isVirtual()) { 9803 PrintDiagAndRemoveAttr(3); 9804 return; 9805 } 9806 } 9807 9808 for (const auto *FD : RD.fields()) { 9809 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 9810 // non-trivial for the purpose of calls. 9811 QualType FT = FD->getType(); 9812 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 9813 PrintDiagAndRemoveAttr(4); 9814 return; 9815 } 9816 9817 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 9818 if (!RT->isDependentType() && 9819 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 9820 PrintDiagAndRemoveAttr(5); 9821 return; 9822 } 9823 } 9824 } 9825 9826 void Sema::ActOnFinishCXXMemberSpecification( 9827 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 9828 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 9829 if (!TagDecl) 9830 return; 9831 9832 AdjustDeclIfTemplate(TagDecl); 9833 9834 for (const ParsedAttr &AL : AttrList) { 9835 if (AL.getKind() != ParsedAttr::AT_Visibility) 9836 continue; 9837 AL.setInvalid(); 9838 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 9839 } 9840 9841 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 9842 // strict aliasing violation! 9843 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 9844 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 9845 9846 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 9847 } 9848 9849 /// Find the equality comparison functions that should be implicitly declared 9850 /// in a given class definition, per C++2a [class.compare.default]p3. 9851 static void findImplicitlyDeclaredEqualityComparisons( 9852 ASTContext &Ctx, CXXRecordDecl *RD, 9853 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 9854 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 9855 if (!RD->lookup(EqEq).empty()) 9856 // Member operator== explicitly declared: no implicit operator==s. 9857 return; 9858 9859 // Traverse friends looking for an '==' or a '<=>'. 9860 for (FriendDecl *Friend : RD->friends()) { 9861 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 9862 if (!FD) continue; 9863 9864 if (FD->getOverloadedOperator() == OO_EqualEqual) { 9865 // Friend operator== explicitly declared: no implicit operator==s. 9866 Spaceships.clear(); 9867 return; 9868 } 9869 9870 if (FD->getOverloadedOperator() == OO_Spaceship && 9871 FD->isExplicitlyDefaulted()) 9872 Spaceships.push_back(FD); 9873 } 9874 9875 // Look for members named 'operator<=>'. 9876 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 9877 for (NamedDecl *ND : RD->lookup(Cmp)) { 9878 // Note that we could find a non-function here (either a function template 9879 // or a using-declaration). Neither case results in an implicit 9880 // 'operator=='. 9881 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 9882 if (FD->isExplicitlyDefaulted()) 9883 Spaceships.push_back(FD); 9884 } 9885 } 9886 9887 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 9888 /// special functions, such as the default constructor, copy 9889 /// constructor, or destructor, to the given C++ class (C++ 9890 /// [special]p1). This routine can only be executed just before the 9891 /// definition of the class is complete. 9892 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 9893 // Don't add implicit special members to templated classes. 9894 // FIXME: This means unqualified lookups for 'operator=' within a class 9895 // template don't work properly. 9896 if (!ClassDecl->isDependentType()) { 9897 if (ClassDecl->needsImplicitDefaultConstructor()) { 9898 ++getASTContext().NumImplicitDefaultConstructors; 9899 9900 if (ClassDecl->hasInheritedConstructor()) 9901 DeclareImplicitDefaultConstructor(ClassDecl); 9902 } 9903 9904 if (ClassDecl->needsImplicitCopyConstructor()) { 9905 ++getASTContext().NumImplicitCopyConstructors; 9906 9907 // If the properties or semantics of the copy constructor couldn't be 9908 // determined while the class was being declared, force a declaration 9909 // of it now. 9910 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 9911 ClassDecl->hasInheritedConstructor()) 9912 DeclareImplicitCopyConstructor(ClassDecl); 9913 // For the MS ABI we need to know whether the copy ctor is deleted. A 9914 // prerequisite for deleting the implicit copy ctor is that the class has 9915 // a move ctor or move assignment that is either user-declared or whose 9916 // semantics are inherited from a subobject. FIXME: We should provide a 9917 // more direct way for CodeGen to ask whether the constructor was deleted. 9918 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 9919 (ClassDecl->hasUserDeclaredMoveConstructor() || 9920 ClassDecl->needsOverloadResolutionForMoveConstructor() || 9921 ClassDecl->hasUserDeclaredMoveAssignment() || 9922 ClassDecl->needsOverloadResolutionForMoveAssignment())) 9923 DeclareImplicitCopyConstructor(ClassDecl); 9924 } 9925 9926 if (getLangOpts().CPlusPlus11 && 9927 ClassDecl->needsImplicitMoveConstructor()) { 9928 ++getASTContext().NumImplicitMoveConstructors; 9929 9930 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 9931 ClassDecl->hasInheritedConstructor()) 9932 DeclareImplicitMoveConstructor(ClassDecl); 9933 } 9934 9935 if (ClassDecl->needsImplicitCopyAssignment()) { 9936 ++getASTContext().NumImplicitCopyAssignmentOperators; 9937 9938 // If we have a dynamic class, then the copy assignment operator may be 9939 // virtual, so we have to declare it immediately. This ensures that, e.g., 9940 // it shows up in the right place in the vtable and that we diagnose 9941 // problems with the implicit exception specification. 9942 if (ClassDecl->isDynamicClass() || 9943 ClassDecl->needsOverloadResolutionForCopyAssignment() || 9944 ClassDecl->hasInheritedAssignment()) 9945 DeclareImplicitCopyAssignment(ClassDecl); 9946 } 9947 9948 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 9949 ++getASTContext().NumImplicitMoveAssignmentOperators; 9950 9951 // Likewise for the move assignment operator. 9952 if (ClassDecl->isDynamicClass() || 9953 ClassDecl->needsOverloadResolutionForMoveAssignment() || 9954 ClassDecl->hasInheritedAssignment()) 9955 DeclareImplicitMoveAssignment(ClassDecl); 9956 } 9957 9958 if (ClassDecl->needsImplicitDestructor()) { 9959 ++getASTContext().NumImplicitDestructors; 9960 9961 // If we have a dynamic class, then the destructor may be virtual, so we 9962 // have to declare the destructor immediately. This ensures that, e.g., it 9963 // shows up in the right place in the vtable and that we diagnose problems 9964 // with the implicit exception specification. 9965 if (ClassDecl->isDynamicClass() || 9966 ClassDecl->needsOverloadResolutionForDestructor()) 9967 DeclareImplicitDestructor(ClassDecl); 9968 } 9969 } 9970 9971 // C++2a [class.compare.default]p3: 9972 // If the member-specification does not explicitly declare any member or 9973 // friend named operator==, an == operator function is declared implicitly 9974 // for each defaulted three-way comparison operator function defined in 9975 // the member-specification 9976 // FIXME: Consider doing this lazily. 9977 // We do this during the initial parse for a class template, not during 9978 // instantiation, so that we can handle unqualified lookups for 'operator==' 9979 // when parsing the template. 9980 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) { 9981 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships; 9982 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 9983 DefaultedSpaceships); 9984 for (auto *FD : DefaultedSpaceships) 9985 DeclareImplicitEqualityComparison(ClassDecl, FD); 9986 } 9987 } 9988 9989 unsigned 9990 Sema::ActOnReenterTemplateScope(Decl *D, 9991 llvm::function_ref<Scope *()> EnterScope) { 9992 if (!D) 9993 return 0; 9994 AdjustDeclIfTemplate(D); 9995 9996 // In order to get name lookup right, reenter template scopes in order from 9997 // outermost to innermost. 9998 SmallVector<TemplateParameterList *, 4> ParameterLists; 9999 DeclContext *LookupDC = dyn_cast<DeclContext>(D); 10000 10001 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 10002 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 10003 ParameterLists.push_back(DD->getTemplateParameterList(i)); 10004 10005 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10006 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 10007 ParameterLists.push_back(FTD->getTemplateParameters()); 10008 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 10009 LookupDC = VD->getDeclContext(); 10010 10011 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate()) 10012 ParameterLists.push_back(VTD->getTemplateParameters()); 10013 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) 10014 ParameterLists.push_back(PSD->getTemplateParameters()); 10015 } 10016 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 10017 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 10018 ParameterLists.push_back(TD->getTemplateParameterList(i)); 10019 10020 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 10021 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 10022 ParameterLists.push_back(CTD->getTemplateParameters()); 10023 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 10024 ParameterLists.push_back(PSD->getTemplateParameters()); 10025 } 10026 } 10027 // FIXME: Alias declarations and concepts. 10028 10029 unsigned Count = 0; 10030 Scope *InnermostTemplateScope = nullptr; 10031 for (TemplateParameterList *Params : ParameterLists) { 10032 // Ignore explicit specializations; they don't contribute to the template 10033 // depth. 10034 if (Params->size() == 0) 10035 continue; 10036 10037 InnermostTemplateScope = EnterScope(); 10038 for (NamedDecl *Param : *Params) { 10039 if (Param->getDeclName()) { 10040 InnermostTemplateScope->AddDecl(Param); 10041 IdResolver.AddDecl(Param); 10042 } 10043 } 10044 ++Count; 10045 } 10046 10047 // Associate the new template scopes with the corresponding entities. 10048 if (InnermostTemplateScope) { 10049 assert(LookupDC && "no enclosing DeclContext for template lookup"); 10050 EnterTemplatedContext(InnermostTemplateScope, LookupDC); 10051 } 10052 10053 return Count; 10054 } 10055 10056 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10057 if (!RecordD) return; 10058 AdjustDeclIfTemplate(RecordD); 10059 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 10060 PushDeclContext(S, Record); 10061 } 10062 10063 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10064 if (!RecordD) return; 10065 PopDeclContext(); 10066 } 10067 10068 /// This is used to implement the constant expression evaluation part of the 10069 /// attribute enable_if extension. There is nothing in standard C++ which would 10070 /// require reentering parameters. 10071 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 10072 if (!Param) 10073 return; 10074 10075 S->AddDecl(Param); 10076 if (Param->getDeclName()) 10077 IdResolver.AddDecl(Param); 10078 } 10079 10080 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 10081 /// parsing a top-level (non-nested) C++ class, and we are now 10082 /// parsing those parts of the given Method declaration that could 10083 /// not be parsed earlier (C++ [class.mem]p2), such as default 10084 /// arguments. This action should enter the scope of the given 10085 /// Method declaration as if we had just parsed the qualified method 10086 /// name. However, it should not bring the parameters into scope; 10087 /// that will be performed by ActOnDelayedCXXMethodParameter. 10088 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10089 } 10090 10091 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 10092 /// C++ method declaration. We're (re-)introducing the given 10093 /// function parameter into scope for use in parsing later parts of 10094 /// the method declaration. For example, we could see an 10095 /// ActOnParamDefaultArgument event for this parameter. 10096 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 10097 if (!ParamD) 10098 return; 10099 10100 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 10101 10102 S->AddDecl(Param); 10103 if (Param->getDeclName()) 10104 IdResolver.AddDecl(Param); 10105 } 10106 10107 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 10108 /// processing the delayed method declaration for Method. The method 10109 /// declaration is now considered finished. There may be a separate 10110 /// ActOnStartOfFunctionDef action later (not necessarily 10111 /// immediately!) for this method, if it was also defined inside the 10112 /// class body. 10113 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10114 if (!MethodD) 10115 return; 10116 10117 AdjustDeclIfTemplate(MethodD); 10118 10119 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 10120 10121 // Now that we have our default arguments, check the constructor 10122 // again. It could produce additional diagnostics or affect whether 10123 // the class has implicitly-declared destructors, among other 10124 // things. 10125 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 10126 CheckConstructor(Constructor); 10127 10128 // Check the default arguments, which we may have added. 10129 if (!Method->isInvalidDecl()) 10130 CheckCXXDefaultArguments(Method); 10131 } 10132 10133 // Emit the given diagnostic for each non-address-space qualifier. 10134 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 10135 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 10136 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10137 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 10138 bool DiagOccured = false; 10139 FTI.MethodQualifiers->forEachQualifier( 10140 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 10141 SourceLocation SL) { 10142 // This diagnostic should be emitted on any qualifier except an addr 10143 // space qualifier. However, forEachQualifier currently doesn't visit 10144 // addr space qualifiers, so there's no way to write this condition 10145 // right now; we just diagnose on everything. 10146 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 10147 DiagOccured = true; 10148 }); 10149 if (DiagOccured) 10150 D.setInvalidType(); 10151 } 10152 } 10153 10154 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 10155 /// the well-formedness of the constructor declarator @p D with type @p 10156 /// R. If there are any errors in the declarator, this routine will 10157 /// emit diagnostics and set the invalid bit to true. In any case, the type 10158 /// will be updated to reflect a well-formed type for the constructor and 10159 /// returned. 10160 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 10161 StorageClass &SC) { 10162 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 10163 10164 // C++ [class.ctor]p3: 10165 // A constructor shall not be virtual (10.3) or static (9.4). A 10166 // constructor can be invoked for a const, volatile or const 10167 // volatile object. A constructor shall not be declared const, 10168 // volatile, or const volatile (9.3.2). 10169 if (isVirtual) { 10170 if (!D.isInvalidType()) 10171 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10172 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 10173 << SourceRange(D.getIdentifierLoc()); 10174 D.setInvalidType(); 10175 } 10176 if (SC == SC_Static) { 10177 if (!D.isInvalidType()) 10178 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10179 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10180 << SourceRange(D.getIdentifierLoc()); 10181 D.setInvalidType(); 10182 SC = SC_None; 10183 } 10184 10185 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10186 diagnoseIgnoredQualifiers( 10187 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 10188 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 10189 D.getDeclSpec().getRestrictSpecLoc(), 10190 D.getDeclSpec().getAtomicSpecLoc()); 10191 D.setInvalidType(); 10192 } 10193 10194 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 10195 10196 // C++0x [class.ctor]p4: 10197 // A constructor shall not be declared with a ref-qualifier. 10198 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10199 if (FTI.hasRefQualifier()) { 10200 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 10201 << FTI.RefQualifierIsLValueRef 10202 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10203 D.setInvalidType(); 10204 } 10205 10206 // Rebuild the function type "R" without any type qualifiers (in 10207 // case any of the errors above fired) and with "void" as the 10208 // return type, since constructors don't have return types. 10209 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10210 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 10211 return R; 10212 10213 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10214 EPI.TypeQuals = Qualifiers(); 10215 EPI.RefQualifier = RQ_None; 10216 10217 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 10218 } 10219 10220 /// CheckConstructor - Checks a fully-formed constructor for 10221 /// well-formedness, issuing any diagnostics required. Returns true if 10222 /// the constructor declarator is invalid. 10223 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 10224 CXXRecordDecl *ClassDecl 10225 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 10226 if (!ClassDecl) 10227 return Constructor->setInvalidDecl(); 10228 10229 // C++ [class.copy]p3: 10230 // A declaration of a constructor for a class X is ill-formed if 10231 // its first parameter is of type (optionally cv-qualified) X and 10232 // either there are no other parameters or else all other 10233 // parameters have default arguments. 10234 if (!Constructor->isInvalidDecl() && 10235 Constructor->hasOneParamOrDefaultArgs() && 10236 Constructor->getTemplateSpecializationKind() != 10237 TSK_ImplicitInstantiation) { 10238 QualType ParamType = Constructor->getParamDecl(0)->getType(); 10239 QualType ClassTy = Context.getTagDeclType(ClassDecl); 10240 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 10241 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 10242 const char *ConstRef 10243 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 10244 : " const &"; 10245 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 10246 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 10247 10248 // FIXME: Rather that making the constructor invalid, we should endeavor 10249 // to fix the type. 10250 Constructor->setInvalidDecl(); 10251 } 10252 } 10253 } 10254 10255 /// CheckDestructor - Checks a fully-formed destructor definition for 10256 /// well-formedness, issuing any diagnostics required. Returns true 10257 /// on error. 10258 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 10259 CXXRecordDecl *RD = Destructor->getParent(); 10260 10261 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 10262 SourceLocation Loc; 10263 10264 if (!Destructor->isImplicit()) 10265 Loc = Destructor->getLocation(); 10266 else 10267 Loc = RD->getLocation(); 10268 10269 // If we have a virtual destructor, look up the deallocation function 10270 if (FunctionDecl *OperatorDelete = 10271 FindDeallocationFunctionForDestructor(Loc, RD)) { 10272 Expr *ThisArg = nullptr; 10273 10274 // If the notional 'delete this' expression requires a non-trivial 10275 // conversion from 'this' to the type of a destroying operator delete's 10276 // first parameter, perform that conversion now. 10277 if (OperatorDelete->isDestroyingOperatorDelete()) { 10278 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 10279 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 10280 // C++ [class.dtor]p13: 10281 // ... as if for the expression 'delete this' appearing in a 10282 // non-virtual destructor of the destructor's class. 10283 ContextRAII SwitchContext(*this, Destructor); 10284 ExprResult This = 10285 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 10286 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 10287 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 10288 if (This.isInvalid()) { 10289 // FIXME: Register this as a context note so that it comes out 10290 // in the right order. 10291 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 10292 return true; 10293 } 10294 ThisArg = This.get(); 10295 } 10296 } 10297 10298 DiagnoseUseOfDecl(OperatorDelete, Loc); 10299 MarkFunctionReferenced(Loc, OperatorDelete); 10300 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 10301 } 10302 } 10303 10304 return false; 10305 } 10306 10307 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 10308 /// the well-formednes of the destructor declarator @p D with type @p 10309 /// R. If there are any errors in the declarator, this routine will 10310 /// emit diagnostics and set the declarator to invalid. Even if this happens, 10311 /// will be updated to reflect a well-formed type for the destructor and 10312 /// returned. 10313 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 10314 StorageClass& SC) { 10315 // C++ [class.dtor]p1: 10316 // [...] A typedef-name that names a class is a class-name 10317 // (7.1.3); however, a typedef-name that names a class shall not 10318 // be used as the identifier in the declarator for a destructor 10319 // declaration. 10320 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 10321 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 10322 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10323 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 10324 else if (const TemplateSpecializationType *TST = 10325 DeclaratorType->getAs<TemplateSpecializationType>()) 10326 if (TST->isTypeAlias()) 10327 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10328 << DeclaratorType << 1; 10329 10330 // C++ [class.dtor]p2: 10331 // A destructor is used to destroy objects of its class type. A 10332 // destructor takes no parameters, and no return type can be 10333 // specified for it (not even void). The address of a destructor 10334 // shall not be taken. A destructor shall not be static. A 10335 // destructor can be invoked for a const, volatile or const 10336 // volatile object. A destructor shall not be declared const, 10337 // volatile or const volatile (9.3.2). 10338 if (SC == SC_Static) { 10339 if (!D.isInvalidType()) 10340 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 10341 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10342 << SourceRange(D.getIdentifierLoc()) 10343 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10344 10345 SC = SC_None; 10346 } 10347 if (!D.isInvalidType()) { 10348 // Destructors don't have return types, but the parser will 10349 // happily parse something like: 10350 // 10351 // class X { 10352 // float ~X(); 10353 // }; 10354 // 10355 // The return type will be eliminated later. 10356 if (D.getDeclSpec().hasTypeSpecifier()) 10357 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 10358 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 10359 << SourceRange(D.getIdentifierLoc()); 10360 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10361 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 10362 SourceLocation(), 10363 D.getDeclSpec().getConstSpecLoc(), 10364 D.getDeclSpec().getVolatileSpecLoc(), 10365 D.getDeclSpec().getRestrictSpecLoc(), 10366 D.getDeclSpec().getAtomicSpecLoc()); 10367 D.setInvalidType(); 10368 } 10369 } 10370 10371 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 10372 10373 // C++0x [class.dtor]p2: 10374 // A destructor shall not be declared with a ref-qualifier. 10375 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10376 if (FTI.hasRefQualifier()) { 10377 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 10378 << FTI.RefQualifierIsLValueRef 10379 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10380 D.setInvalidType(); 10381 } 10382 10383 // Make sure we don't have any parameters. 10384 if (FTIHasNonVoidParameters(FTI)) { 10385 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 10386 10387 // Delete the parameters. 10388 FTI.freeParams(); 10389 D.setInvalidType(); 10390 } 10391 10392 // Make sure the destructor isn't variadic. 10393 if (FTI.isVariadic) { 10394 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10395 D.setInvalidType(); 10396 } 10397 10398 // Rebuild the function type "R" without any type qualifiers or 10399 // parameters (in case any of the errors above fired) and with 10400 // "void" as the return type, since destructors don't have return 10401 // types. 10402 if (!D.isInvalidType()) 10403 return R; 10404 10405 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10406 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10407 EPI.Variadic = false; 10408 EPI.TypeQuals = Qualifiers(); 10409 EPI.RefQualifier = RQ_None; 10410 return Context.getFunctionType(Context.VoidTy, None, EPI); 10411 } 10412 10413 static void extendLeft(SourceRange &R, SourceRange Before) { 10414 if (Before.isInvalid()) 10415 return; 10416 R.setBegin(Before.getBegin()); 10417 if (R.getEnd().isInvalid()) 10418 R.setEnd(Before.getEnd()); 10419 } 10420 10421 static void extendRight(SourceRange &R, SourceRange After) { 10422 if (After.isInvalid()) 10423 return; 10424 if (R.getBegin().isInvalid()) 10425 R.setBegin(After.getBegin()); 10426 R.setEnd(After.getEnd()); 10427 } 10428 10429 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10430 /// well-formednes of the conversion function declarator @p D with 10431 /// type @p R. If there are any errors in the declarator, this routine 10432 /// will emit diagnostics and return true. Otherwise, it will return 10433 /// false. Either way, the type @p R will be updated to reflect a 10434 /// well-formed type for the conversion operator. 10435 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10436 StorageClass& SC) { 10437 // C++ [class.conv.fct]p1: 10438 // Neither parameter types nor return type can be specified. The 10439 // type of a conversion function (8.3.5) is "function taking no 10440 // parameter returning conversion-type-id." 10441 if (SC == SC_Static) { 10442 if (!D.isInvalidType()) 10443 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10444 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10445 << D.getName().getSourceRange(); 10446 D.setInvalidType(); 10447 SC = SC_None; 10448 } 10449 10450 TypeSourceInfo *ConvTSI = nullptr; 10451 QualType ConvType = 10452 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10453 10454 const DeclSpec &DS = D.getDeclSpec(); 10455 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10456 // Conversion functions don't have return types, but the parser will 10457 // happily parse something like: 10458 // 10459 // class X { 10460 // float operator bool(); 10461 // }; 10462 // 10463 // The return type will be changed later anyway. 10464 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10465 << SourceRange(DS.getTypeSpecTypeLoc()) 10466 << SourceRange(D.getIdentifierLoc()); 10467 D.setInvalidType(); 10468 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10469 // It's also plausible that the user writes type qualifiers in the wrong 10470 // place, such as: 10471 // struct S { const operator int(); }; 10472 // FIXME: we could provide a fixit to move the qualifiers onto the 10473 // conversion type. 10474 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10475 << SourceRange(D.getIdentifierLoc()) << 0; 10476 D.setInvalidType(); 10477 } 10478 10479 const auto *Proto = R->castAs<FunctionProtoType>(); 10480 10481 // Make sure we don't have any parameters. 10482 if (Proto->getNumParams() > 0) { 10483 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10484 10485 // Delete the parameters. 10486 D.getFunctionTypeInfo().freeParams(); 10487 D.setInvalidType(); 10488 } else if (Proto->isVariadic()) { 10489 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10490 D.setInvalidType(); 10491 } 10492 10493 // Diagnose "&operator bool()" and other such nonsense. This 10494 // is actually a gcc extension which we don't support. 10495 if (Proto->getReturnType() != ConvType) { 10496 bool NeedsTypedef = false; 10497 SourceRange Before, After; 10498 10499 // Walk the chunks and extract information on them for our diagnostic. 10500 bool PastFunctionChunk = false; 10501 for (auto &Chunk : D.type_objects()) { 10502 switch (Chunk.Kind) { 10503 case DeclaratorChunk::Function: 10504 if (!PastFunctionChunk) { 10505 if (Chunk.Fun.HasTrailingReturnType) { 10506 TypeSourceInfo *TRT = nullptr; 10507 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10508 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10509 } 10510 PastFunctionChunk = true; 10511 break; 10512 } 10513 LLVM_FALLTHROUGH; 10514 case DeclaratorChunk::Array: 10515 NeedsTypedef = true; 10516 extendRight(After, Chunk.getSourceRange()); 10517 break; 10518 10519 case DeclaratorChunk::Pointer: 10520 case DeclaratorChunk::BlockPointer: 10521 case DeclaratorChunk::Reference: 10522 case DeclaratorChunk::MemberPointer: 10523 case DeclaratorChunk::Pipe: 10524 extendLeft(Before, Chunk.getSourceRange()); 10525 break; 10526 10527 case DeclaratorChunk::Paren: 10528 extendLeft(Before, Chunk.Loc); 10529 extendRight(After, Chunk.EndLoc); 10530 break; 10531 } 10532 } 10533 10534 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10535 After.isValid() ? After.getBegin() : 10536 D.getIdentifierLoc(); 10537 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10538 DB << Before << After; 10539 10540 if (!NeedsTypedef) { 10541 DB << /*don't need a typedef*/0; 10542 10543 // If we can provide a correct fix-it hint, do so. 10544 if (After.isInvalid() && ConvTSI) { 10545 SourceLocation InsertLoc = 10546 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10547 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10548 << FixItHint::CreateInsertionFromRange( 10549 InsertLoc, CharSourceRange::getTokenRange(Before)) 10550 << FixItHint::CreateRemoval(Before); 10551 } 10552 } else if (!Proto->getReturnType()->isDependentType()) { 10553 DB << /*typedef*/1 << Proto->getReturnType(); 10554 } else if (getLangOpts().CPlusPlus11) { 10555 DB << /*alias template*/2 << Proto->getReturnType(); 10556 } else { 10557 DB << /*might not be fixable*/3; 10558 } 10559 10560 // Recover by incorporating the other type chunks into the result type. 10561 // Note, this does *not* change the name of the function. This is compatible 10562 // with the GCC extension: 10563 // struct S { &operator int(); } s; 10564 // int &r = s.operator int(); // ok in GCC 10565 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10566 ConvType = Proto->getReturnType(); 10567 } 10568 10569 // C++ [class.conv.fct]p4: 10570 // The conversion-type-id shall not represent a function type nor 10571 // an array type. 10572 if (ConvType->isArrayType()) { 10573 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10574 ConvType = Context.getPointerType(ConvType); 10575 D.setInvalidType(); 10576 } else if (ConvType->isFunctionType()) { 10577 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10578 ConvType = Context.getPointerType(ConvType); 10579 D.setInvalidType(); 10580 } 10581 10582 // Rebuild the function type "R" without any parameters (in case any 10583 // of the errors above fired) and with the conversion type as the 10584 // return type. 10585 if (D.isInvalidType()) 10586 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 10587 10588 // C++0x explicit conversion operators. 10589 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20) 10590 Diag(DS.getExplicitSpecLoc(), 10591 getLangOpts().CPlusPlus11 10592 ? diag::warn_cxx98_compat_explicit_conversion_functions 10593 : diag::ext_explicit_conversion_functions) 10594 << SourceRange(DS.getExplicitSpecRange()); 10595 } 10596 10597 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 10598 /// the declaration of the given C++ conversion function. This routine 10599 /// is responsible for recording the conversion function in the C++ 10600 /// class, if possible. 10601 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 10602 assert(Conversion && "Expected to receive a conversion function declaration"); 10603 10604 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 10605 10606 // Make sure we aren't redeclaring the conversion function. 10607 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 10608 // C++ [class.conv.fct]p1: 10609 // [...] A conversion function is never used to convert a 10610 // (possibly cv-qualified) object to the (possibly cv-qualified) 10611 // same object type (or a reference to it), to a (possibly 10612 // cv-qualified) base class of that type (or a reference to it), 10613 // or to (possibly cv-qualified) void. 10614 QualType ClassType 10615 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10616 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 10617 ConvType = ConvTypeRef->getPointeeType(); 10618 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 10619 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 10620 /* Suppress diagnostics for instantiations. */; 10621 else if (Conversion->size_overridden_methods() != 0) 10622 /* Suppress diagnostics for overriding virtual function in a base class. */; 10623 else if (ConvType->isRecordType()) { 10624 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 10625 if (ConvType == ClassType) 10626 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 10627 << ClassType; 10628 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 10629 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 10630 << ClassType << ConvType; 10631 } else if (ConvType->isVoidType()) { 10632 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 10633 << ClassType << ConvType; 10634 } 10635 10636 if (FunctionTemplateDecl *ConversionTemplate 10637 = Conversion->getDescribedFunctionTemplate()) 10638 return ConversionTemplate; 10639 10640 return Conversion; 10641 } 10642 10643 namespace { 10644 /// Utility class to accumulate and print a diagnostic listing the invalid 10645 /// specifier(s) on a declaration. 10646 struct BadSpecifierDiagnoser { 10647 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10648 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10649 ~BadSpecifierDiagnoser() { 10650 Diagnostic << Specifiers; 10651 } 10652 10653 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10654 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10655 } 10656 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10657 return check(SpecLoc, 10658 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10659 } 10660 void check(SourceLocation SpecLoc, const char *Spec) { 10661 if (SpecLoc.isInvalid()) return; 10662 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10663 if (!Specifiers.empty()) Specifiers += " "; 10664 Specifiers += Spec; 10665 } 10666 10667 Sema &S; 10668 Sema::SemaDiagnosticBuilder Diagnostic; 10669 std::string Specifiers; 10670 }; 10671 } 10672 10673 /// Check the validity of a declarator that we parsed for a deduction-guide. 10674 /// These aren't actually declarators in the grammar, so we need to check that 10675 /// the user didn't specify any pieces that are not part of the deduction-guide 10676 /// grammar. 10677 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10678 StorageClass &SC) { 10679 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10680 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10681 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 10682 10683 // C++ [temp.deduct.guide]p3: 10684 // A deduction-gide shall be declared in the same scope as the 10685 // corresponding class template. 10686 if (!CurContext->getRedeclContext()->Equals( 10687 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10688 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10689 << GuidedTemplateDecl; 10690 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10691 } 10692 10693 auto &DS = D.getMutableDeclSpec(); 10694 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10695 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10696 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10697 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10698 BadSpecifierDiagnoser Diagnoser( 10699 *this, D.getIdentifierLoc(), 10700 diag::err_deduction_guide_invalid_specifier); 10701 10702 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10703 DS.ClearStorageClassSpecs(); 10704 SC = SC_None; 10705 10706 // 'explicit' is permitted. 10707 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10708 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10709 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10710 DS.ClearConstexprSpec(); 10711 10712 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10713 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10714 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10715 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10716 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10717 DS.ClearTypeQualifiers(); 10718 10719 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 10720 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 10721 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 10722 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 10723 DS.ClearTypeSpecType(); 10724 } 10725 10726 if (D.isInvalidType()) 10727 return; 10728 10729 // Check the declarator is simple enough. 10730 bool FoundFunction = false; 10731 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 10732 if (Chunk.Kind == DeclaratorChunk::Paren) 10733 continue; 10734 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 10735 Diag(D.getDeclSpec().getBeginLoc(), 10736 diag::err_deduction_guide_with_complex_decl) 10737 << D.getSourceRange(); 10738 break; 10739 } 10740 if (!Chunk.Fun.hasTrailingReturnType()) { 10741 Diag(D.getName().getBeginLoc(), 10742 diag::err_deduction_guide_no_trailing_return_type); 10743 break; 10744 } 10745 10746 // Check that the return type is written as a specialization of 10747 // the template specified as the deduction-guide's name. 10748 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 10749 TypeSourceInfo *TSI = nullptr; 10750 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 10751 assert(TSI && "deduction guide has valid type but invalid return type?"); 10752 bool AcceptableReturnType = false; 10753 bool MightInstantiateToSpecialization = false; 10754 if (auto RetTST = 10755 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 10756 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 10757 bool TemplateMatches = 10758 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 10759 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 10760 AcceptableReturnType = true; 10761 else { 10762 // This could still instantiate to the right type, unless we know it 10763 // names the wrong class template. 10764 auto *TD = SpecifiedName.getAsTemplateDecl(); 10765 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 10766 !TemplateMatches); 10767 } 10768 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 10769 MightInstantiateToSpecialization = true; 10770 } 10771 10772 if (!AcceptableReturnType) { 10773 Diag(TSI->getTypeLoc().getBeginLoc(), 10774 diag::err_deduction_guide_bad_trailing_return_type) 10775 << GuidedTemplate << TSI->getType() 10776 << MightInstantiateToSpecialization 10777 << TSI->getTypeLoc().getSourceRange(); 10778 } 10779 10780 // Keep going to check that we don't have any inner declarator pieces (we 10781 // could still have a function returning a pointer to a function). 10782 FoundFunction = true; 10783 } 10784 10785 if (D.isFunctionDefinition()) 10786 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 10787 } 10788 10789 //===----------------------------------------------------------------------===// 10790 // Namespace Handling 10791 //===----------------------------------------------------------------------===// 10792 10793 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 10794 /// reopened. 10795 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 10796 SourceLocation Loc, 10797 IdentifierInfo *II, bool *IsInline, 10798 NamespaceDecl *PrevNS) { 10799 assert(*IsInline != PrevNS->isInline()); 10800 10801 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 10802 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 10803 // inline namespaces, with the intention of bringing names into namespace std. 10804 // 10805 // We support this just well enough to get that case working; this is not 10806 // sufficient to support reopening namespaces as inline in general. 10807 if (*IsInline && II && II->getName().startswith("__atomic") && 10808 S.getSourceManager().isInSystemHeader(Loc)) { 10809 // Mark all prior declarations of the namespace as inline. 10810 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 10811 NS = NS->getPreviousDecl()) 10812 NS->setInline(*IsInline); 10813 // Patch up the lookup table for the containing namespace. This isn't really 10814 // correct, but it's good enough for this particular case. 10815 for (auto *I : PrevNS->decls()) 10816 if (auto *ND = dyn_cast<NamedDecl>(I)) 10817 PrevNS->getParent()->makeDeclVisibleInContext(ND); 10818 return; 10819 } 10820 10821 if (PrevNS->isInline()) 10822 // The user probably just forgot the 'inline', so suggest that it 10823 // be added back. 10824 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 10825 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 10826 else 10827 S.Diag(Loc, diag::err_inline_namespace_mismatch); 10828 10829 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 10830 *IsInline = PrevNS->isInline(); 10831 } 10832 10833 /// ActOnStartNamespaceDef - This is called at the start of a namespace 10834 /// definition. 10835 Decl *Sema::ActOnStartNamespaceDef( 10836 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 10837 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 10838 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 10839 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 10840 // For anonymous namespace, take the location of the left brace. 10841 SourceLocation Loc = II ? IdentLoc : LBrace; 10842 bool IsInline = InlineLoc.isValid(); 10843 bool IsInvalid = false; 10844 bool IsStd = false; 10845 bool AddToKnown = false; 10846 Scope *DeclRegionScope = NamespcScope->getParent(); 10847 10848 NamespaceDecl *PrevNS = nullptr; 10849 if (II) { 10850 // C++ [namespace.def]p2: 10851 // The identifier in an original-namespace-definition shall not 10852 // have been previously defined in the declarative region in 10853 // which the original-namespace-definition appears. The 10854 // identifier in an original-namespace-definition is the name of 10855 // the namespace. Subsequently in that declarative region, it is 10856 // treated as an original-namespace-name. 10857 // 10858 // Since namespace names are unique in their scope, and we don't 10859 // look through using directives, just look for any ordinary names 10860 // as if by qualified name lookup. 10861 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 10862 ForExternalRedeclaration); 10863 LookupQualifiedName(R, CurContext->getRedeclContext()); 10864 NamedDecl *PrevDecl = 10865 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 10866 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 10867 10868 if (PrevNS) { 10869 // This is an extended namespace definition. 10870 if (IsInline != PrevNS->isInline()) 10871 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 10872 &IsInline, PrevNS); 10873 } else if (PrevDecl) { 10874 // This is an invalid name redefinition. 10875 Diag(Loc, diag::err_redefinition_different_kind) 10876 << II; 10877 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10878 IsInvalid = true; 10879 // Continue on to push Namespc as current DeclContext and return it. 10880 } else if (II->isStr("std") && 10881 CurContext->getRedeclContext()->isTranslationUnit()) { 10882 // This is the first "real" definition of the namespace "std", so update 10883 // our cache of the "std" namespace to point at this definition. 10884 PrevNS = getStdNamespace(); 10885 IsStd = true; 10886 AddToKnown = !IsInline; 10887 } else { 10888 // We've seen this namespace for the first time. 10889 AddToKnown = !IsInline; 10890 } 10891 } else { 10892 // Anonymous namespaces. 10893 10894 // Determine whether the parent already has an anonymous namespace. 10895 DeclContext *Parent = CurContext->getRedeclContext(); 10896 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10897 PrevNS = TU->getAnonymousNamespace(); 10898 } else { 10899 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 10900 PrevNS = ND->getAnonymousNamespace(); 10901 } 10902 10903 if (PrevNS && IsInline != PrevNS->isInline()) 10904 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 10905 &IsInline, PrevNS); 10906 } 10907 10908 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 10909 StartLoc, Loc, II, PrevNS); 10910 if (IsInvalid) 10911 Namespc->setInvalidDecl(); 10912 10913 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 10914 AddPragmaAttributes(DeclRegionScope, Namespc); 10915 10916 // FIXME: Should we be merging attributes? 10917 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 10918 PushNamespaceVisibilityAttr(Attr, Loc); 10919 10920 if (IsStd) 10921 StdNamespace = Namespc; 10922 if (AddToKnown) 10923 KnownNamespaces[Namespc] = false; 10924 10925 if (II) { 10926 PushOnScopeChains(Namespc, DeclRegionScope); 10927 } else { 10928 // Link the anonymous namespace into its parent. 10929 DeclContext *Parent = CurContext->getRedeclContext(); 10930 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10931 TU->setAnonymousNamespace(Namespc); 10932 } else { 10933 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 10934 } 10935 10936 CurContext->addDecl(Namespc); 10937 10938 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 10939 // behaves as if it were replaced by 10940 // namespace unique { /* empty body */ } 10941 // using namespace unique; 10942 // namespace unique { namespace-body } 10943 // where all occurrences of 'unique' in a translation unit are 10944 // replaced by the same identifier and this identifier differs 10945 // from all other identifiers in the entire program. 10946 10947 // We just create the namespace with an empty name and then add an 10948 // implicit using declaration, just like the standard suggests. 10949 // 10950 // CodeGen enforces the "universally unique" aspect by giving all 10951 // declarations semantically contained within an anonymous 10952 // namespace internal linkage. 10953 10954 if (!PrevNS) { 10955 UD = UsingDirectiveDecl::Create(Context, Parent, 10956 /* 'using' */ LBrace, 10957 /* 'namespace' */ SourceLocation(), 10958 /* qualifier */ NestedNameSpecifierLoc(), 10959 /* identifier */ SourceLocation(), 10960 Namespc, 10961 /* Ancestor */ Parent); 10962 UD->setImplicit(); 10963 Parent->addDecl(UD); 10964 } 10965 } 10966 10967 ActOnDocumentableDecl(Namespc); 10968 10969 // Although we could have an invalid decl (i.e. the namespace name is a 10970 // redefinition), push it as current DeclContext and try to continue parsing. 10971 // FIXME: We should be able to push Namespc here, so that the each DeclContext 10972 // for the namespace has the declarations that showed up in that particular 10973 // namespace definition. 10974 PushDeclContext(NamespcScope, Namespc); 10975 return Namespc; 10976 } 10977 10978 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 10979 /// is a namespace alias, returns the namespace it points to. 10980 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 10981 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 10982 return AD->getNamespace(); 10983 return dyn_cast_or_null<NamespaceDecl>(D); 10984 } 10985 10986 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 10987 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 10988 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 10989 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 10990 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 10991 Namespc->setRBraceLoc(RBrace); 10992 PopDeclContext(); 10993 if (Namespc->hasAttr<VisibilityAttr>()) 10994 PopPragmaVisibility(true, RBrace); 10995 // If this namespace contains an export-declaration, export it now. 10996 if (DeferredExportedNamespaces.erase(Namespc)) 10997 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 10998 } 10999 11000 CXXRecordDecl *Sema::getStdBadAlloc() const { 11001 return cast_or_null<CXXRecordDecl>( 11002 StdBadAlloc.get(Context.getExternalSource())); 11003 } 11004 11005 EnumDecl *Sema::getStdAlignValT() const { 11006 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 11007 } 11008 11009 NamespaceDecl *Sema::getStdNamespace() const { 11010 return cast_or_null<NamespaceDecl>( 11011 StdNamespace.get(Context.getExternalSource())); 11012 } 11013 11014 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 11015 if (!StdExperimentalNamespaceCache) { 11016 if (auto Std = getStdNamespace()) { 11017 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 11018 SourceLocation(), LookupNamespaceName); 11019 if (!LookupQualifiedName(Result, Std) || 11020 !(StdExperimentalNamespaceCache = 11021 Result.getAsSingle<NamespaceDecl>())) 11022 Result.suppressDiagnostics(); 11023 } 11024 } 11025 return StdExperimentalNamespaceCache; 11026 } 11027 11028 namespace { 11029 11030 enum UnsupportedSTLSelect { 11031 USS_InvalidMember, 11032 USS_MissingMember, 11033 USS_NonTrivial, 11034 USS_Other 11035 }; 11036 11037 struct InvalidSTLDiagnoser { 11038 Sema &S; 11039 SourceLocation Loc; 11040 QualType TyForDiags; 11041 11042 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 11043 const VarDecl *VD = nullptr) { 11044 { 11045 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 11046 << TyForDiags << ((int)Sel); 11047 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 11048 assert(!Name.empty()); 11049 D << Name; 11050 } 11051 } 11052 if (Sel == USS_InvalidMember) { 11053 S.Diag(VD->getLocation(), diag::note_var_declared_here) 11054 << VD << VD->getSourceRange(); 11055 } 11056 return QualType(); 11057 } 11058 }; 11059 } // namespace 11060 11061 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 11062 SourceLocation Loc, 11063 ComparisonCategoryUsage Usage) { 11064 assert(getLangOpts().CPlusPlus && 11065 "Looking for comparison category type outside of C++."); 11066 11067 // Use an elaborated type for diagnostics which has a name containing the 11068 // prepended 'std' namespace but not any inline namespace names. 11069 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 11070 auto *NNS = 11071 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 11072 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 11073 }; 11074 11075 // Check if we've already successfully checked the comparison category type 11076 // before. If so, skip checking it again. 11077 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 11078 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 11079 // The only thing we need to check is that the type has a reachable 11080 // definition in the current context. 11081 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11082 return QualType(); 11083 11084 return Info->getType(); 11085 } 11086 11087 // If lookup failed 11088 if (!Info) { 11089 std::string NameForDiags = "std::"; 11090 NameForDiags += ComparisonCategories::getCategoryString(Kind); 11091 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 11092 << NameForDiags << (int)Usage; 11093 return QualType(); 11094 } 11095 11096 assert(Info->Kind == Kind); 11097 assert(Info->Record); 11098 11099 // Update the Record decl in case we encountered a forward declaration on our 11100 // first pass. FIXME: This is a bit of a hack. 11101 if (Info->Record->hasDefinition()) 11102 Info->Record = Info->Record->getDefinition(); 11103 11104 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11105 return QualType(); 11106 11107 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 11108 11109 if (!Info->Record->isTriviallyCopyable()) 11110 return UnsupportedSTLError(USS_NonTrivial); 11111 11112 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 11113 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 11114 // Tolerate empty base classes. 11115 if (Base->isEmpty()) 11116 continue; 11117 // Reject STL implementations which have at least one non-empty base. 11118 return UnsupportedSTLError(); 11119 } 11120 11121 // Check that the STL has implemented the types using a single integer field. 11122 // This expectation allows better codegen for builtin operators. We require: 11123 // (1) The class has exactly one field. 11124 // (2) The field is an integral or enumeration type. 11125 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 11126 if (std::distance(FIt, FEnd) != 1 || 11127 !FIt->getType()->isIntegralOrEnumerationType()) { 11128 return UnsupportedSTLError(); 11129 } 11130 11131 // Build each of the require values and store them in Info. 11132 for (ComparisonCategoryResult CCR : 11133 ComparisonCategories::getPossibleResultsForType(Kind)) { 11134 StringRef MemName = ComparisonCategories::getResultString(CCR); 11135 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 11136 11137 if (!ValInfo) 11138 return UnsupportedSTLError(USS_MissingMember, MemName); 11139 11140 VarDecl *VD = ValInfo->VD; 11141 assert(VD && "should not be null!"); 11142 11143 // Attempt to diagnose reasons why the STL definition of this type 11144 // might be foobar, including it failing to be a constant expression. 11145 // TODO Handle more ways the lookup or result can be invalid. 11146 if (!VD->isStaticDataMember() || 11147 !VD->isUsableInConstantExpressions(Context)) 11148 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 11149 11150 // Attempt to evaluate the var decl as a constant expression and extract 11151 // the value of its first field as a ICE. If this fails, the STL 11152 // implementation is not supported. 11153 if (!ValInfo->hasValidIntValue()) 11154 return UnsupportedSTLError(); 11155 11156 MarkVariableReferenced(Loc, VD); 11157 } 11158 11159 // We've successfully built the required types and expressions. Update 11160 // the cache and return the newly cached value. 11161 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 11162 return Info->getType(); 11163 } 11164 11165 /// Retrieve the special "std" namespace, which may require us to 11166 /// implicitly define the namespace. 11167 NamespaceDecl *Sema::getOrCreateStdNamespace() { 11168 if (!StdNamespace) { 11169 // The "std" namespace has not yet been defined, so build one implicitly. 11170 StdNamespace = NamespaceDecl::Create(Context, 11171 Context.getTranslationUnitDecl(), 11172 /*Inline=*/false, 11173 SourceLocation(), SourceLocation(), 11174 &PP.getIdentifierTable().get("std"), 11175 /*PrevDecl=*/nullptr); 11176 getStdNamespace()->setImplicit(true); 11177 } 11178 11179 return getStdNamespace(); 11180 } 11181 11182 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 11183 assert(getLangOpts().CPlusPlus && 11184 "Looking for std::initializer_list outside of C++."); 11185 11186 // We're looking for implicit instantiations of 11187 // template <typename E> class std::initializer_list. 11188 11189 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 11190 return false; 11191 11192 ClassTemplateDecl *Template = nullptr; 11193 const TemplateArgument *Arguments = nullptr; 11194 11195 if (const RecordType *RT = Ty->getAs<RecordType>()) { 11196 11197 ClassTemplateSpecializationDecl *Specialization = 11198 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 11199 if (!Specialization) 11200 return false; 11201 11202 Template = Specialization->getSpecializedTemplate(); 11203 Arguments = Specialization->getTemplateArgs().data(); 11204 } else if (const TemplateSpecializationType *TST = 11205 Ty->getAs<TemplateSpecializationType>()) { 11206 Template = dyn_cast_or_null<ClassTemplateDecl>( 11207 TST->getTemplateName().getAsTemplateDecl()); 11208 Arguments = TST->getArgs(); 11209 } 11210 if (!Template) 11211 return false; 11212 11213 if (!StdInitializerList) { 11214 // Haven't recognized std::initializer_list yet, maybe this is it. 11215 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 11216 if (TemplateClass->getIdentifier() != 11217 &PP.getIdentifierTable().get("initializer_list") || 11218 !getStdNamespace()->InEnclosingNamespaceSetOf( 11219 TemplateClass->getDeclContext())) 11220 return false; 11221 // This is a template called std::initializer_list, but is it the right 11222 // template? 11223 TemplateParameterList *Params = Template->getTemplateParameters(); 11224 if (Params->getMinRequiredArguments() != 1) 11225 return false; 11226 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 11227 return false; 11228 11229 // It's the right template. 11230 StdInitializerList = Template; 11231 } 11232 11233 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 11234 return false; 11235 11236 // This is an instance of std::initializer_list. Find the argument type. 11237 if (Element) 11238 *Element = Arguments[0].getAsType(); 11239 return true; 11240 } 11241 11242 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 11243 NamespaceDecl *Std = S.getStdNamespace(); 11244 if (!Std) { 11245 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11246 return nullptr; 11247 } 11248 11249 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 11250 Loc, Sema::LookupOrdinaryName); 11251 if (!S.LookupQualifiedName(Result, Std)) { 11252 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11253 return nullptr; 11254 } 11255 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 11256 if (!Template) { 11257 Result.suppressDiagnostics(); 11258 // We found something weird. Complain about the first thing we found. 11259 NamedDecl *Found = *Result.begin(); 11260 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 11261 return nullptr; 11262 } 11263 11264 // We found some template called std::initializer_list. Now verify that it's 11265 // correct. 11266 TemplateParameterList *Params = Template->getTemplateParameters(); 11267 if (Params->getMinRequiredArguments() != 1 || 11268 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 11269 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 11270 return nullptr; 11271 } 11272 11273 return Template; 11274 } 11275 11276 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 11277 if (!StdInitializerList) { 11278 StdInitializerList = LookupStdInitializerList(*this, Loc); 11279 if (!StdInitializerList) 11280 return QualType(); 11281 } 11282 11283 TemplateArgumentListInfo Args(Loc, Loc); 11284 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 11285 Context.getTrivialTypeSourceInfo(Element, 11286 Loc))); 11287 return Context.getCanonicalType( 11288 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 11289 } 11290 11291 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 11292 // C++ [dcl.init.list]p2: 11293 // A constructor is an initializer-list constructor if its first parameter 11294 // is of type std::initializer_list<E> or reference to possibly cv-qualified 11295 // std::initializer_list<E> for some type E, and either there are no other 11296 // parameters or else all other parameters have default arguments. 11297 if (!Ctor->hasOneParamOrDefaultArgs()) 11298 return false; 11299 11300 QualType ArgType = Ctor->getParamDecl(0)->getType(); 11301 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 11302 ArgType = RT->getPointeeType().getUnqualifiedType(); 11303 11304 return isStdInitializerList(ArgType, nullptr); 11305 } 11306 11307 /// Determine whether a using statement is in a context where it will be 11308 /// apply in all contexts. 11309 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 11310 switch (CurContext->getDeclKind()) { 11311 case Decl::TranslationUnit: 11312 return true; 11313 case Decl::LinkageSpec: 11314 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 11315 default: 11316 return false; 11317 } 11318 } 11319 11320 namespace { 11321 11322 // Callback to only accept typo corrections that are namespaces. 11323 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 11324 public: 11325 bool ValidateCandidate(const TypoCorrection &candidate) override { 11326 if (NamedDecl *ND = candidate.getCorrectionDecl()) 11327 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 11328 return false; 11329 } 11330 11331 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11332 return std::make_unique<NamespaceValidatorCCC>(*this); 11333 } 11334 }; 11335 11336 } 11337 11338 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 11339 CXXScopeSpec &SS, 11340 SourceLocation IdentLoc, 11341 IdentifierInfo *Ident) { 11342 R.clear(); 11343 NamespaceValidatorCCC CCC{}; 11344 if (TypoCorrection Corrected = 11345 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 11346 Sema::CTK_ErrorRecovery)) { 11347 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 11348 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 11349 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 11350 Ident->getName().equals(CorrectedStr); 11351 S.diagnoseTypo(Corrected, 11352 S.PDiag(diag::err_using_directive_member_suggest) 11353 << Ident << DC << DroppedSpecifier << SS.getRange(), 11354 S.PDiag(diag::note_namespace_defined_here)); 11355 } else { 11356 S.diagnoseTypo(Corrected, 11357 S.PDiag(diag::err_using_directive_suggest) << Ident, 11358 S.PDiag(diag::note_namespace_defined_here)); 11359 } 11360 R.addDecl(Corrected.getFoundDecl()); 11361 return true; 11362 } 11363 return false; 11364 } 11365 11366 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 11367 SourceLocation NamespcLoc, CXXScopeSpec &SS, 11368 SourceLocation IdentLoc, 11369 IdentifierInfo *NamespcName, 11370 const ParsedAttributesView &AttrList) { 11371 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11372 assert(NamespcName && "Invalid NamespcName."); 11373 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 11374 11375 // This can only happen along a recovery path. 11376 while (S->isTemplateParamScope()) 11377 S = S->getParent(); 11378 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11379 11380 UsingDirectiveDecl *UDir = nullptr; 11381 NestedNameSpecifier *Qualifier = nullptr; 11382 if (SS.isSet()) 11383 Qualifier = SS.getScopeRep(); 11384 11385 // Lookup namespace name. 11386 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 11387 LookupParsedName(R, S, &SS); 11388 if (R.isAmbiguous()) 11389 return nullptr; 11390 11391 if (R.empty()) { 11392 R.clear(); 11393 // Allow "using namespace std;" or "using namespace ::std;" even if 11394 // "std" hasn't been defined yet, for GCC compatibility. 11395 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11396 NamespcName->isStr("std")) { 11397 Diag(IdentLoc, diag::ext_using_undefined_std); 11398 R.addDecl(getOrCreateStdNamespace()); 11399 R.resolveKind(); 11400 } 11401 // Otherwise, attempt typo correction. 11402 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11403 } 11404 11405 if (!R.empty()) { 11406 NamedDecl *Named = R.getRepresentativeDecl(); 11407 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11408 assert(NS && "expected namespace decl"); 11409 11410 // The use of a nested name specifier may trigger deprecation warnings. 11411 DiagnoseUseOfDecl(Named, IdentLoc); 11412 11413 // C++ [namespace.udir]p1: 11414 // A using-directive specifies that the names in the nominated 11415 // namespace can be used in the scope in which the 11416 // using-directive appears after the using-directive. During 11417 // unqualified name lookup (3.4.1), the names appear as if they 11418 // were declared in the nearest enclosing namespace which 11419 // contains both the using-directive and the nominated 11420 // namespace. [Note: in this context, "contains" means "contains 11421 // directly or indirectly". ] 11422 11423 // Find enclosing context containing both using-directive and 11424 // nominated namespace. 11425 DeclContext *CommonAncestor = NS; 11426 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11427 CommonAncestor = CommonAncestor->getParent(); 11428 11429 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11430 SS.getWithLocInContext(Context), 11431 IdentLoc, Named, CommonAncestor); 11432 11433 if (IsUsingDirectiveInToplevelContext(CurContext) && 11434 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11435 Diag(IdentLoc, diag::warn_using_directive_in_header); 11436 } 11437 11438 PushUsingDirective(S, UDir); 11439 } else { 11440 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11441 } 11442 11443 if (UDir) 11444 ProcessDeclAttributeList(S, UDir, AttrList); 11445 11446 return UDir; 11447 } 11448 11449 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11450 // If the scope has an associated entity and the using directive is at 11451 // namespace or translation unit scope, add the UsingDirectiveDecl into 11452 // its lookup structure so qualified name lookup can find it. 11453 DeclContext *Ctx = S->getEntity(); 11454 if (Ctx && !Ctx->isFunctionOrMethod()) 11455 Ctx->addDecl(UDir); 11456 else 11457 // Otherwise, it is at block scope. The using-directives will affect lookup 11458 // only to the end of the scope. 11459 S->PushUsingDirective(UDir); 11460 } 11461 11462 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11463 SourceLocation UsingLoc, 11464 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11465 UnqualifiedId &Name, 11466 SourceLocation EllipsisLoc, 11467 const ParsedAttributesView &AttrList) { 11468 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11469 11470 if (SS.isEmpty()) { 11471 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11472 return nullptr; 11473 } 11474 11475 switch (Name.getKind()) { 11476 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11477 case UnqualifiedIdKind::IK_Identifier: 11478 case UnqualifiedIdKind::IK_OperatorFunctionId: 11479 case UnqualifiedIdKind::IK_LiteralOperatorId: 11480 case UnqualifiedIdKind::IK_ConversionFunctionId: 11481 break; 11482 11483 case UnqualifiedIdKind::IK_ConstructorName: 11484 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11485 // C++11 inheriting constructors. 11486 Diag(Name.getBeginLoc(), 11487 getLangOpts().CPlusPlus11 11488 ? diag::warn_cxx98_compat_using_decl_constructor 11489 : diag::err_using_decl_constructor) 11490 << SS.getRange(); 11491 11492 if (getLangOpts().CPlusPlus11) break; 11493 11494 return nullptr; 11495 11496 case UnqualifiedIdKind::IK_DestructorName: 11497 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11498 return nullptr; 11499 11500 case UnqualifiedIdKind::IK_TemplateId: 11501 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11502 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11503 return nullptr; 11504 11505 case UnqualifiedIdKind::IK_DeductionGuideName: 11506 llvm_unreachable("cannot parse qualified deduction guide name"); 11507 } 11508 11509 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11510 DeclarationName TargetName = TargetNameInfo.getName(); 11511 if (!TargetName) 11512 return nullptr; 11513 11514 // Warn about access declarations. 11515 if (UsingLoc.isInvalid()) { 11516 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11517 ? diag::err_access_decl 11518 : diag::warn_access_decl_deprecated) 11519 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11520 } 11521 11522 if (EllipsisLoc.isInvalid()) { 11523 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11524 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11525 return nullptr; 11526 } else { 11527 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11528 !TargetNameInfo.containsUnexpandedParameterPack()) { 11529 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11530 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11531 EllipsisLoc = SourceLocation(); 11532 } 11533 } 11534 11535 NamedDecl *UD = 11536 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 11537 SS, TargetNameInfo, EllipsisLoc, AttrList, 11538 /*IsInstantiation*/false); 11539 if (UD) 11540 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11541 11542 return UD; 11543 } 11544 11545 /// Determine whether a using declaration considers the given 11546 /// declarations as "equivalent", e.g., if they are redeclarations of 11547 /// the same entity or are both typedefs of the same type. 11548 static bool 11549 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11550 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11551 return true; 11552 11553 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11554 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11555 return Context.hasSameType(TD1->getUnderlyingType(), 11556 TD2->getUnderlyingType()); 11557 11558 return false; 11559 } 11560 11561 11562 /// Determines whether to create a using shadow decl for a particular 11563 /// decl, given the set of decls existing prior to this using lookup. 11564 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 11565 const LookupResult &Previous, 11566 UsingShadowDecl *&PrevShadow) { 11567 // Diagnose finding a decl which is not from a base class of the 11568 // current class. We do this now because there are cases where this 11569 // function will silently decide not to build a shadow decl, which 11570 // will pre-empt further diagnostics. 11571 // 11572 // We don't need to do this in C++11 because we do the check once on 11573 // the qualifier. 11574 // 11575 // FIXME: diagnose the following if we care enough: 11576 // struct A { int foo; }; 11577 // struct B : A { using A::foo; }; 11578 // template <class T> struct C : A {}; 11579 // template <class T> struct D : C<T> { using B::foo; } // <--- 11580 // This is invalid (during instantiation) in C++03 because B::foo 11581 // resolves to the using decl in B, which is not a base class of D<T>. 11582 // We can't diagnose it immediately because C<T> is an unknown 11583 // specialization. The UsingShadowDecl in D<T> then points directly 11584 // to A::foo, which will look well-formed when we instantiate. 11585 // The right solution is to not collapse the shadow-decl chain. 11586 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 11587 DeclContext *OrigDC = Orig->getDeclContext(); 11588 11589 // Handle enums and anonymous structs. 11590 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 11591 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 11592 while (OrigRec->isAnonymousStructOrUnion()) 11593 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 11594 11595 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 11596 if (OrigDC == CurContext) { 11597 Diag(Using->getLocation(), 11598 diag::err_using_decl_nested_name_specifier_is_current_class) 11599 << Using->getQualifierLoc().getSourceRange(); 11600 Diag(Orig->getLocation(), diag::note_using_decl_target); 11601 Using->setInvalidDecl(); 11602 return true; 11603 } 11604 11605 Diag(Using->getQualifierLoc().getBeginLoc(), 11606 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11607 << Using->getQualifier() 11608 << cast<CXXRecordDecl>(CurContext) 11609 << Using->getQualifierLoc().getSourceRange(); 11610 Diag(Orig->getLocation(), diag::note_using_decl_target); 11611 Using->setInvalidDecl(); 11612 return true; 11613 } 11614 } 11615 11616 if (Previous.empty()) return false; 11617 11618 NamedDecl *Target = Orig; 11619 if (isa<UsingShadowDecl>(Target)) 11620 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11621 11622 // If the target happens to be one of the previous declarations, we 11623 // don't have a conflict. 11624 // 11625 // FIXME: but we might be increasing its access, in which case we 11626 // should redeclare it. 11627 NamedDecl *NonTag = nullptr, *Tag = nullptr; 11628 bool FoundEquivalentDecl = false; 11629 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 11630 I != E; ++I) { 11631 NamedDecl *D = (*I)->getUnderlyingDecl(); 11632 // We can have UsingDecls in our Previous results because we use the same 11633 // LookupResult for checking whether the UsingDecl itself is a valid 11634 // redeclaration. 11635 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 11636 continue; 11637 11638 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 11639 // C++ [class.mem]p19: 11640 // If T is the name of a class, then [every named member other than 11641 // a non-static data member] shall have a name different from T 11642 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11643 !isa<IndirectFieldDecl>(Target) && 11644 !isa<UnresolvedUsingValueDecl>(Target) && 11645 DiagnoseClassNameShadow( 11646 CurContext, 11647 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 11648 return true; 11649 } 11650 11651 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11652 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11653 PrevShadow = Shadow; 11654 FoundEquivalentDecl = true; 11655 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11656 // We don't conflict with an existing using shadow decl of an equivalent 11657 // declaration, but we're not a redeclaration of it. 11658 FoundEquivalentDecl = true; 11659 } 11660 11661 if (isVisible(D)) 11662 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11663 } 11664 11665 if (FoundEquivalentDecl) 11666 return false; 11667 11668 if (FunctionDecl *FD = Target->getAsFunction()) { 11669 NamedDecl *OldDecl = nullptr; 11670 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11671 /*IsForUsingDecl*/ true)) { 11672 case Ovl_Overload: 11673 return false; 11674 11675 case Ovl_NonFunction: 11676 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11677 break; 11678 11679 // We found a decl with the exact signature. 11680 case Ovl_Match: 11681 // If we're in a record, we want to hide the target, so we 11682 // return true (without a diagnostic) to tell the caller not to 11683 // build a shadow decl. 11684 if (CurContext->isRecord()) 11685 return true; 11686 11687 // If we're not in a record, this is an error. 11688 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11689 break; 11690 } 11691 11692 Diag(Target->getLocation(), diag::note_using_decl_target); 11693 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 11694 Using->setInvalidDecl(); 11695 return true; 11696 } 11697 11698 // Target is not a function. 11699 11700 if (isa<TagDecl>(Target)) { 11701 // No conflict between a tag and a non-tag. 11702 if (!Tag) return false; 11703 11704 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11705 Diag(Target->getLocation(), diag::note_using_decl_target); 11706 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 11707 Using->setInvalidDecl(); 11708 return true; 11709 } 11710 11711 // No conflict between a tag and a non-tag. 11712 if (!NonTag) return false; 11713 11714 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11715 Diag(Target->getLocation(), diag::note_using_decl_target); 11716 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 11717 Using->setInvalidDecl(); 11718 return true; 11719 } 11720 11721 /// Determine whether a direct base class is a virtual base class. 11722 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 11723 if (!Derived->getNumVBases()) 11724 return false; 11725 for (auto &B : Derived->bases()) 11726 if (B.getType()->getAsCXXRecordDecl() == Base) 11727 return B.isVirtual(); 11728 llvm_unreachable("not a direct base class"); 11729 } 11730 11731 /// Builds a shadow declaration corresponding to a 'using' declaration. 11732 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 11733 UsingDecl *UD, 11734 NamedDecl *Orig, 11735 UsingShadowDecl *PrevDecl) { 11736 // If we resolved to another shadow declaration, just coalesce them. 11737 NamedDecl *Target = Orig; 11738 if (isa<UsingShadowDecl>(Target)) { 11739 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11740 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 11741 } 11742 11743 NamedDecl *NonTemplateTarget = Target; 11744 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 11745 NonTemplateTarget = TargetTD->getTemplatedDecl(); 11746 11747 UsingShadowDecl *Shadow; 11748 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 11749 bool IsVirtualBase = 11750 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 11751 UD->getQualifier()->getAsRecordDecl()); 11752 Shadow = ConstructorUsingShadowDecl::Create( 11753 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 11754 } else { 11755 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 11756 Target); 11757 } 11758 UD->addShadowDecl(Shadow); 11759 11760 Shadow->setAccess(UD->getAccess()); 11761 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 11762 Shadow->setInvalidDecl(); 11763 11764 Shadow->setPreviousDecl(PrevDecl); 11765 11766 if (S) 11767 PushOnScopeChains(Shadow, S); 11768 else 11769 CurContext->addDecl(Shadow); 11770 11771 11772 return Shadow; 11773 } 11774 11775 /// Hides a using shadow declaration. This is required by the current 11776 /// using-decl implementation when a resolvable using declaration in a 11777 /// class is followed by a declaration which would hide or override 11778 /// one or more of the using decl's targets; for example: 11779 /// 11780 /// struct Base { void foo(int); }; 11781 /// struct Derived : Base { 11782 /// using Base::foo; 11783 /// void foo(int); 11784 /// }; 11785 /// 11786 /// The governing language is C++03 [namespace.udecl]p12: 11787 /// 11788 /// When a using-declaration brings names from a base class into a 11789 /// derived class scope, member functions in the derived class 11790 /// override and/or hide member functions with the same name and 11791 /// parameter types in a base class (rather than conflicting). 11792 /// 11793 /// There are two ways to implement this: 11794 /// (1) optimistically create shadow decls when they're not hidden 11795 /// by existing declarations, or 11796 /// (2) don't create any shadow decls (or at least don't make them 11797 /// visible) until we've fully parsed/instantiated the class. 11798 /// The problem with (1) is that we might have to retroactively remove 11799 /// a shadow decl, which requires several O(n) operations because the 11800 /// decl structures are (very reasonably) not designed for removal. 11801 /// (2) avoids this but is very fiddly and phase-dependent. 11802 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 11803 if (Shadow->getDeclName().getNameKind() == 11804 DeclarationName::CXXConversionFunctionName) 11805 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 11806 11807 // Remove it from the DeclContext... 11808 Shadow->getDeclContext()->removeDecl(Shadow); 11809 11810 // ...and the scope, if applicable... 11811 if (S) { 11812 S->RemoveDecl(Shadow); 11813 IdResolver.RemoveDecl(Shadow); 11814 } 11815 11816 // ...and the using decl. 11817 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 11818 11819 // TODO: complain somehow if Shadow was used. It shouldn't 11820 // be possible for this to happen, because...? 11821 } 11822 11823 /// Find the base specifier for a base class with the given type. 11824 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 11825 QualType DesiredBase, 11826 bool &AnyDependentBases) { 11827 // Check whether the named type is a direct base class. 11828 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 11829 .getUnqualifiedType(); 11830 for (auto &Base : Derived->bases()) { 11831 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 11832 if (CanonicalDesiredBase == BaseType) 11833 return &Base; 11834 if (BaseType->isDependentType()) 11835 AnyDependentBases = true; 11836 } 11837 return nullptr; 11838 } 11839 11840 namespace { 11841 class UsingValidatorCCC final : public CorrectionCandidateCallback { 11842 public: 11843 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 11844 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 11845 : HasTypenameKeyword(HasTypenameKeyword), 11846 IsInstantiation(IsInstantiation), OldNNS(NNS), 11847 RequireMemberOf(RequireMemberOf) {} 11848 11849 bool ValidateCandidate(const TypoCorrection &Candidate) override { 11850 NamedDecl *ND = Candidate.getCorrectionDecl(); 11851 11852 // Keywords are not valid here. 11853 if (!ND || isa<NamespaceDecl>(ND)) 11854 return false; 11855 11856 // Completely unqualified names are invalid for a 'using' declaration. 11857 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 11858 return false; 11859 11860 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 11861 // reject. 11862 11863 if (RequireMemberOf) { 11864 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11865 if (FoundRecord && FoundRecord->isInjectedClassName()) { 11866 // No-one ever wants a using-declaration to name an injected-class-name 11867 // of a base class, unless they're declaring an inheriting constructor. 11868 ASTContext &Ctx = ND->getASTContext(); 11869 if (!Ctx.getLangOpts().CPlusPlus11) 11870 return false; 11871 QualType FoundType = Ctx.getRecordType(FoundRecord); 11872 11873 // Check that the injected-class-name is named as a member of its own 11874 // type; we don't want to suggest 'using Derived::Base;', since that 11875 // means something else. 11876 NestedNameSpecifier *Specifier = 11877 Candidate.WillReplaceSpecifier() 11878 ? Candidate.getCorrectionSpecifier() 11879 : OldNNS; 11880 if (!Specifier->getAsType() || 11881 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 11882 return false; 11883 11884 // Check that this inheriting constructor declaration actually names a 11885 // direct base class of the current class. 11886 bool AnyDependentBases = false; 11887 if (!findDirectBaseWithType(RequireMemberOf, 11888 Ctx.getRecordType(FoundRecord), 11889 AnyDependentBases) && 11890 !AnyDependentBases) 11891 return false; 11892 } else { 11893 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 11894 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 11895 return false; 11896 11897 // FIXME: Check that the base class member is accessible? 11898 } 11899 } else { 11900 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11901 if (FoundRecord && FoundRecord->isInjectedClassName()) 11902 return false; 11903 } 11904 11905 if (isa<TypeDecl>(ND)) 11906 return HasTypenameKeyword || !IsInstantiation; 11907 11908 return !HasTypenameKeyword; 11909 } 11910 11911 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11912 return std::make_unique<UsingValidatorCCC>(*this); 11913 } 11914 11915 private: 11916 bool HasTypenameKeyword; 11917 bool IsInstantiation; 11918 NestedNameSpecifier *OldNNS; 11919 CXXRecordDecl *RequireMemberOf; 11920 }; 11921 } // end anonymous namespace 11922 11923 /// Builds a using declaration. 11924 /// 11925 /// \param IsInstantiation - Whether this call arises from an 11926 /// instantiation of an unresolved using declaration. We treat 11927 /// the lookup differently for these declarations. 11928 NamedDecl *Sema::BuildUsingDeclaration( 11929 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 11930 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 11931 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 11932 const ParsedAttributesView &AttrList, bool IsInstantiation) { 11933 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11934 SourceLocation IdentLoc = NameInfo.getLoc(); 11935 assert(IdentLoc.isValid() && "Invalid TargetName location."); 11936 11937 // FIXME: We ignore attributes for now. 11938 11939 // For an inheriting constructor declaration, the name of the using 11940 // declaration is the name of a constructor in this class, not in the 11941 // base class. 11942 DeclarationNameInfo UsingName = NameInfo; 11943 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 11944 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 11945 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 11946 Context.getCanonicalType(Context.getRecordType(RD)))); 11947 11948 // Do the redeclaration lookup in the current scope. 11949 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 11950 ForVisibleRedeclaration); 11951 Previous.setHideTags(false); 11952 if (S) { 11953 LookupName(Previous, S); 11954 11955 // It is really dumb that we have to do this. 11956 LookupResult::Filter F = Previous.makeFilter(); 11957 while (F.hasNext()) { 11958 NamedDecl *D = F.next(); 11959 if (!isDeclInScope(D, CurContext, S)) 11960 F.erase(); 11961 // If we found a local extern declaration that's not ordinarily visible, 11962 // and this declaration is being added to a non-block scope, ignore it. 11963 // We're only checking for scope conflicts here, not also for violations 11964 // of the linkage rules. 11965 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 11966 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 11967 F.erase(); 11968 } 11969 F.done(); 11970 } else { 11971 assert(IsInstantiation && "no scope in non-instantiation"); 11972 if (CurContext->isRecord()) 11973 LookupQualifiedName(Previous, CurContext); 11974 else { 11975 // No redeclaration check is needed here; in non-member contexts we 11976 // diagnosed all possible conflicts with other using-declarations when 11977 // building the template: 11978 // 11979 // For a dependent non-type using declaration, the only valid case is 11980 // if we instantiate to a single enumerator. We check for conflicts 11981 // between shadow declarations we introduce, and we check in the template 11982 // definition for conflicts between a non-type using declaration and any 11983 // other declaration, which together covers all cases. 11984 // 11985 // A dependent typename using declaration will never successfully 11986 // instantiate, since it will always name a class member, so we reject 11987 // that in the template definition. 11988 } 11989 } 11990 11991 // Check for invalid redeclarations. 11992 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 11993 SS, IdentLoc, Previous)) 11994 return nullptr; 11995 11996 // Check for bad qualifiers. 11997 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 11998 IdentLoc)) 11999 return nullptr; 12000 12001 DeclContext *LookupContext = computeDeclContext(SS); 12002 NamedDecl *D; 12003 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12004 if (!LookupContext || EllipsisLoc.isValid()) { 12005 if (HasTypenameKeyword) { 12006 // FIXME: not all declaration name kinds are legal here 12007 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 12008 UsingLoc, TypenameLoc, 12009 QualifierLoc, 12010 IdentLoc, NameInfo.getName(), 12011 EllipsisLoc); 12012 } else { 12013 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 12014 QualifierLoc, NameInfo, EllipsisLoc); 12015 } 12016 D->setAccess(AS); 12017 CurContext->addDecl(D); 12018 return D; 12019 } 12020 12021 auto Build = [&](bool Invalid) { 12022 UsingDecl *UD = 12023 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 12024 UsingName, HasTypenameKeyword); 12025 UD->setAccess(AS); 12026 CurContext->addDecl(UD); 12027 UD->setInvalidDecl(Invalid); 12028 return UD; 12029 }; 12030 auto BuildInvalid = [&]{ return Build(true); }; 12031 auto BuildValid = [&]{ return Build(false); }; 12032 12033 if (RequireCompleteDeclContext(SS, LookupContext)) 12034 return BuildInvalid(); 12035 12036 // Look up the target name. 12037 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12038 12039 // Unlike most lookups, we don't always want to hide tag 12040 // declarations: tag names are visible through the using declaration 12041 // even if hidden by ordinary names, *except* in a dependent context 12042 // where it's important for the sanity of two-phase lookup. 12043 if (!IsInstantiation) 12044 R.setHideTags(false); 12045 12046 // For the purposes of this lookup, we have a base object type 12047 // equal to that of the current context. 12048 if (CurContext->isRecord()) { 12049 R.setBaseObjectType( 12050 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 12051 } 12052 12053 LookupQualifiedName(R, LookupContext); 12054 12055 // Try to correct typos if possible. If constructor name lookup finds no 12056 // results, that means the named class has no explicit constructors, and we 12057 // suppressed declaring implicit ones (probably because it's dependent or 12058 // invalid). 12059 if (R.empty() && 12060 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 12061 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 12062 // it will believe that glibc provides a ::gets in cases where it does not, 12063 // and will try to pull it into namespace std with a using-declaration. 12064 // Just ignore the using-declaration in that case. 12065 auto *II = NameInfo.getName().getAsIdentifierInfo(); 12066 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 12067 CurContext->isStdNamespace() && 12068 isa<TranslationUnitDecl>(LookupContext) && 12069 getSourceManager().isInSystemHeader(UsingLoc)) 12070 return nullptr; 12071 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 12072 dyn_cast<CXXRecordDecl>(CurContext)); 12073 if (TypoCorrection Corrected = 12074 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 12075 CTK_ErrorRecovery)) { 12076 // We reject candidates where DroppedSpecifier == true, hence the 12077 // literal '0' below. 12078 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 12079 << NameInfo.getName() << LookupContext << 0 12080 << SS.getRange()); 12081 12082 // If we picked a correction with no attached Decl we can't do anything 12083 // useful with it, bail out. 12084 NamedDecl *ND = Corrected.getCorrectionDecl(); 12085 if (!ND) 12086 return BuildInvalid(); 12087 12088 // If we corrected to an inheriting constructor, handle it as one. 12089 auto *RD = dyn_cast<CXXRecordDecl>(ND); 12090 if (RD && RD->isInjectedClassName()) { 12091 // The parent of the injected class name is the class itself. 12092 RD = cast<CXXRecordDecl>(RD->getParent()); 12093 12094 // Fix up the information we'll use to build the using declaration. 12095 if (Corrected.WillReplaceSpecifier()) { 12096 NestedNameSpecifierLocBuilder Builder; 12097 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 12098 QualifierLoc.getSourceRange()); 12099 QualifierLoc = Builder.getWithLocInContext(Context); 12100 } 12101 12102 // In this case, the name we introduce is the name of a derived class 12103 // constructor. 12104 auto *CurClass = cast<CXXRecordDecl>(CurContext); 12105 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12106 Context.getCanonicalType(Context.getRecordType(CurClass)))); 12107 UsingName.setNamedTypeInfo(nullptr); 12108 for (auto *Ctor : LookupConstructors(RD)) 12109 R.addDecl(Ctor); 12110 R.resolveKind(); 12111 } else { 12112 // FIXME: Pick up all the declarations if we found an overloaded 12113 // function. 12114 UsingName.setName(ND->getDeclName()); 12115 R.addDecl(ND); 12116 } 12117 } else { 12118 Diag(IdentLoc, diag::err_no_member) 12119 << NameInfo.getName() << LookupContext << SS.getRange(); 12120 return BuildInvalid(); 12121 } 12122 } 12123 12124 if (R.isAmbiguous()) 12125 return BuildInvalid(); 12126 12127 if (HasTypenameKeyword) { 12128 // If we asked for a typename and got a non-type decl, error out. 12129 if (!R.getAsSingle<TypeDecl>()) { 12130 Diag(IdentLoc, diag::err_using_typename_non_type); 12131 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12132 Diag((*I)->getUnderlyingDecl()->getLocation(), 12133 diag::note_using_decl_target); 12134 return BuildInvalid(); 12135 } 12136 } else { 12137 // If we asked for a non-typename and we got a type, error out, 12138 // but only if this is an instantiation of an unresolved using 12139 // decl. Otherwise just silently find the type name. 12140 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 12141 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 12142 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 12143 return BuildInvalid(); 12144 } 12145 } 12146 12147 // C++14 [namespace.udecl]p6: 12148 // A using-declaration shall not name a namespace. 12149 if (R.getAsSingle<NamespaceDecl>()) { 12150 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 12151 << SS.getRange(); 12152 return BuildInvalid(); 12153 } 12154 12155 // C++14 [namespace.udecl]p7: 12156 // A using-declaration shall not name a scoped enumerator. 12157 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 12158 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 12159 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 12160 << SS.getRange(); 12161 return BuildInvalid(); 12162 } 12163 } 12164 12165 UsingDecl *UD = BuildValid(); 12166 12167 // Some additional rules apply to inheriting constructors. 12168 if (UsingName.getName().getNameKind() == 12169 DeclarationName::CXXConstructorName) { 12170 // Suppress access diagnostics; the access check is instead performed at the 12171 // point of use for an inheriting constructor. 12172 R.suppressDiagnostics(); 12173 if (CheckInheritingConstructorUsingDecl(UD)) 12174 return UD; 12175 } 12176 12177 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 12178 UsingShadowDecl *PrevDecl = nullptr; 12179 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 12180 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 12181 } 12182 12183 return UD; 12184 } 12185 12186 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 12187 ArrayRef<NamedDecl *> Expansions) { 12188 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 12189 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 12190 isa<UsingPackDecl>(InstantiatedFrom)); 12191 12192 auto *UPD = 12193 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 12194 UPD->setAccess(InstantiatedFrom->getAccess()); 12195 CurContext->addDecl(UPD); 12196 return UPD; 12197 } 12198 12199 /// Additional checks for a using declaration referring to a constructor name. 12200 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 12201 assert(!UD->hasTypename() && "expecting a constructor name"); 12202 12203 const Type *SourceType = UD->getQualifier()->getAsType(); 12204 assert(SourceType && 12205 "Using decl naming constructor doesn't have type in scope spec."); 12206 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 12207 12208 // Check whether the named type is a direct base class. 12209 bool AnyDependentBases = false; 12210 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 12211 AnyDependentBases); 12212 if (!Base && !AnyDependentBases) { 12213 Diag(UD->getUsingLoc(), 12214 diag::err_using_decl_constructor_not_in_direct_base) 12215 << UD->getNameInfo().getSourceRange() 12216 << QualType(SourceType, 0) << TargetClass; 12217 UD->setInvalidDecl(); 12218 return true; 12219 } 12220 12221 if (Base) 12222 Base->setInheritConstructors(); 12223 12224 return false; 12225 } 12226 12227 /// Checks that the given using declaration is not an invalid 12228 /// redeclaration. Note that this is checking only for the using decl 12229 /// itself, not for any ill-formedness among the UsingShadowDecls. 12230 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 12231 bool HasTypenameKeyword, 12232 const CXXScopeSpec &SS, 12233 SourceLocation NameLoc, 12234 const LookupResult &Prev) { 12235 NestedNameSpecifier *Qual = SS.getScopeRep(); 12236 12237 // C++03 [namespace.udecl]p8: 12238 // C++0x [namespace.udecl]p10: 12239 // A using-declaration is a declaration and can therefore be used 12240 // repeatedly where (and only where) multiple declarations are 12241 // allowed. 12242 // 12243 // That's in non-member contexts. 12244 if (!CurContext->getRedeclContext()->isRecord()) { 12245 // A dependent qualifier outside a class can only ever resolve to an 12246 // enumeration type. Therefore it conflicts with any other non-type 12247 // declaration in the same scope. 12248 // FIXME: How should we check for dependent type-type conflicts at block 12249 // scope? 12250 if (Qual->isDependent() && !HasTypenameKeyword) { 12251 for (auto *D : Prev) { 12252 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 12253 bool OldCouldBeEnumerator = 12254 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 12255 Diag(NameLoc, 12256 OldCouldBeEnumerator ? diag::err_redefinition 12257 : diag::err_redefinition_different_kind) 12258 << Prev.getLookupName(); 12259 Diag(D->getLocation(), diag::note_previous_definition); 12260 return true; 12261 } 12262 } 12263 } 12264 return false; 12265 } 12266 12267 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 12268 NamedDecl *D = *I; 12269 12270 bool DTypename; 12271 NestedNameSpecifier *DQual; 12272 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 12273 DTypename = UD->hasTypename(); 12274 DQual = UD->getQualifier(); 12275 } else if (UnresolvedUsingValueDecl *UD 12276 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 12277 DTypename = false; 12278 DQual = UD->getQualifier(); 12279 } else if (UnresolvedUsingTypenameDecl *UD 12280 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 12281 DTypename = true; 12282 DQual = UD->getQualifier(); 12283 } else continue; 12284 12285 // using decls differ if one says 'typename' and the other doesn't. 12286 // FIXME: non-dependent using decls? 12287 if (HasTypenameKeyword != DTypename) continue; 12288 12289 // using decls differ if they name different scopes (but note that 12290 // template instantiation can cause this check to trigger when it 12291 // didn't before instantiation). 12292 if (Context.getCanonicalNestedNameSpecifier(Qual) != 12293 Context.getCanonicalNestedNameSpecifier(DQual)) 12294 continue; 12295 12296 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 12297 Diag(D->getLocation(), diag::note_using_decl) << 1; 12298 return true; 12299 } 12300 12301 return false; 12302 } 12303 12304 12305 /// Checks that the given nested-name qualifier used in a using decl 12306 /// in the current context is appropriately related to the current 12307 /// scope. If an error is found, diagnoses it and returns true. 12308 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 12309 bool HasTypename, 12310 const CXXScopeSpec &SS, 12311 const DeclarationNameInfo &NameInfo, 12312 SourceLocation NameLoc) { 12313 DeclContext *NamedContext = computeDeclContext(SS); 12314 12315 if (!CurContext->isRecord()) { 12316 // C++03 [namespace.udecl]p3: 12317 // C++0x [namespace.udecl]p8: 12318 // A using-declaration for a class member shall be a member-declaration. 12319 12320 // If we weren't able to compute a valid scope, it might validly be a 12321 // dependent class scope or a dependent enumeration unscoped scope. If 12322 // we have a 'typename' keyword, the scope must resolve to a class type. 12323 if ((HasTypename && !NamedContext) || 12324 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 12325 auto *RD = NamedContext 12326 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 12327 : nullptr; 12328 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 12329 RD = nullptr; 12330 12331 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 12332 << SS.getRange(); 12333 12334 // If we have a complete, non-dependent source type, try to suggest a 12335 // way to get the same effect. 12336 if (!RD) 12337 return true; 12338 12339 // Find what this using-declaration was referring to. 12340 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12341 R.setHideTags(false); 12342 R.suppressDiagnostics(); 12343 LookupQualifiedName(R, RD); 12344 12345 if (R.getAsSingle<TypeDecl>()) { 12346 if (getLangOpts().CPlusPlus11) { 12347 // Convert 'using X::Y;' to 'using Y = X::Y;'. 12348 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 12349 << 0 // alias declaration 12350 << FixItHint::CreateInsertion(SS.getBeginLoc(), 12351 NameInfo.getName().getAsString() + 12352 " = "); 12353 } else { 12354 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 12355 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 12356 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 12357 << 1 // typedef declaration 12358 << FixItHint::CreateReplacement(UsingLoc, "typedef") 12359 << FixItHint::CreateInsertion( 12360 InsertLoc, " " + NameInfo.getName().getAsString()); 12361 } 12362 } else if (R.getAsSingle<VarDecl>()) { 12363 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12364 // repeating the type of the static data member here. 12365 FixItHint FixIt; 12366 if (getLangOpts().CPlusPlus11) { 12367 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12368 FixIt = FixItHint::CreateReplacement( 12369 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 12370 } 12371 12372 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12373 << 2 // reference declaration 12374 << FixIt; 12375 } else if (R.getAsSingle<EnumConstantDecl>()) { 12376 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12377 // repeating the type of the enumeration here, and we can't do so if 12378 // the type is anonymous. 12379 FixItHint FixIt; 12380 if (getLangOpts().CPlusPlus11) { 12381 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12382 FixIt = FixItHint::CreateReplacement( 12383 UsingLoc, 12384 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 12385 } 12386 12387 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12388 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 12389 << FixIt; 12390 } 12391 return true; 12392 } 12393 12394 // Otherwise, this might be valid. 12395 return false; 12396 } 12397 12398 // The current scope is a record. 12399 12400 // If the named context is dependent, we can't decide much. 12401 if (!NamedContext) { 12402 // FIXME: in C++0x, we can diagnose if we can prove that the 12403 // nested-name-specifier does not refer to a base class, which is 12404 // still possible in some cases. 12405 12406 // Otherwise we have to conservatively report that things might be 12407 // okay. 12408 return false; 12409 } 12410 12411 if (!NamedContext->isRecord()) { 12412 // Ideally this would point at the last name in the specifier, 12413 // but we don't have that level of source info. 12414 Diag(SS.getRange().getBegin(), 12415 diag::err_using_decl_nested_name_specifier_is_not_class) 12416 << SS.getScopeRep() << SS.getRange(); 12417 return true; 12418 } 12419 12420 if (!NamedContext->isDependentContext() && 12421 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 12422 return true; 12423 12424 if (getLangOpts().CPlusPlus11) { 12425 // C++11 [namespace.udecl]p3: 12426 // In a using-declaration used as a member-declaration, the 12427 // nested-name-specifier shall name a base class of the class 12428 // being defined. 12429 12430 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 12431 cast<CXXRecordDecl>(NamedContext))) { 12432 if (CurContext == NamedContext) { 12433 Diag(NameLoc, 12434 diag::err_using_decl_nested_name_specifier_is_current_class) 12435 << SS.getRange(); 12436 return true; 12437 } 12438 12439 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 12440 Diag(SS.getRange().getBegin(), 12441 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12442 << SS.getScopeRep() 12443 << cast<CXXRecordDecl>(CurContext) 12444 << SS.getRange(); 12445 } 12446 return true; 12447 } 12448 12449 return false; 12450 } 12451 12452 // C++03 [namespace.udecl]p4: 12453 // A using-declaration used as a member-declaration shall refer 12454 // to a member of a base class of the class being defined [etc.]. 12455 12456 // Salient point: SS doesn't have to name a base class as long as 12457 // lookup only finds members from base classes. Therefore we can 12458 // diagnose here only if we can prove that that can't happen, 12459 // i.e. if the class hierarchies provably don't intersect. 12460 12461 // TODO: it would be nice if "definitely valid" results were cached 12462 // in the UsingDecl and UsingShadowDecl so that these checks didn't 12463 // need to be repeated. 12464 12465 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 12466 auto Collect = [&Bases](const CXXRecordDecl *Base) { 12467 Bases.insert(Base); 12468 return true; 12469 }; 12470 12471 // Collect all bases. Return false if we find a dependent base. 12472 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 12473 return false; 12474 12475 // Returns true if the base is dependent or is one of the accumulated base 12476 // classes. 12477 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 12478 return !Bases.count(Base); 12479 }; 12480 12481 // Return false if the class has a dependent base or if it or one 12482 // of its bases is present in the base set of the current context. 12483 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 12484 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 12485 return false; 12486 12487 Diag(SS.getRange().getBegin(), 12488 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12489 << SS.getScopeRep() 12490 << cast<CXXRecordDecl>(CurContext) 12491 << SS.getRange(); 12492 12493 return true; 12494 } 12495 12496 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 12497 MultiTemplateParamsArg TemplateParamLists, 12498 SourceLocation UsingLoc, UnqualifiedId &Name, 12499 const ParsedAttributesView &AttrList, 12500 TypeResult Type, Decl *DeclFromDeclSpec) { 12501 // Skip up to the relevant declaration scope. 12502 while (S->isTemplateParamScope()) 12503 S = S->getParent(); 12504 assert((S->getFlags() & Scope::DeclScope) && 12505 "got alias-declaration outside of declaration scope"); 12506 12507 if (Type.isInvalid()) 12508 return nullptr; 12509 12510 bool Invalid = false; 12511 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 12512 TypeSourceInfo *TInfo = nullptr; 12513 GetTypeFromParser(Type.get(), &TInfo); 12514 12515 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 12516 return nullptr; 12517 12518 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 12519 UPPC_DeclarationType)) { 12520 Invalid = true; 12521 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12522 TInfo->getTypeLoc().getBeginLoc()); 12523 } 12524 12525 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12526 TemplateParamLists.size() 12527 ? forRedeclarationInCurContext() 12528 : ForVisibleRedeclaration); 12529 LookupName(Previous, S); 12530 12531 // Warn about shadowing the name of a template parameter. 12532 if (Previous.isSingleResult() && 12533 Previous.getFoundDecl()->isTemplateParameter()) { 12534 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 12535 Previous.clear(); 12536 } 12537 12538 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 12539 "name in alias declaration must be an identifier"); 12540 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 12541 Name.StartLocation, 12542 Name.Identifier, TInfo); 12543 12544 NewTD->setAccess(AS); 12545 12546 if (Invalid) 12547 NewTD->setInvalidDecl(); 12548 12549 ProcessDeclAttributeList(S, NewTD, AttrList); 12550 AddPragmaAttributes(S, NewTD); 12551 12552 CheckTypedefForVariablyModifiedType(S, NewTD); 12553 Invalid |= NewTD->isInvalidDecl(); 12554 12555 bool Redeclaration = false; 12556 12557 NamedDecl *NewND; 12558 if (TemplateParamLists.size()) { 12559 TypeAliasTemplateDecl *OldDecl = nullptr; 12560 TemplateParameterList *OldTemplateParams = nullptr; 12561 12562 if (TemplateParamLists.size() != 1) { 12563 Diag(UsingLoc, diag::err_alias_template_extra_headers) 12564 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 12565 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 12566 } 12567 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 12568 12569 // Check that we can declare a template here. 12570 if (CheckTemplateDeclScope(S, TemplateParams)) 12571 return nullptr; 12572 12573 // Only consider previous declarations in the same scope. 12574 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 12575 /*ExplicitInstantiationOrSpecialization*/false); 12576 if (!Previous.empty()) { 12577 Redeclaration = true; 12578 12579 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 12580 if (!OldDecl && !Invalid) { 12581 Diag(UsingLoc, diag::err_redefinition_different_kind) 12582 << Name.Identifier; 12583 12584 NamedDecl *OldD = Previous.getRepresentativeDecl(); 12585 if (OldD->getLocation().isValid()) 12586 Diag(OldD->getLocation(), diag::note_previous_definition); 12587 12588 Invalid = true; 12589 } 12590 12591 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 12592 if (TemplateParameterListsAreEqual(TemplateParams, 12593 OldDecl->getTemplateParameters(), 12594 /*Complain=*/true, 12595 TPL_TemplateMatch)) 12596 OldTemplateParams = 12597 OldDecl->getMostRecentDecl()->getTemplateParameters(); 12598 else 12599 Invalid = true; 12600 12601 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 12602 if (!Invalid && 12603 !Context.hasSameType(OldTD->getUnderlyingType(), 12604 NewTD->getUnderlyingType())) { 12605 // FIXME: The C++0x standard does not clearly say this is ill-formed, 12606 // but we can't reasonably accept it. 12607 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 12608 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 12609 if (OldTD->getLocation().isValid()) 12610 Diag(OldTD->getLocation(), diag::note_previous_definition); 12611 Invalid = true; 12612 } 12613 } 12614 } 12615 12616 // Merge any previous default template arguments into our parameters, 12617 // and check the parameter list. 12618 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 12619 TPC_TypeAliasTemplate)) 12620 return nullptr; 12621 12622 TypeAliasTemplateDecl *NewDecl = 12623 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 12624 Name.Identifier, TemplateParams, 12625 NewTD); 12626 NewTD->setDescribedAliasTemplate(NewDecl); 12627 12628 NewDecl->setAccess(AS); 12629 12630 if (Invalid) 12631 NewDecl->setInvalidDecl(); 12632 else if (OldDecl) { 12633 NewDecl->setPreviousDecl(OldDecl); 12634 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 12635 } 12636 12637 NewND = NewDecl; 12638 } else { 12639 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 12640 setTagNameForLinkagePurposes(TD, NewTD); 12641 handleTagNumbering(TD, S); 12642 } 12643 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 12644 NewND = NewTD; 12645 } 12646 12647 PushOnScopeChains(NewND, S); 12648 ActOnDocumentableDecl(NewND); 12649 return NewND; 12650 } 12651 12652 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 12653 SourceLocation AliasLoc, 12654 IdentifierInfo *Alias, CXXScopeSpec &SS, 12655 SourceLocation IdentLoc, 12656 IdentifierInfo *Ident) { 12657 12658 // Lookup the namespace name. 12659 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 12660 LookupParsedName(R, S, &SS); 12661 12662 if (R.isAmbiguous()) 12663 return nullptr; 12664 12665 if (R.empty()) { 12666 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 12667 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 12668 return nullptr; 12669 } 12670 } 12671 assert(!R.isAmbiguous() && !R.empty()); 12672 NamedDecl *ND = R.getRepresentativeDecl(); 12673 12674 // Check if we have a previous declaration with the same name. 12675 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 12676 ForVisibleRedeclaration); 12677 LookupName(PrevR, S); 12678 12679 // Check we're not shadowing a template parameter. 12680 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 12681 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 12682 PrevR.clear(); 12683 } 12684 12685 // Filter out any other lookup result from an enclosing scope. 12686 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 12687 /*AllowInlineNamespace*/false); 12688 12689 // Find the previous declaration and check that we can redeclare it. 12690 NamespaceAliasDecl *Prev = nullptr; 12691 if (PrevR.isSingleResult()) { 12692 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 12693 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 12694 // We already have an alias with the same name that points to the same 12695 // namespace; check that it matches. 12696 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 12697 Prev = AD; 12698 } else if (isVisible(PrevDecl)) { 12699 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 12700 << Alias; 12701 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 12702 << AD->getNamespace(); 12703 return nullptr; 12704 } 12705 } else if (isVisible(PrevDecl)) { 12706 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 12707 ? diag::err_redefinition 12708 : diag::err_redefinition_different_kind; 12709 Diag(AliasLoc, DiagID) << Alias; 12710 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12711 return nullptr; 12712 } 12713 } 12714 12715 // The use of a nested name specifier may trigger deprecation warnings. 12716 DiagnoseUseOfDecl(ND, IdentLoc); 12717 12718 NamespaceAliasDecl *AliasDecl = 12719 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 12720 Alias, SS.getWithLocInContext(Context), 12721 IdentLoc, ND); 12722 if (Prev) 12723 AliasDecl->setPreviousDecl(Prev); 12724 12725 PushOnScopeChains(AliasDecl, S); 12726 return AliasDecl; 12727 } 12728 12729 namespace { 12730 struct SpecialMemberExceptionSpecInfo 12731 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 12732 SourceLocation Loc; 12733 Sema::ImplicitExceptionSpecification ExceptSpec; 12734 12735 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 12736 Sema::CXXSpecialMember CSM, 12737 Sema::InheritedConstructorInfo *ICI, 12738 SourceLocation Loc) 12739 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 12740 12741 bool visitBase(CXXBaseSpecifier *Base); 12742 bool visitField(FieldDecl *FD); 12743 12744 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 12745 unsigned Quals); 12746 12747 void visitSubobjectCall(Subobject Subobj, 12748 Sema::SpecialMemberOverloadResult SMOR); 12749 }; 12750 } 12751 12752 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 12753 auto *RT = Base->getType()->getAs<RecordType>(); 12754 if (!RT) 12755 return false; 12756 12757 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 12758 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 12759 if (auto *BaseCtor = SMOR.getMethod()) { 12760 visitSubobjectCall(Base, BaseCtor); 12761 return false; 12762 } 12763 12764 visitClassSubobject(BaseClass, Base, 0); 12765 return false; 12766 } 12767 12768 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 12769 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 12770 Expr *E = FD->getInClassInitializer(); 12771 if (!E) 12772 // FIXME: It's a little wasteful to build and throw away a 12773 // CXXDefaultInitExpr here. 12774 // FIXME: We should have a single context note pointing at Loc, and 12775 // this location should be MD->getLocation() instead, since that's 12776 // the location where we actually use the default init expression. 12777 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 12778 if (E) 12779 ExceptSpec.CalledExpr(E); 12780 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 12781 ->getAs<RecordType>()) { 12782 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 12783 FD->getType().getCVRQualifiers()); 12784 } 12785 return false; 12786 } 12787 12788 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 12789 Subobject Subobj, 12790 unsigned Quals) { 12791 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 12792 bool IsMutable = Field && Field->isMutable(); 12793 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 12794 } 12795 12796 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 12797 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 12798 // Note, if lookup fails, it doesn't matter what exception specification we 12799 // choose because the special member will be deleted. 12800 if (CXXMethodDecl *MD = SMOR.getMethod()) 12801 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 12802 } 12803 12804 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 12805 llvm::APSInt Result; 12806 ExprResult Converted = CheckConvertedConstantExpression( 12807 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 12808 ExplicitSpec.setExpr(Converted.get()); 12809 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 12810 ExplicitSpec.setKind(Result.getBoolValue() 12811 ? ExplicitSpecKind::ResolvedTrue 12812 : ExplicitSpecKind::ResolvedFalse); 12813 return true; 12814 } 12815 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 12816 return false; 12817 } 12818 12819 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 12820 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 12821 if (!ExplicitExpr->isTypeDependent()) 12822 tryResolveExplicitSpecifier(ES); 12823 return ES; 12824 } 12825 12826 static Sema::ImplicitExceptionSpecification 12827 ComputeDefaultedSpecialMemberExceptionSpec( 12828 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 12829 Sema::InheritedConstructorInfo *ICI) { 12830 ComputingExceptionSpec CES(S, MD, Loc); 12831 12832 CXXRecordDecl *ClassDecl = MD->getParent(); 12833 12834 // C++ [except.spec]p14: 12835 // An implicitly declared special member function (Clause 12) shall have an 12836 // exception-specification. [...] 12837 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 12838 if (ClassDecl->isInvalidDecl()) 12839 return Info.ExceptSpec; 12840 12841 // FIXME: If this diagnostic fires, we're probably missing a check for 12842 // attempting to resolve an exception specification before it's known 12843 // at a higher level. 12844 if (S.RequireCompleteType(MD->getLocation(), 12845 S.Context.getRecordType(ClassDecl), 12846 diag::err_exception_spec_incomplete_type)) 12847 return Info.ExceptSpec; 12848 12849 // C++1z [except.spec]p7: 12850 // [Look for exceptions thrown by] a constructor selected [...] to 12851 // initialize a potentially constructed subobject, 12852 // C++1z [except.spec]p8: 12853 // The exception specification for an implicitly-declared destructor, or a 12854 // destructor without a noexcept-specifier, is potentially-throwing if and 12855 // only if any of the destructors for any of its potentially constructed 12856 // subojects is potentially throwing. 12857 // FIXME: We respect the first rule but ignore the "potentially constructed" 12858 // in the second rule to resolve a core issue (no number yet) that would have 12859 // us reject: 12860 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 12861 // struct B : A {}; 12862 // struct C : B { void f(); }; 12863 // ... due to giving B::~B() a non-throwing exception specification. 12864 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 12865 : Info.VisitAllBases); 12866 12867 return Info.ExceptSpec; 12868 } 12869 12870 namespace { 12871 /// RAII object to register a special member as being currently declared. 12872 struct DeclaringSpecialMember { 12873 Sema &S; 12874 Sema::SpecialMemberDecl D; 12875 Sema::ContextRAII SavedContext; 12876 bool WasAlreadyBeingDeclared; 12877 12878 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 12879 : S(S), D(RD, CSM), SavedContext(S, RD) { 12880 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 12881 if (WasAlreadyBeingDeclared) 12882 // This almost never happens, but if it does, ensure that our cache 12883 // doesn't contain a stale result. 12884 S.SpecialMemberCache.clear(); 12885 else { 12886 // Register a note to be produced if we encounter an error while 12887 // declaring the special member. 12888 Sema::CodeSynthesisContext Ctx; 12889 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 12890 // FIXME: We don't have a location to use here. Using the class's 12891 // location maintains the fiction that we declare all special members 12892 // with the class, but (1) it's not clear that lying about that helps our 12893 // users understand what's going on, and (2) there may be outer contexts 12894 // on the stack (some of which are relevant) and printing them exposes 12895 // our lies. 12896 Ctx.PointOfInstantiation = RD->getLocation(); 12897 Ctx.Entity = RD; 12898 Ctx.SpecialMember = CSM; 12899 S.pushCodeSynthesisContext(Ctx); 12900 } 12901 } 12902 ~DeclaringSpecialMember() { 12903 if (!WasAlreadyBeingDeclared) { 12904 S.SpecialMembersBeingDeclared.erase(D); 12905 S.popCodeSynthesisContext(); 12906 } 12907 } 12908 12909 /// Are we already trying to declare this special member? 12910 bool isAlreadyBeingDeclared() const { 12911 return WasAlreadyBeingDeclared; 12912 } 12913 }; 12914 } 12915 12916 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 12917 // Look up any existing declarations, but don't trigger declaration of all 12918 // implicit special members with this name. 12919 DeclarationName Name = FD->getDeclName(); 12920 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 12921 ForExternalRedeclaration); 12922 for (auto *D : FD->getParent()->lookup(Name)) 12923 if (auto *Acceptable = R.getAcceptableDecl(D)) 12924 R.addDecl(Acceptable); 12925 R.resolveKind(); 12926 R.suppressDiagnostics(); 12927 12928 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 12929 } 12930 12931 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 12932 QualType ResultTy, 12933 ArrayRef<QualType> Args) { 12934 // Build an exception specification pointing back at this constructor. 12935 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 12936 12937 LangAS AS = getDefaultCXXMethodAddrSpace(); 12938 if (AS != LangAS::Default) { 12939 EPI.TypeQuals.addAddressSpace(AS); 12940 } 12941 12942 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 12943 SpecialMem->setType(QT); 12944 } 12945 12946 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 12947 CXXRecordDecl *ClassDecl) { 12948 // C++ [class.ctor]p5: 12949 // A default constructor for a class X is a constructor of class X 12950 // that can be called without an argument. If there is no 12951 // user-declared constructor for class X, a default constructor is 12952 // implicitly declared. An implicitly-declared default constructor 12953 // is an inline public member of its class. 12954 assert(ClassDecl->needsImplicitDefaultConstructor() && 12955 "Should not build implicit default constructor!"); 12956 12957 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 12958 if (DSM.isAlreadyBeingDeclared()) 12959 return nullptr; 12960 12961 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12962 CXXDefaultConstructor, 12963 false); 12964 12965 // Create the actual constructor declaration. 12966 CanQualType ClassType 12967 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 12968 SourceLocation ClassLoc = ClassDecl->getLocation(); 12969 DeclarationName Name 12970 = Context.DeclarationNames.getCXXConstructorName(ClassType); 12971 DeclarationNameInfo NameInfo(Name, ClassLoc); 12972 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 12973 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 12974 /*TInfo=*/nullptr, ExplicitSpecifier(), 12975 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12976 Constexpr ? ConstexprSpecKind::Constexpr 12977 : ConstexprSpecKind::Unspecified); 12978 DefaultCon->setAccess(AS_public); 12979 DefaultCon->setDefaulted(); 12980 12981 if (getLangOpts().CUDA) { 12982 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 12983 DefaultCon, 12984 /* ConstRHS */ false, 12985 /* Diagnose */ false); 12986 } 12987 12988 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 12989 12990 // We don't need to use SpecialMemberIsTrivial here; triviality for default 12991 // constructors is easy to compute. 12992 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 12993 12994 // Note that we have declared this constructor. 12995 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 12996 12997 Scope *S = getScopeForContext(ClassDecl); 12998 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 12999 13000 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 13001 SetDeclDeleted(DefaultCon, ClassLoc); 13002 13003 if (S) 13004 PushOnScopeChains(DefaultCon, S, false); 13005 ClassDecl->addDecl(DefaultCon); 13006 13007 return DefaultCon; 13008 } 13009 13010 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 13011 CXXConstructorDecl *Constructor) { 13012 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 13013 !Constructor->doesThisDeclarationHaveABody() && 13014 !Constructor->isDeleted()) && 13015 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 13016 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13017 return; 13018 13019 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13020 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 13021 13022 SynthesizedFunctionScope Scope(*this, Constructor); 13023 13024 // The exception specification is needed because we are defining the 13025 // function. 13026 ResolveExceptionSpec(CurrentLocation, 13027 Constructor->getType()->castAs<FunctionProtoType>()); 13028 MarkVTableUsed(CurrentLocation, ClassDecl); 13029 13030 // Add a context note for diagnostics produced after this point. 13031 Scope.addContextNote(CurrentLocation); 13032 13033 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 13034 Constructor->setInvalidDecl(); 13035 return; 13036 } 13037 13038 SourceLocation Loc = Constructor->getEndLoc().isValid() 13039 ? Constructor->getEndLoc() 13040 : Constructor->getLocation(); 13041 Constructor->setBody(new (Context) CompoundStmt(Loc)); 13042 Constructor->markUsed(Context); 13043 13044 if (ASTMutationListener *L = getASTMutationListener()) { 13045 L->CompletedImplicitDefinition(Constructor); 13046 } 13047 13048 DiagnoseUninitializedFields(*this, Constructor); 13049 } 13050 13051 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 13052 // Perform any delayed checks on exception specifications. 13053 CheckDelayedMemberExceptionSpecs(); 13054 } 13055 13056 /// Find or create the fake constructor we synthesize to model constructing an 13057 /// object of a derived class via a constructor of a base class. 13058 CXXConstructorDecl * 13059 Sema::findInheritingConstructor(SourceLocation Loc, 13060 CXXConstructorDecl *BaseCtor, 13061 ConstructorUsingShadowDecl *Shadow) { 13062 CXXRecordDecl *Derived = Shadow->getParent(); 13063 SourceLocation UsingLoc = Shadow->getLocation(); 13064 13065 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 13066 // For now we use the name of the base class constructor as a member of the 13067 // derived class to indicate a (fake) inherited constructor name. 13068 DeclarationName Name = BaseCtor->getDeclName(); 13069 13070 // Check to see if we already have a fake constructor for this inherited 13071 // constructor call. 13072 for (NamedDecl *Ctor : Derived->lookup(Name)) 13073 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 13074 ->getInheritedConstructor() 13075 .getConstructor(), 13076 BaseCtor)) 13077 return cast<CXXConstructorDecl>(Ctor); 13078 13079 DeclarationNameInfo NameInfo(Name, UsingLoc); 13080 TypeSourceInfo *TInfo = 13081 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 13082 FunctionProtoTypeLoc ProtoLoc = 13083 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 13084 13085 // Check the inherited constructor is valid and find the list of base classes 13086 // from which it was inherited. 13087 InheritedConstructorInfo ICI(*this, Loc, Shadow); 13088 13089 bool Constexpr = 13090 BaseCtor->isConstexpr() && 13091 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 13092 false, BaseCtor, &ICI); 13093 13094 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 13095 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 13096 BaseCtor->getExplicitSpecifier(), /*isInline=*/true, 13097 /*isImplicitlyDeclared=*/true, 13098 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified, 13099 InheritedConstructor(Shadow, BaseCtor), 13100 BaseCtor->getTrailingRequiresClause()); 13101 if (Shadow->isInvalidDecl()) 13102 DerivedCtor->setInvalidDecl(); 13103 13104 // Build an unevaluated exception specification for this fake constructor. 13105 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 13106 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13107 EPI.ExceptionSpec.Type = EST_Unevaluated; 13108 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 13109 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 13110 FPT->getParamTypes(), EPI)); 13111 13112 // Build the parameter declarations. 13113 SmallVector<ParmVarDecl *, 16> ParamDecls; 13114 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 13115 TypeSourceInfo *TInfo = 13116 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 13117 ParmVarDecl *PD = ParmVarDecl::Create( 13118 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 13119 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 13120 PD->setScopeInfo(0, I); 13121 PD->setImplicit(); 13122 // Ensure attributes are propagated onto parameters (this matters for 13123 // format, pass_object_size, ...). 13124 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 13125 ParamDecls.push_back(PD); 13126 ProtoLoc.setParam(I, PD); 13127 } 13128 13129 // Set up the new constructor. 13130 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 13131 DerivedCtor->setAccess(BaseCtor->getAccess()); 13132 DerivedCtor->setParams(ParamDecls); 13133 Derived->addDecl(DerivedCtor); 13134 13135 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 13136 SetDeclDeleted(DerivedCtor, UsingLoc); 13137 13138 return DerivedCtor; 13139 } 13140 13141 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 13142 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 13143 Ctor->getInheritedConstructor().getShadowDecl()); 13144 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 13145 /*Diagnose*/true); 13146 } 13147 13148 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 13149 CXXConstructorDecl *Constructor) { 13150 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13151 assert(Constructor->getInheritedConstructor() && 13152 !Constructor->doesThisDeclarationHaveABody() && 13153 !Constructor->isDeleted()); 13154 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13155 return; 13156 13157 // Initializations are performed "as if by a defaulted default constructor", 13158 // so enter the appropriate scope. 13159 SynthesizedFunctionScope Scope(*this, Constructor); 13160 13161 // The exception specification is needed because we are defining the 13162 // function. 13163 ResolveExceptionSpec(CurrentLocation, 13164 Constructor->getType()->castAs<FunctionProtoType>()); 13165 MarkVTableUsed(CurrentLocation, ClassDecl); 13166 13167 // Add a context note for diagnostics produced after this point. 13168 Scope.addContextNote(CurrentLocation); 13169 13170 ConstructorUsingShadowDecl *Shadow = 13171 Constructor->getInheritedConstructor().getShadowDecl(); 13172 CXXConstructorDecl *InheritedCtor = 13173 Constructor->getInheritedConstructor().getConstructor(); 13174 13175 // [class.inhctor.init]p1: 13176 // initialization proceeds as if a defaulted default constructor is used to 13177 // initialize the D object and each base class subobject from which the 13178 // constructor was inherited 13179 13180 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 13181 CXXRecordDecl *RD = Shadow->getParent(); 13182 SourceLocation InitLoc = Shadow->getLocation(); 13183 13184 // Build explicit initializers for all base classes from which the 13185 // constructor was inherited. 13186 SmallVector<CXXCtorInitializer*, 8> Inits; 13187 for (bool VBase : {false, true}) { 13188 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 13189 if (B.isVirtual() != VBase) 13190 continue; 13191 13192 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 13193 if (!BaseRD) 13194 continue; 13195 13196 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 13197 if (!BaseCtor.first) 13198 continue; 13199 13200 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 13201 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 13202 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 13203 13204 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 13205 Inits.push_back(new (Context) CXXCtorInitializer( 13206 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 13207 SourceLocation())); 13208 } 13209 } 13210 13211 // We now proceed as if for a defaulted default constructor, with the relevant 13212 // initializers replaced. 13213 13214 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 13215 Constructor->setInvalidDecl(); 13216 return; 13217 } 13218 13219 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 13220 Constructor->markUsed(Context); 13221 13222 if (ASTMutationListener *L = getASTMutationListener()) { 13223 L->CompletedImplicitDefinition(Constructor); 13224 } 13225 13226 DiagnoseUninitializedFields(*this, Constructor); 13227 } 13228 13229 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 13230 // C++ [class.dtor]p2: 13231 // If a class has no user-declared destructor, a destructor is 13232 // declared implicitly. An implicitly-declared destructor is an 13233 // inline public member of its class. 13234 assert(ClassDecl->needsImplicitDestructor()); 13235 13236 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 13237 if (DSM.isAlreadyBeingDeclared()) 13238 return nullptr; 13239 13240 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13241 CXXDestructor, 13242 false); 13243 13244 // Create the actual destructor declaration. 13245 CanQualType ClassType 13246 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13247 SourceLocation ClassLoc = ClassDecl->getLocation(); 13248 DeclarationName Name 13249 = Context.DeclarationNames.getCXXDestructorName(ClassType); 13250 DeclarationNameInfo NameInfo(Name, ClassLoc); 13251 CXXDestructorDecl *Destructor = 13252 CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 13253 QualType(), nullptr, /*isInline=*/true, 13254 /*isImplicitlyDeclared=*/true, 13255 Constexpr ? ConstexprSpecKind::Constexpr 13256 : ConstexprSpecKind::Unspecified); 13257 Destructor->setAccess(AS_public); 13258 Destructor->setDefaulted(); 13259 13260 if (getLangOpts().CUDA) { 13261 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 13262 Destructor, 13263 /* ConstRHS */ false, 13264 /* Diagnose */ false); 13265 } 13266 13267 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 13268 13269 // We don't need to use SpecialMemberIsTrivial here; triviality for 13270 // destructors is easy to compute. 13271 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 13272 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 13273 ClassDecl->hasTrivialDestructorForCall()); 13274 13275 // Note that we have declared this destructor. 13276 ++getASTContext().NumImplicitDestructorsDeclared; 13277 13278 Scope *S = getScopeForContext(ClassDecl); 13279 CheckImplicitSpecialMemberDeclaration(S, Destructor); 13280 13281 // We can't check whether an implicit destructor is deleted before we complete 13282 // the definition of the class, because its validity depends on the alignment 13283 // of the class. We'll check this from ActOnFields once the class is complete. 13284 if (ClassDecl->isCompleteDefinition() && 13285 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 13286 SetDeclDeleted(Destructor, ClassLoc); 13287 13288 // Introduce this destructor into its scope. 13289 if (S) 13290 PushOnScopeChains(Destructor, S, false); 13291 ClassDecl->addDecl(Destructor); 13292 13293 return Destructor; 13294 } 13295 13296 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 13297 CXXDestructorDecl *Destructor) { 13298 assert((Destructor->isDefaulted() && 13299 !Destructor->doesThisDeclarationHaveABody() && 13300 !Destructor->isDeleted()) && 13301 "DefineImplicitDestructor - call it for implicit default dtor"); 13302 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 13303 return; 13304 13305 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13306 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 13307 13308 SynthesizedFunctionScope Scope(*this, Destructor); 13309 13310 // The exception specification is needed because we are defining the 13311 // function. 13312 ResolveExceptionSpec(CurrentLocation, 13313 Destructor->getType()->castAs<FunctionProtoType>()); 13314 MarkVTableUsed(CurrentLocation, ClassDecl); 13315 13316 // Add a context note for diagnostics produced after this point. 13317 Scope.addContextNote(CurrentLocation); 13318 13319 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13320 Destructor->getParent()); 13321 13322 if (CheckDestructor(Destructor)) { 13323 Destructor->setInvalidDecl(); 13324 return; 13325 } 13326 13327 SourceLocation Loc = Destructor->getEndLoc().isValid() 13328 ? Destructor->getEndLoc() 13329 : Destructor->getLocation(); 13330 Destructor->setBody(new (Context) CompoundStmt(Loc)); 13331 Destructor->markUsed(Context); 13332 13333 if (ASTMutationListener *L = getASTMutationListener()) { 13334 L->CompletedImplicitDefinition(Destructor); 13335 } 13336 } 13337 13338 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 13339 CXXDestructorDecl *Destructor) { 13340 if (Destructor->isInvalidDecl()) 13341 return; 13342 13343 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13344 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() && 13345 "implicit complete dtors unneeded outside MS ABI"); 13346 assert(ClassDecl->getNumVBases() > 0 && 13347 "complete dtor only exists for classes with vbases"); 13348 13349 SynthesizedFunctionScope Scope(*this, Destructor); 13350 13351 // Add a context note for diagnostics produced after this point. 13352 Scope.addContextNote(CurrentLocation); 13353 13354 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl); 13355 } 13356 13357 /// Perform any semantic analysis which needs to be delayed until all 13358 /// pending class member declarations have been parsed. 13359 void Sema::ActOnFinishCXXMemberDecls() { 13360 // If the context is an invalid C++ class, just suppress these checks. 13361 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 13362 if (Record->isInvalidDecl()) { 13363 DelayedOverridingExceptionSpecChecks.clear(); 13364 DelayedEquivalentExceptionSpecChecks.clear(); 13365 return; 13366 } 13367 checkForMultipleExportedDefaultConstructors(*this, Record); 13368 } 13369 } 13370 13371 void Sema::ActOnFinishCXXNonNestedClass() { 13372 referenceDLLExportedClassMethods(); 13373 13374 if (!DelayedDllExportMemberFunctions.empty()) { 13375 SmallVector<CXXMethodDecl*, 4> WorkList; 13376 std::swap(DelayedDllExportMemberFunctions, WorkList); 13377 for (CXXMethodDecl *M : WorkList) { 13378 DefineDefaultedFunction(*this, M, M->getLocation()); 13379 13380 // Pass the method to the consumer to get emitted. This is not necessary 13381 // for explicit instantiation definitions, as they will get emitted 13382 // anyway. 13383 if (M->getParent()->getTemplateSpecializationKind() != 13384 TSK_ExplicitInstantiationDefinition) 13385 ActOnFinishInlineFunctionDef(M); 13386 } 13387 } 13388 } 13389 13390 void Sema::referenceDLLExportedClassMethods() { 13391 if (!DelayedDllExportClasses.empty()) { 13392 // Calling ReferenceDllExportedMembers might cause the current function to 13393 // be called again, so use a local copy of DelayedDllExportClasses. 13394 SmallVector<CXXRecordDecl *, 4> WorkList; 13395 std::swap(DelayedDllExportClasses, WorkList); 13396 for (CXXRecordDecl *Class : WorkList) 13397 ReferenceDllExportedMembers(*this, Class); 13398 } 13399 } 13400 13401 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 13402 assert(getLangOpts().CPlusPlus11 && 13403 "adjusting dtor exception specs was introduced in c++11"); 13404 13405 if (Destructor->isDependentContext()) 13406 return; 13407 13408 // C++11 [class.dtor]p3: 13409 // A declaration of a destructor that does not have an exception- 13410 // specification is implicitly considered to have the same exception- 13411 // specification as an implicit declaration. 13412 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); 13413 if (DtorType->hasExceptionSpec()) 13414 return; 13415 13416 // Replace the destructor's type, building off the existing one. Fortunately, 13417 // the only thing of interest in the destructor type is its extended info. 13418 // The return and arguments are fixed. 13419 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 13420 EPI.ExceptionSpec.Type = EST_Unevaluated; 13421 EPI.ExceptionSpec.SourceDecl = Destructor; 13422 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 13423 13424 // FIXME: If the destructor has a body that could throw, and the newly created 13425 // spec doesn't allow exceptions, we should emit a warning, because this 13426 // change in behavior can break conforming C++03 programs at runtime. 13427 // However, we don't have a body or an exception specification yet, so it 13428 // needs to be done somewhere else. 13429 } 13430 13431 namespace { 13432 /// An abstract base class for all helper classes used in building the 13433 // copy/move operators. These classes serve as factory functions and help us 13434 // avoid using the same Expr* in the AST twice. 13435 class ExprBuilder { 13436 ExprBuilder(const ExprBuilder&) = delete; 13437 ExprBuilder &operator=(const ExprBuilder&) = delete; 13438 13439 protected: 13440 static Expr *assertNotNull(Expr *E) { 13441 assert(E && "Expression construction must not fail."); 13442 return E; 13443 } 13444 13445 public: 13446 ExprBuilder() {} 13447 virtual ~ExprBuilder() {} 13448 13449 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 13450 }; 13451 13452 class RefBuilder: public ExprBuilder { 13453 VarDecl *Var; 13454 QualType VarType; 13455 13456 public: 13457 Expr *build(Sema &S, SourceLocation Loc) const override { 13458 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 13459 } 13460 13461 RefBuilder(VarDecl *Var, QualType VarType) 13462 : Var(Var), VarType(VarType) {} 13463 }; 13464 13465 class ThisBuilder: public ExprBuilder { 13466 public: 13467 Expr *build(Sema &S, SourceLocation Loc) const override { 13468 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 13469 } 13470 }; 13471 13472 class CastBuilder: public ExprBuilder { 13473 const ExprBuilder &Builder; 13474 QualType Type; 13475 ExprValueKind Kind; 13476 const CXXCastPath &Path; 13477 13478 public: 13479 Expr *build(Sema &S, SourceLocation Loc) const override { 13480 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 13481 CK_UncheckedDerivedToBase, Kind, 13482 &Path).get()); 13483 } 13484 13485 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 13486 const CXXCastPath &Path) 13487 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 13488 }; 13489 13490 class DerefBuilder: public ExprBuilder { 13491 const ExprBuilder &Builder; 13492 13493 public: 13494 Expr *build(Sema &S, SourceLocation Loc) const override { 13495 return assertNotNull( 13496 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 13497 } 13498 13499 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13500 }; 13501 13502 class MemberBuilder: public ExprBuilder { 13503 const ExprBuilder &Builder; 13504 QualType Type; 13505 CXXScopeSpec SS; 13506 bool IsArrow; 13507 LookupResult &MemberLookup; 13508 13509 public: 13510 Expr *build(Sema &S, SourceLocation Loc) const override { 13511 return assertNotNull(S.BuildMemberReferenceExpr( 13512 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 13513 nullptr, MemberLookup, nullptr, nullptr).get()); 13514 } 13515 13516 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 13517 LookupResult &MemberLookup) 13518 : Builder(Builder), Type(Type), IsArrow(IsArrow), 13519 MemberLookup(MemberLookup) {} 13520 }; 13521 13522 class MoveCastBuilder: public ExprBuilder { 13523 const ExprBuilder &Builder; 13524 13525 public: 13526 Expr *build(Sema &S, SourceLocation Loc) const override { 13527 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 13528 } 13529 13530 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13531 }; 13532 13533 class LvalueConvBuilder: public ExprBuilder { 13534 const ExprBuilder &Builder; 13535 13536 public: 13537 Expr *build(Sema &S, SourceLocation Loc) const override { 13538 return assertNotNull( 13539 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 13540 } 13541 13542 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13543 }; 13544 13545 class SubscriptBuilder: public ExprBuilder { 13546 const ExprBuilder &Base; 13547 const ExprBuilder &Index; 13548 13549 public: 13550 Expr *build(Sema &S, SourceLocation Loc) const override { 13551 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 13552 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 13553 } 13554 13555 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 13556 : Base(Base), Index(Index) {} 13557 }; 13558 13559 } // end anonymous namespace 13560 13561 /// When generating a defaulted copy or move assignment operator, if a field 13562 /// should be copied with __builtin_memcpy rather than via explicit assignments, 13563 /// do so. This optimization only applies for arrays of scalars, and for arrays 13564 /// of class type where the selected copy/move-assignment operator is trivial. 13565 static StmtResult 13566 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 13567 const ExprBuilder &ToB, const ExprBuilder &FromB) { 13568 // Compute the size of the memory buffer to be copied. 13569 QualType SizeType = S.Context.getSizeType(); 13570 llvm::APInt Size(S.Context.getTypeSize(SizeType), 13571 S.Context.getTypeSizeInChars(T).getQuantity()); 13572 13573 // Take the address of the field references for "from" and "to". We 13574 // directly construct UnaryOperators here because semantic analysis 13575 // does not permit us to take the address of an xvalue. 13576 Expr *From = FromB.build(S, Loc); 13577 From = UnaryOperator::Create( 13578 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()), 13579 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13580 Expr *To = ToB.build(S, Loc); 13581 To = UnaryOperator::Create( 13582 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()), 13583 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13584 13585 const Type *E = T->getBaseElementTypeUnsafe(); 13586 bool NeedsCollectableMemCpy = 13587 E->isRecordType() && 13588 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 13589 13590 // Create a reference to the __builtin_objc_memmove_collectable function 13591 StringRef MemCpyName = NeedsCollectableMemCpy ? 13592 "__builtin_objc_memmove_collectable" : 13593 "__builtin_memcpy"; 13594 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 13595 Sema::LookupOrdinaryName); 13596 S.LookupName(R, S.TUScope, true); 13597 13598 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 13599 if (!MemCpy) 13600 // Something went horribly wrong earlier, and we will have complained 13601 // about it. 13602 return StmtError(); 13603 13604 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 13605 VK_RValue, Loc, nullptr); 13606 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 13607 13608 Expr *CallArgs[] = { 13609 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 13610 }; 13611 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 13612 Loc, CallArgs, Loc); 13613 13614 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 13615 return Call.getAs<Stmt>(); 13616 } 13617 13618 /// Builds a statement that copies/moves the given entity from \p From to 13619 /// \c To. 13620 /// 13621 /// This routine is used to copy/move the members of a class with an 13622 /// implicitly-declared copy/move assignment operator. When the entities being 13623 /// copied are arrays, this routine builds for loops to copy them. 13624 /// 13625 /// \param S The Sema object used for type-checking. 13626 /// 13627 /// \param Loc The location where the implicit copy/move is being generated. 13628 /// 13629 /// \param T The type of the expressions being copied/moved. Both expressions 13630 /// must have this type. 13631 /// 13632 /// \param To The expression we are copying/moving to. 13633 /// 13634 /// \param From The expression we are copying/moving from. 13635 /// 13636 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 13637 /// Otherwise, it's a non-static member subobject. 13638 /// 13639 /// \param Copying Whether we're copying or moving. 13640 /// 13641 /// \param Depth Internal parameter recording the depth of the recursion. 13642 /// 13643 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 13644 /// if a memcpy should be used instead. 13645 static StmtResult 13646 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 13647 const ExprBuilder &To, const ExprBuilder &From, 13648 bool CopyingBaseSubobject, bool Copying, 13649 unsigned Depth = 0) { 13650 // C++11 [class.copy]p28: 13651 // Each subobject is assigned in the manner appropriate to its type: 13652 // 13653 // - if the subobject is of class type, as if by a call to operator= with 13654 // the subobject as the object expression and the corresponding 13655 // subobject of x as a single function argument (as if by explicit 13656 // qualification; that is, ignoring any possible virtual overriding 13657 // functions in more derived classes); 13658 // 13659 // C++03 [class.copy]p13: 13660 // - if the subobject is of class type, the copy assignment operator for 13661 // the class is used (as if by explicit qualification; that is, 13662 // ignoring any possible virtual overriding functions in more derived 13663 // classes); 13664 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 13665 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 13666 13667 // Look for operator=. 13668 DeclarationName Name 13669 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13670 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 13671 S.LookupQualifiedName(OpLookup, ClassDecl, false); 13672 13673 // Prior to C++11, filter out any result that isn't a copy/move-assignment 13674 // operator. 13675 if (!S.getLangOpts().CPlusPlus11) { 13676 LookupResult::Filter F = OpLookup.makeFilter(); 13677 while (F.hasNext()) { 13678 NamedDecl *D = F.next(); 13679 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 13680 if (Method->isCopyAssignmentOperator() || 13681 (!Copying && Method->isMoveAssignmentOperator())) 13682 continue; 13683 13684 F.erase(); 13685 } 13686 F.done(); 13687 } 13688 13689 // Suppress the protected check (C++ [class.protected]) for each of the 13690 // assignment operators we found. This strange dance is required when 13691 // we're assigning via a base classes's copy-assignment operator. To 13692 // ensure that we're getting the right base class subobject (without 13693 // ambiguities), we need to cast "this" to that subobject type; to 13694 // ensure that we don't go through the virtual call mechanism, we need 13695 // to qualify the operator= name with the base class (see below). However, 13696 // this means that if the base class has a protected copy assignment 13697 // operator, the protected member access check will fail. So, we 13698 // rewrite "protected" access to "public" access in this case, since we 13699 // know by construction that we're calling from a derived class. 13700 if (CopyingBaseSubobject) { 13701 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 13702 L != LEnd; ++L) { 13703 if (L.getAccess() == AS_protected) 13704 L.setAccess(AS_public); 13705 } 13706 } 13707 13708 // Create the nested-name-specifier that will be used to qualify the 13709 // reference to operator=; this is required to suppress the virtual 13710 // call mechanism. 13711 CXXScopeSpec SS; 13712 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 13713 SS.MakeTrivial(S.Context, 13714 NestedNameSpecifier::Create(S.Context, nullptr, false, 13715 CanonicalT), 13716 Loc); 13717 13718 // Create the reference to operator=. 13719 ExprResult OpEqualRef 13720 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 13721 SS, /*TemplateKWLoc=*/SourceLocation(), 13722 /*FirstQualifierInScope=*/nullptr, 13723 OpLookup, 13724 /*TemplateArgs=*/nullptr, /*S*/nullptr, 13725 /*SuppressQualifierCheck=*/true); 13726 if (OpEqualRef.isInvalid()) 13727 return StmtError(); 13728 13729 // Build the call to the assignment operator. 13730 13731 Expr *FromInst = From.build(S, Loc); 13732 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 13733 OpEqualRef.getAs<Expr>(), 13734 Loc, FromInst, Loc); 13735 if (Call.isInvalid()) 13736 return StmtError(); 13737 13738 // If we built a call to a trivial 'operator=' while copying an array, 13739 // bail out. We'll replace the whole shebang with a memcpy. 13740 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 13741 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 13742 return StmtResult((Stmt*)nullptr); 13743 13744 // Convert to an expression-statement, and clean up any produced 13745 // temporaries. 13746 return S.ActOnExprStmt(Call); 13747 } 13748 13749 // - if the subobject is of scalar type, the built-in assignment 13750 // operator is used. 13751 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 13752 if (!ArrayTy) { 13753 ExprResult Assignment = S.CreateBuiltinBinOp( 13754 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 13755 if (Assignment.isInvalid()) 13756 return StmtError(); 13757 return S.ActOnExprStmt(Assignment); 13758 } 13759 13760 // - if the subobject is an array, each element is assigned, in the 13761 // manner appropriate to the element type; 13762 13763 // Construct a loop over the array bounds, e.g., 13764 // 13765 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 13766 // 13767 // that will copy each of the array elements. 13768 QualType SizeType = S.Context.getSizeType(); 13769 13770 // Create the iteration variable. 13771 IdentifierInfo *IterationVarName = nullptr; 13772 { 13773 SmallString<8> Str; 13774 llvm::raw_svector_ostream OS(Str); 13775 OS << "__i" << Depth; 13776 IterationVarName = &S.Context.Idents.get(OS.str()); 13777 } 13778 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 13779 IterationVarName, SizeType, 13780 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 13781 SC_None); 13782 13783 // Initialize the iteration variable to zero. 13784 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 13785 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 13786 13787 // Creates a reference to the iteration variable. 13788 RefBuilder IterationVarRef(IterationVar, SizeType); 13789 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 13790 13791 // Create the DeclStmt that holds the iteration variable. 13792 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 13793 13794 // Subscript the "from" and "to" expressions with the iteration variable. 13795 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 13796 MoveCastBuilder FromIndexMove(FromIndexCopy); 13797 const ExprBuilder *FromIndex; 13798 if (Copying) 13799 FromIndex = &FromIndexCopy; 13800 else 13801 FromIndex = &FromIndexMove; 13802 13803 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 13804 13805 // Build the copy/move for an individual element of the array. 13806 StmtResult Copy = 13807 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 13808 ToIndex, *FromIndex, CopyingBaseSubobject, 13809 Copying, Depth + 1); 13810 // Bail out if copying fails or if we determined that we should use memcpy. 13811 if (Copy.isInvalid() || !Copy.get()) 13812 return Copy; 13813 13814 // Create the comparison against the array bound. 13815 llvm::APInt Upper 13816 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 13817 Expr *Comparison = BinaryOperator::Create( 13818 S.Context, IterationVarRefRVal.build(S, Loc), 13819 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE, 13820 S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides()); 13821 13822 // Create the pre-increment of the iteration variable. We can determine 13823 // whether the increment will overflow based on the value of the array 13824 // bound. 13825 Expr *Increment = UnaryOperator::Create( 13826 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue, 13827 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides()); 13828 13829 // Construct the loop that copies all elements of this array. 13830 return S.ActOnForStmt( 13831 Loc, Loc, InitStmt, 13832 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 13833 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 13834 } 13835 13836 static StmtResult 13837 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 13838 const ExprBuilder &To, const ExprBuilder &From, 13839 bool CopyingBaseSubobject, bool Copying) { 13840 // Maybe we should use a memcpy? 13841 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 13842 T.isTriviallyCopyableType(S.Context)) 13843 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13844 13845 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 13846 CopyingBaseSubobject, 13847 Copying, 0)); 13848 13849 // If we ended up picking a trivial assignment operator for an array of a 13850 // non-trivially-copyable class type, just emit a memcpy. 13851 if (!Result.isInvalid() && !Result.get()) 13852 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13853 13854 return Result; 13855 } 13856 13857 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 13858 // Note: The following rules are largely analoguous to the copy 13859 // constructor rules. Note that virtual bases are not taken into account 13860 // for determining the argument type of the operator. Note also that 13861 // operators taking an object instead of a reference are allowed. 13862 assert(ClassDecl->needsImplicitCopyAssignment()); 13863 13864 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 13865 if (DSM.isAlreadyBeingDeclared()) 13866 return nullptr; 13867 13868 QualType ArgType = Context.getTypeDeclType(ClassDecl); 13869 LangAS AS = getDefaultCXXMethodAddrSpace(); 13870 if (AS != LangAS::Default) 13871 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 13872 QualType RetType = Context.getLValueReferenceType(ArgType); 13873 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 13874 if (Const) 13875 ArgType = ArgType.withConst(); 13876 13877 ArgType = Context.getLValueReferenceType(ArgType); 13878 13879 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13880 CXXCopyAssignment, 13881 Const); 13882 13883 // An implicitly-declared copy assignment operator is an inline public 13884 // member of its class. 13885 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13886 SourceLocation ClassLoc = ClassDecl->getLocation(); 13887 DeclarationNameInfo NameInfo(Name, ClassLoc); 13888 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 13889 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 13890 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 13891 /*isInline=*/true, 13892 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 13893 SourceLocation()); 13894 CopyAssignment->setAccess(AS_public); 13895 CopyAssignment->setDefaulted(); 13896 CopyAssignment->setImplicit(); 13897 13898 if (getLangOpts().CUDA) { 13899 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 13900 CopyAssignment, 13901 /* ConstRHS */ Const, 13902 /* Diagnose */ false); 13903 } 13904 13905 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 13906 13907 // Add the parameter to the operator. 13908 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 13909 ClassLoc, ClassLoc, 13910 /*Id=*/nullptr, ArgType, 13911 /*TInfo=*/nullptr, SC_None, 13912 nullptr); 13913 CopyAssignment->setParams(FromParam); 13914 13915 CopyAssignment->setTrivial( 13916 ClassDecl->needsOverloadResolutionForCopyAssignment() 13917 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 13918 : ClassDecl->hasTrivialCopyAssignment()); 13919 13920 // Note that we have added this copy-assignment operator. 13921 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 13922 13923 Scope *S = getScopeForContext(ClassDecl); 13924 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 13925 13926 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) { 13927 ClassDecl->setImplicitCopyAssignmentIsDeleted(); 13928 SetDeclDeleted(CopyAssignment, ClassLoc); 13929 } 13930 13931 if (S) 13932 PushOnScopeChains(CopyAssignment, S, false); 13933 ClassDecl->addDecl(CopyAssignment); 13934 13935 return CopyAssignment; 13936 } 13937 13938 /// Diagnose an implicit copy operation for a class which is odr-used, but 13939 /// which is deprecated because the class has a user-declared copy constructor, 13940 /// copy assignment operator, or destructor. 13941 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 13942 assert(CopyOp->isImplicit()); 13943 13944 CXXRecordDecl *RD = CopyOp->getParent(); 13945 CXXMethodDecl *UserDeclaredOperation = nullptr; 13946 13947 // In Microsoft mode, assignment operations don't affect constructors and 13948 // vice versa. 13949 if (RD->hasUserDeclaredDestructor()) { 13950 UserDeclaredOperation = RD->getDestructor(); 13951 } else if (!isa<CXXConstructorDecl>(CopyOp) && 13952 RD->hasUserDeclaredCopyConstructor() && 13953 !S.getLangOpts().MSVCCompat) { 13954 // Find any user-declared copy constructor. 13955 for (auto *I : RD->ctors()) { 13956 if (I->isCopyConstructor()) { 13957 UserDeclaredOperation = I; 13958 break; 13959 } 13960 } 13961 assert(UserDeclaredOperation); 13962 } else if (isa<CXXConstructorDecl>(CopyOp) && 13963 RD->hasUserDeclaredCopyAssignment() && 13964 !S.getLangOpts().MSVCCompat) { 13965 // Find any user-declared move assignment operator. 13966 for (auto *I : RD->methods()) { 13967 if (I->isCopyAssignmentOperator()) { 13968 UserDeclaredOperation = I; 13969 break; 13970 } 13971 } 13972 assert(UserDeclaredOperation); 13973 } 13974 13975 if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) { 13976 S.Diag(UserDeclaredOperation->getLocation(), 13977 isa<CXXDestructorDecl>(UserDeclaredOperation) 13978 ? diag::warn_deprecated_copy_dtor_operation 13979 : diag::warn_deprecated_copy_operation) 13980 << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp); 13981 } 13982 } 13983 13984 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 13985 CXXMethodDecl *CopyAssignOperator) { 13986 assert((CopyAssignOperator->isDefaulted() && 13987 CopyAssignOperator->isOverloadedOperator() && 13988 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 13989 !CopyAssignOperator->doesThisDeclarationHaveABody() && 13990 !CopyAssignOperator->isDeleted()) && 13991 "DefineImplicitCopyAssignment called for wrong function"); 13992 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 13993 return; 13994 13995 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 13996 if (ClassDecl->isInvalidDecl()) { 13997 CopyAssignOperator->setInvalidDecl(); 13998 return; 13999 } 14000 14001 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 14002 14003 // The exception specification is needed because we are defining the 14004 // function. 14005 ResolveExceptionSpec(CurrentLocation, 14006 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 14007 14008 // Add a context note for diagnostics produced after this point. 14009 Scope.addContextNote(CurrentLocation); 14010 14011 // C++11 [class.copy]p18: 14012 // The [definition of an implicitly declared copy assignment operator] is 14013 // deprecated if the class has a user-declared copy constructor or a 14014 // user-declared destructor. 14015 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 14016 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 14017 14018 // C++0x [class.copy]p30: 14019 // The implicitly-defined or explicitly-defaulted copy assignment operator 14020 // for a non-union class X performs memberwise copy assignment of its 14021 // subobjects. The direct base classes of X are assigned first, in the 14022 // order of their declaration in the base-specifier-list, and then the 14023 // immediate non-static data members of X are assigned, in the order in 14024 // which they were declared in the class definition. 14025 14026 // The statements that form the synthesized function body. 14027 SmallVector<Stmt*, 8> Statements; 14028 14029 // The parameter for the "other" object, which we are copying from. 14030 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 14031 Qualifiers OtherQuals = Other->getType().getQualifiers(); 14032 QualType OtherRefType = Other->getType(); 14033 if (const LValueReferenceType *OtherRef 14034 = OtherRefType->getAs<LValueReferenceType>()) { 14035 OtherRefType = OtherRef->getPointeeType(); 14036 OtherQuals = OtherRefType.getQualifiers(); 14037 } 14038 14039 // Our location for everything implicitly-generated. 14040 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 14041 ? CopyAssignOperator->getEndLoc() 14042 : CopyAssignOperator->getLocation(); 14043 14044 // Builds a DeclRefExpr for the "other" object. 14045 RefBuilder OtherRef(Other, OtherRefType); 14046 14047 // Builds the "this" pointer. 14048 ThisBuilder This; 14049 14050 // Assign base classes. 14051 bool Invalid = false; 14052 for (auto &Base : ClassDecl->bases()) { 14053 // Form the assignment: 14054 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 14055 QualType BaseType = Base.getType().getUnqualifiedType(); 14056 if (!BaseType->isRecordType()) { 14057 Invalid = true; 14058 continue; 14059 } 14060 14061 CXXCastPath BasePath; 14062 BasePath.push_back(&Base); 14063 14064 // Construct the "from" expression, which is an implicit cast to the 14065 // appropriately-qualified base type. 14066 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 14067 VK_LValue, BasePath); 14068 14069 // Dereference "this". 14070 DerefBuilder DerefThis(This); 14071 CastBuilder To(DerefThis, 14072 Context.getQualifiedType( 14073 BaseType, CopyAssignOperator->getMethodQualifiers()), 14074 VK_LValue, BasePath); 14075 14076 // Build the copy. 14077 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 14078 To, From, 14079 /*CopyingBaseSubobject=*/true, 14080 /*Copying=*/true); 14081 if (Copy.isInvalid()) { 14082 CopyAssignOperator->setInvalidDecl(); 14083 return; 14084 } 14085 14086 // Success! Record the copy. 14087 Statements.push_back(Copy.getAs<Expr>()); 14088 } 14089 14090 // Assign non-static members. 14091 for (auto *Field : ClassDecl->fields()) { 14092 // FIXME: We should form some kind of AST representation for the implied 14093 // memcpy in a union copy operation. 14094 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14095 continue; 14096 14097 if (Field->isInvalidDecl()) { 14098 Invalid = true; 14099 continue; 14100 } 14101 14102 // Check for members of reference type; we can't copy those. 14103 if (Field->getType()->isReferenceType()) { 14104 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14105 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14106 Diag(Field->getLocation(), diag::note_declared_at); 14107 Invalid = true; 14108 continue; 14109 } 14110 14111 // Check for members of const-qualified, non-class type. 14112 QualType BaseType = Context.getBaseElementType(Field->getType()); 14113 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14114 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14115 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14116 Diag(Field->getLocation(), diag::note_declared_at); 14117 Invalid = true; 14118 continue; 14119 } 14120 14121 // Suppress assigning zero-width bitfields. 14122 if (Field->isZeroLengthBitField(Context)) 14123 continue; 14124 14125 QualType FieldType = Field->getType().getNonReferenceType(); 14126 if (FieldType->isIncompleteArrayType()) { 14127 assert(ClassDecl->hasFlexibleArrayMember() && 14128 "Incomplete array type is not valid"); 14129 continue; 14130 } 14131 14132 // Build references to the field in the object we're copying from and to. 14133 CXXScopeSpec SS; // Intentionally empty 14134 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14135 LookupMemberName); 14136 MemberLookup.addDecl(Field); 14137 MemberLookup.resolveKind(); 14138 14139 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 14140 14141 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 14142 14143 // Build the copy of this field. 14144 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 14145 To, From, 14146 /*CopyingBaseSubobject=*/false, 14147 /*Copying=*/true); 14148 if (Copy.isInvalid()) { 14149 CopyAssignOperator->setInvalidDecl(); 14150 return; 14151 } 14152 14153 // Success! Record the copy. 14154 Statements.push_back(Copy.getAs<Stmt>()); 14155 } 14156 14157 if (!Invalid) { 14158 // Add a "return *this;" 14159 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14160 14161 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14162 if (Return.isInvalid()) 14163 Invalid = true; 14164 else 14165 Statements.push_back(Return.getAs<Stmt>()); 14166 } 14167 14168 if (Invalid) { 14169 CopyAssignOperator->setInvalidDecl(); 14170 return; 14171 } 14172 14173 StmtResult Body; 14174 { 14175 CompoundScopeRAII CompoundScope(*this); 14176 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14177 /*isStmtExpr=*/false); 14178 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14179 } 14180 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 14181 CopyAssignOperator->markUsed(Context); 14182 14183 if (ASTMutationListener *L = getASTMutationListener()) { 14184 L->CompletedImplicitDefinition(CopyAssignOperator); 14185 } 14186 } 14187 14188 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 14189 assert(ClassDecl->needsImplicitMoveAssignment()); 14190 14191 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 14192 if (DSM.isAlreadyBeingDeclared()) 14193 return nullptr; 14194 14195 // Note: The following rules are largely analoguous to the move 14196 // constructor rules. 14197 14198 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14199 LangAS AS = getDefaultCXXMethodAddrSpace(); 14200 if (AS != LangAS::Default) 14201 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14202 QualType RetType = Context.getLValueReferenceType(ArgType); 14203 ArgType = Context.getRValueReferenceType(ArgType); 14204 14205 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14206 CXXMoveAssignment, 14207 false); 14208 14209 // An implicitly-declared move assignment operator is an inline public 14210 // member of its class. 14211 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14212 SourceLocation ClassLoc = ClassDecl->getLocation(); 14213 DeclarationNameInfo NameInfo(Name, ClassLoc); 14214 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 14215 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14216 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14217 /*isInline=*/true, 14218 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14219 SourceLocation()); 14220 MoveAssignment->setAccess(AS_public); 14221 MoveAssignment->setDefaulted(); 14222 MoveAssignment->setImplicit(); 14223 14224 if (getLangOpts().CUDA) { 14225 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 14226 MoveAssignment, 14227 /* ConstRHS */ false, 14228 /* Diagnose */ false); 14229 } 14230 14231 // Build an exception specification pointing back at this member. 14232 FunctionProtoType::ExtProtoInfo EPI = 14233 getImplicitMethodEPI(*this, MoveAssignment); 14234 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 14235 14236 // Add the parameter to the operator. 14237 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 14238 ClassLoc, ClassLoc, 14239 /*Id=*/nullptr, ArgType, 14240 /*TInfo=*/nullptr, SC_None, 14241 nullptr); 14242 MoveAssignment->setParams(FromParam); 14243 14244 MoveAssignment->setTrivial( 14245 ClassDecl->needsOverloadResolutionForMoveAssignment() 14246 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 14247 : ClassDecl->hasTrivialMoveAssignment()); 14248 14249 // Note that we have added this copy-assignment operator. 14250 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 14251 14252 Scope *S = getScopeForContext(ClassDecl); 14253 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 14254 14255 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 14256 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 14257 SetDeclDeleted(MoveAssignment, ClassLoc); 14258 } 14259 14260 if (S) 14261 PushOnScopeChains(MoveAssignment, S, false); 14262 ClassDecl->addDecl(MoveAssignment); 14263 14264 return MoveAssignment; 14265 } 14266 14267 /// Check if we're implicitly defining a move assignment operator for a class 14268 /// with virtual bases. Such a move assignment might move-assign the virtual 14269 /// base multiple times. 14270 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 14271 SourceLocation CurrentLocation) { 14272 assert(!Class->isDependentContext() && "should not define dependent move"); 14273 14274 // Only a virtual base could get implicitly move-assigned multiple times. 14275 // Only a non-trivial move assignment can observe this. We only want to 14276 // diagnose if we implicitly define an assignment operator that assigns 14277 // two base classes, both of which move-assign the same virtual base. 14278 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 14279 Class->getNumBases() < 2) 14280 return; 14281 14282 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 14283 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 14284 VBaseMap VBases; 14285 14286 for (auto &BI : Class->bases()) { 14287 Worklist.push_back(&BI); 14288 while (!Worklist.empty()) { 14289 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 14290 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 14291 14292 // If the base has no non-trivial move assignment operators, 14293 // we don't care about moves from it. 14294 if (!Base->hasNonTrivialMoveAssignment()) 14295 continue; 14296 14297 // If there's nothing virtual here, skip it. 14298 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 14299 continue; 14300 14301 // If we're not actually going to call a move assignment for this base, 14302 // or the selected move assignment is trivial, skip it. 14303 Sema::SpecialMemberOverloadResult SMOR = 14304 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 14305 /*ConstArg*/false, /*VolatileArg*/false, 14306 /*RValueThis*/true, /*ConstThis*/false, 14307 /*VolatileThis*/false); 14308 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 14309 !SMOR.getMethod()->isMoveAssignmentOperator()) 14310 continue; 14311 14312 if (BaseSpec->isVirtual()) { 14313 // We're going to move-assign this virtual base, and its move 14314 // assignment operator is not trivial. If this can happen for 14315 // multiple distinct direct bases of Class, diagnose it. (If it 14316 // only happens in one base, we'll diagnose it when synthesizing 14317 // that base class's move assignment operator.) 14318 CXXBaseSpecifier *&Existing = 14319 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 14320 .first->second; 14321 if (Existing && Existing != &BI) { 14322 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 14323 << Class << Base; 14324 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 14325 << (Base->getCanonicalDecl() == 14326 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14327 << Base << Existing->getType() << Existing->getSourceRange(); 14328 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 14329 << (Base->getCanonicalDecl() == 14330 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14331 << Base << BI.getType() << BaseSpec->getSourceRange(); 14332 14333 // Only diagnose each vbase once. 14334 Existing = nullptr; 14335 } 14336 } else { 14337 // Only walk over bases that have defaulted move assignment operators. 14338 // We assume that any user-provided move assignment operator handles 14339 // the multiple-moves-of-vbase case itself somehow. 14340 if (!SMOR.getMethod()->isDefaulted()) 14341 continue; 14342 14343 // We're going to move the base classes of Base. Add them to the list. 14344 for (auto &BI : Base->bases()) 14345 Worklist.push_back(&BI); 14346 } 14347 } 14348 } 14349 } 14350 14351 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 14352 CXXMethodDecl *MoveAssignOperator) { 14353 assert((MoveAssignOperator->isDefaulted() && 14354 MoveAssignOperator->isOverloadedOperator() && 14355 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 14356 !MoveAssignOperator->doesThisDeclarationHaveABody() && 14357 !MoveAssignOperator->isDeleted()) && 14358 "DefineImplicitMoveAssignment called for wrong function"); 14359 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 14360 return; 14361 14362 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 14363 if (ClassDecl->isInvalidDecl()) { 14364 MoveAssignOperator->setInvalidDecl(); 14365 return; 14366 } 14367 14368 // C++0x [class.copy]p28: 14369 // The implicitly-defined or move assignment operator for a non-union class 14370 // X performs memberwise move assignment of its subobjects. The direct base 14371 // classes of X are assigned first, in the order of their declaration in the 14372 // base-specifier-list, and then the immediate non-static data members of X 14373 // are assigned, in the order in which they were declared in the class 14374 // definition. 14375 14376 // Issue a warning if our implicit move assignment operator will move 14377 // from a virtual base more than once. 14378 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 14379 14380 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 14381 14382 // The exception specification is needed because we are defining the 14383 // function. 14384 ResolveExceptionSpec(CurrentLocation, 14385 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 14386 14387 // Add a context note for diagnostics produced after this point. 14388 Scope.addContextNote(CurrentLocation); 14389 14390 // The statements that form the synthesized function body. 14391 SmallVector<Stmt*, 8> Statements; 14392 14393 // The parameter for the "other" object, which we are move from. 14394 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 14395 QualType OtherRefType = 14396 Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); 14397 14398 // Our location for everything implicitly-generated. 14399 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 14400 ? MoveAssignOperator->getEndLoc() 14401 : MoveAssignOperator->getLocation(); 14402 14403 // Builds a reference to the "other" object. 14404 RefBuilder OtherRef(Other, OtherRefType); 14405 // Cast to rvalue. 14406 MoveCastBuilder MoveOther(OtherRef); 14407 14408 // Builds the "this" pointer. 14409 ThisBuilder This; 14410 14411 // Assign base classes. 14412 bool Invalid = false; 14413 for (auto &Base : ClassDecl->bases()) { 14414 // C++11 [class.copy]p28: 14415 // It is unspecified whether subobjects representing virtual base classes 14416 // are assigned more than once by the implicitly-defined copy assignment 14417 // operator. 14418 // FIXME: Do not assign to a vbase that will be assigned by some other base 14419 // class. For a move-assignment, this can result in the vbase being moved 14420 // multiple times. 14421 14422 // Form the assignment: 14423 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 14424 QualType BaseType = Base.getType().getUnqualifiedType(); 14425 if (!BaseType->isRecordType()) { 14426 Invalid = true; 14427 continue; 14428 } 14429 14430 CXXCastPath BasePath; 14431 BasePath.push_back(&Base); 14432 14433 // Construct the "from" expression, which is an implicit cast to the 14434 // appropriately-qualified base type. 14435 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 14436 14437 // Dereference "this". 14438 DerefBuilder DerefThis(This); 14439 14440 // Implicitly cast "this" to the appropriately-qualified base type. 14441 CastBuilder To(DerefThis, 14442 Context.getQualifiedType( 14443 BaseType, MoveAssignOperator->getMethodQualifiers()), 14444 VK_LValue, BasePath); 14445 14446 // Build the move. 14447 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 14448 To, From, 14449 /*CopyingBaseSubobject=*/true, 14450 /*Copying=*/false); 14451 if (Move.isInvalid()) { 14452 MoveAssignOperator->setInvalidDecl(); 14453 return; 14454 } 14455 14456 // Success! Record the move. 14457 Statements.push_back(Move.getAs<Expr>()); 14458 } 14459 14460 // Assign non-static members. 14461 for (auto *Field : ClassDecl->fields()) { 14462 // FIXME: We should form some kind of AST representation for the implied 14463 // memcpy in a union copy operation. 14464 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14465 continue; 14466 14467 if (Field->isInvalidDecl()) { 14468 Invalid = true; 14469 continue; 14470 } 14471 14472 // Check for members of reference type; we can't move those. 14473 if (Field->getType()->isReferenceType()) { 14474 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14475 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14476 Diag(Field->getLocation(), diag::note_declared_at); 14477 Invalid = true; 14478 continue; 14479 } 14480 14481 // Check for members of const-qualified, non-class type. 14482 QualType BaseType = Context.getBaseElementType(Field->getType()); 14483 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14484 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14485 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14486 Diag(Field->getLocation(), diag::note_declared_at); 14487 Invalid = true; 14488 continue; 14489 } 14490 14491 // Suppress assigning zero-width bitfields. 14492 if (Field->isZeroLengthBitField(Context)) 14493 continue; 14494 14495 QualType FieldType = Field->getType().getNonReferenceType(); 14496 if (FieldType->isIncompleteArrayType()) { 14497 assert(ClassDecl->hasFlexibleArrayMember() && 14498 "Incomplete array type is not valid"); 14499 continue; 14500 } 14501 14502 // Build references to the field in the object we're copying from and to. 14503 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14504 LookupMemberName); 14505 MemberLookup.addDecl(Field); 14506 MemberLookup.resolveKind(); 14507 MemberBuilder From(MoveOther, OtherRefType, 14508 /*IsArrow=*/false, MemberLookup); 14509 MemberBuilder To(This, getCurrentThisType(), 14510 /*IsArrow=*/true, MemberLookup); 14511 14512 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 14513 "Member reference with rvalue base must be rvalue except for reference " 14514 "members, which aren't allowed for move assignment."); 14515 14516 // Build the move of this field. 14517 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 14518 To, From, 14519 /*CopyingBaseSubobject=*/false, 14520 /*Copying=*/false); 14521 if (Move.isInvalid()) { 14522 MoveAssignOperator->setInvalidDecl(); 14523 return; 14524 } 14525 14526 // Success! Record the copy. 14527 Statements.push_back(Move.getAs<Stmt>()); 14528 } 14529 14530 if (!Invalid) { 14531 // Add a "return *this;" 14532 ExprResult ThisObj = 14533 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14534 14535 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14536 if (Return.isInvalid()) 14537 Invalid = true; 14538 else 14539 Statements.push_back(Return.getAs<Stmt>()); 14540 } 14541 14542 if (Invalid) { 14543 MoveAssignOperator->setInvalidDecl(); 14544 return; 14545 } 14546 14547 StmtResult Body; 14548 { 14549 CompoundScopeRAII CompoundScope(*this); 14550 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14551 /*isStmtExpr=*/false); 14552 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14553 } 14554 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 14555 MoveAssignOperator->markUsed(Context); 14556 14557 if (ASTMutationListener *L = getASTMutationListener()) { 14558 L->CompletedImplicitDefinition(MoveAssignOperator); 14559 } 14560 } 14561 14562 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 14563 CXXRecordDecl *ClassDecl) { 14564 // C++ [class.copy]p4: 14565 // If the class definition does not explicitly declare a copy 14566 // constructor, one is declared implicitly. 14567 assert(ClassDecl->needsImplicitCopyConstructor()); 14568 14569 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 14570 if (DSM.isAlreadyBeingDeclared()) 14571 return nullptr; 14572 14573 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14574 QualType ArgType = ClassType; 14575 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 14576 if (Const) 14577 ArgType = ArgType.withConst(); 14578 14579 LangAS AS = getDefaultCXXMethodAddrSpace(); 14580 if (AS != LangAS::Default) 14581 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14582 14583 ArgType = Context.getLValueReferenceType(ArgType); 14584 14585 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14586 CXXCopyConstructor, 14587 Const); 14588 14589 DeclarationName Name 14590 = Context.DeclarationNames.getCXXConstructorName( 14591 Context.getCanonicalType(ClassType)); 14592 SourceLocation ClassLoc = ClassDecl->getLocation(); 14593 DeclarationNameInfo NameInfo(Name, ClassLoc); 14594 14595 // An implicitly-declared copy constructor is an inline public 14596 // member of its class. 14597 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 14598 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14599 ExplicitSpecifier(), 14600 /*isInline=*/true, 14601 /*isImplicitlyDeclared=*/true, 14602 Constexpr ? ConstexprSpecKind::Constexpr 14603 : ConstexprSpecKind::Unspecified); 14604 CopyConstructor->setAccess(AS_public); 14605 CopyConstructor->setDefaulted(); 14606 14607 if (getLangOpts().CUDA) { 14608 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 14609 CopyConstructor, 14610 /* ConstRHS */ Const, 14611 /* Diagnose */ false); 14612 } 14613 14614 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 14615 14616 // Add the parameter to the constructor. 14617 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 14618 ClassLoc, ClassLoc, 14619 /*IdentifierInfo=*/nullptr, 14620 ArgType, /*TInfo=*/nullptr, 14621 SC_None, nullptr); 14622 CopyConstructor->setParams(FromParam); 14623 14624 CopyConstructor->setTrivial( 14625 ClassDecl->needsOverloadResolutionForCopyConstructor() 14626 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 14627 : ClassDecl->hasTrivialCopyConstructor()); 14628 14629 CopyConstructor->setTrivialForCall( 14630 ClassDecl->hasAttr<TrivialABIAttr>() || 14631 (ClassDecl->needsOverloadResolutionForCopyConstructor() 14632 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 14633 TAH_ConsiderTrivialABI) 14634 : ClassDecl->hasTrivialCopyConstructorForCall())); 14635 14636 // Note that we have declared this constructor. 14637 ++getASTContext().NumImplicitCopyConstructorsDeclared; 14638 14639 Scope *S = getScopeForContext(ClassDecl); 14640 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 14641 14642 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 14643 ClassDecl->setImplicitCopyConstructorIsDeleted(); 14644 SetDeclDeleted(CopyConstructor, ClassLoc); 14645 } 14646 14647 if (S) 14648 PushOnScopeChains(CopyConstructor, S, false); 14649 ClassDecl->addDecl(CopyConstructor); 14650 14651 return CopyConstructor; 14652 } 14653 14654 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 14655 CXXConstructorDecl *CopyConstructor) { 14656 assert((CopyConstructor->isDefaulted() && 14657 CopyConstructor->isCopyConstructor() && 14658 !CopyConstructor->doesThisDeclarationHaveABody() && 14659 !CopyConstructor->isDeleted()) && 14660 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 14661 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 14662 return; 14663 14664 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 14665 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 14666 14667 SynthesizedFunctionScope Scope(*this, CopyConstructor); 14668 14669 // The exception specification is needed because we are defining the 14670 // function. 14671 ResolveExceptionSpec(CurrentLocation, 14672 CopyConstructor->getType()->castAs<FunctionProtoType>()); 14673 MarkVTableUsed(CurrentLocation, ClassDecl); 14674 14675 // Add a context note for diagnostics produced after this point. 14676 Scope.addContextNote(CurrentLocation); 14677 14678 // C++11 [class.copy]p7: 14679 // The [definition of an implicitly declared copy constructor] is 14680 // deprecated if the class has a user-declared copy assignment operator 14681 // or a user-declared destructor. 14682 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 14683 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 14684 14685 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 14686 CopyConstructor->setInvalidDecl(); 14687 } else { 14688 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 14689 ? CopyConstructor->getEndLoc() 14690 : CopyConstructor->getLocation(); 14691 Sema::CompoundScopeRAII CompoundScope(*this); 14692 CopyConstructor->setBody( 14693 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 14694 CopyConstructor->markUsed(Context); 14695 } 14696 14697 if (ASTMutationListener *L = getASTMutationListener()) { 14698 L->CompletedImplicitDefinition(CopyConstructor); 14699 } 14700 } 14701 14702 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 14703 CXXRecordDecl *ClassDecl) { 14704 assert(ClassDecl->needsImplicitMoveConstructor()); 14705 14706 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 14707 if (DSM.isAlreadyBeingDeclared()) 14708 return nullptr; 14709 14710 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14711 14712 QualType ArgType = ClassType; 14713 LangAS AS = getDefaultCXXMethodAddrSpace(); 14714 if (AS != LangAS::Default) 14715 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 14716 ArgType = Context.getRValueReferenceType(ArgType); 14717 14718 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14719 CXXMoveConstructor, 14720 false); 14721 14722 DeclarationName Name 14723 = Context.DeclarationNames.getCXXConstructorName( 14724 Context.getCanonicalType(ClassType)); 14725 SourceLocation ClassLoc = ClassDecl->getLocation(); 14726 DeclarationNameInfo NameInfo(Name, ClassLoc); 14727 14728 // C++11 [class.copy]p11: 14729 // An implicitly-declared copy/move constructor is an inline public 14730 // member of its class. 14731 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 14732 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14733 ExplicitSpecifier(), 14734 /*isInline=*/true, 14735 /*isImplicitlyDeclared=*/true, 14736 Constexpr ? ConstexprSpecKind::Constexpr 14737 : ConstexprSpecKind::Unspecified); 14738 MoveConstructor->setAccess(AS_public); 14739 MoveConstructor->setDefaulted(); 14740 14741 if (getLangOpts().CUDA) { 14742 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 14743 MoveConstructor, 14744 /* ConstRHS */ false, 14745 /* Diagnose */ false); 14746 } 14747 14748 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 14749 14750 // Add the parameter to the constructor. 14751 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 14752 ClassLoc, ClassLoc, 14753 /*IdentifierInfo=*/nullptr, 14754 ArgType, /*TInfo=*/nullptr, 14755 SC_None, nullptr); 14756 MoveConstructor->setParams(FromParam); 14757 14758 MoveConstructor->setTrivial( 14759 ClassDecl->needsOverloadResolutionForMoveConstructor() 14760 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 14761 : ClassDecl->hasTrivialMoveConstructor()); 14762 14763 MoveConstructor->setTrivialForCall( 14764 ClassDecl->hasAttr<TrivialABIAttr>() || 14765 (ClassDecl->needsOverloadResolutionForMoveConstructor() 14766 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 14767 TAH_ConsiderTrivialABI) 14768 : ClassDecl->hasTrivialMoveConstructorForCall())); 14769 14770 // Note that we have declared this constructor. 14771 ++getASTContext().NumImplicitMoveConstructorsDeclared; 14772 14773 Scope *S = getScopeForContext(ClassDecl); 14774 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 14775 14776 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 14777 ClassDecl->setImplicitMoveConstructorIsDeleted(); 14778 SetDeclDeleted(MoveConstructor, ClassLoc); 14779 } 14780 14781 if (S) 14782 PushOnScopeChains(MoveConstructor, S, false); 14783 ClassDecl->addDecl(MoveConstructor); 14784 14785 return MoveConstructor; 14786 } 14787 14788 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 14789 CXXConstructorDecl *MoveConstructor) { 14790 assert((MoveConstructor->isDefaulted() && 14791 MoveConstructor->isMoveConstructor() && 14792 !MoveConstructor->doesThisDeclarationHaveABody() && 14793 !MoveConstructor->isDeleted()) && 14794 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 14795 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 14796 return; 14797 14798 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 14799 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 14800 14801 SynthesizedFunctionScope Scope(*this, MoveConstructor); 14802 14803 // The exception specification is needed because we are defining the 14804 // function. 14805 ResolveExceptionSpec(CurrentLocation, 14806 MoveConstructor->getType()->castAs<FunctionProtoType>()); 14807 MarkVTableUsed(CurrentLocation, ClassDecl); 14808 14809 // Add a context note for diagnostics produced after this point. 14810 Scope.addContextNote(CurrentLocation); 14811 14812 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 14813 MoveConstructor->setInvalidDecl(); 14814 } else { 14815 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 14816 ? MoveConstructor->getEndLoc() 14817 : MoveConstructor->getLocation(); 14818 Sema::CompoundScopeRAII CompoundScope(*this); 14819 MoveConstructor->setBody(ActOnCompoundStmt( 14820 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 14821 MoveConstructor->markUsed(Context); 14822 } 14823 14824 if (ASTMutationListener *L = getASTMutationListener()) { 14825 L->CompletedImplicitDefinition(MoveConstructor); 14826 } 14827 } 14828 14829 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 14830 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 14831 } 14832 14833 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 14834 SourceLocation CurrentLocation, 14835 CXXConversionDecl *Conv) { 14836 SynthesizedFunctionScope Scope(*this, Conv); 14837 assert(!Conv->getReturnType()->isUndeducedType()); 14838 14839 QualType ConvRT = Conv->getType()->getAs<FunctionType>()->getReturnType(); 14840 CallingConv CC = 14841 ConvRT->getPointeeType()->getAs<FunctionType>()->getCallConv(); 14842 14843 CXXRecordDecl *Lambda = Conv->getParent(); 14844 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 14845 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC); 14846 14847 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 14848 CallOp = InstantiateFunctionDeclaration( 14849 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14850 if (!CallOp) 14851 return; 14852 14853 Invoker = InstantiateFunctionDeclaration( 14854 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14855 if (!Invoker) 14856 return; 14857 } 14858 14859 if (CallOp->isInvalidDecl()) 14860 return; 14861 14862 // Mark the call operator referenced (and add to pending instantiations 14863 // if necessary). 14864 // For both the conversion and static-invoker template specializations 14865 // we construct their body's in this function, so no need to add them 14866 // to the PendingInstantiations. 14867 MarkFunctionReferenced(CurrentLocation, CallOp); 14868 14869 // Fill in the __invoke function with a dummy implementation. IR generation 14870 // will fill in the actual details. Update its type in case it contained 14871 // an 'auto'. 14872 Invoker->markUsed(Context); 14873 Invoker->setReferenced(); 14874 Invoker->setType(Conv->getReturnType()->getPointeeType()); 14875 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 14876 14877 // Construct the body of the conversion function { return __invoke; }. 14878 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 14879 VK_LValue, Conv->getLocation()); 14880 assert(FunctionRef && "Can't refer to __invoke function?"); 14881 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 14882 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 14883 Conv->getLocation())); 14884 Conv->markUsed(Context); 14885 Conv->setReferenced(); 14886 14887 if (ASTMutationListener *L = getASTMutationListener()) { 14888 L->CompletedImplicitDefinition(Conv); 14889 L->CompletedImplicitDefinition(Invoker); 14890 } 14891 } 14892 14893 14894 14895 void Sema::DefineImplicitLambdaToBlockPointerConversion( 14896 SourceLocation CurrentLocation, 14897 CXXConversionDecl *Conv) 14898 { 14899 assert(!Conv->getParent()->isGenericLambda()); 14900 14901 SynthesizedFunctionScope Scope(*this, Conv); 14902 14903 // Copy-initialize the lambda object as needed to capture it. 14904 Expr *This = ActOnCXXThis(CurrentLocation).get(); 14905 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 14906 14907 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 14908 Conv->getLocation(), 14909 Conv, DerefThis); 14910 14911 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 14912 // behavior. Note that only the general conversion function does this 14913 // (since it's unusable otherwise); in the case where we inline the 14914 // block literal, it has block literal lifetime semantics. 14915 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 14916 BuildBlock = ImplicitCastExpr::Create( 14917 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject, 14918 BuildBlock.get(), nullptr, VK_RValue, FPOptionsOverride()); 14919 14920 if (BuildBlock.isInvalid()) { 14921 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14922 Conv->setInvalidDecl(); 14923 return; 14924 } 14925 14926 // Create the return statement that returns the block from the conversion 14927 // function. 14928 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 14929 if (Return.isInvalid()) { 14930 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14931 Conv->setInvalidDecl(); 14932 return; 14933 } 14934 14935 // Set the body of the conversion function. 14936 Stmt *ReturnS = Return.get(); 14937 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 14938 Conv->getLocation())); 14939 Conv->markUsed(Context); 14940 14941 // We're done; notify the mutation listener, if any. 14942 if (ASTMutationListener *L = getASTMutationListener()) { 14943 L->CompletedImplicitDefinition(Conv); 14944 } 14945 } 14946 14947 /// Determine whether the given list arguments contains exactly one 14948 /// "real" (non-default) argument. 14949 static bool hasOneRealArgument(MultiExprArg Args) { 14950 switch (Args.size()) { 14951 case 0: 14952 return false; 14953 14954 default: 14955 if (!Args[1]->isDefaultArgument()) 14956 return false; 14957 14958 LLVM_FALLTHROUGH; 14959 case 1: 14960 return !Args[0]->isDefaultArgument(); 14961 } 14962 14963 return false; 14964 } 14965 14966 ExprResult 14967 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14968 NamedDecl *FoundDecl, 14969 CXXConstructorDecl *Constructor, 14970 MultiExprArg ExprArgs, 14971 bool HadMultipleCandidates, 14972 bool IsListInitialization, 14973 bool IsStdInitListInitialization, 14974 bool RequiresZeroInit, 14975 unsigned ConstructKind, 14976 SourceRange ParenRange) { 14977 bool Elidable = false; 14978 14979 // C++0x [class.copy]p34: 14980 // When certain criteria are met, an implementation is allowed to 14981 // omit the copy/move construction of a class object, even if the 14982 // copy/move constructor and/or destructor for the object have 14983 // side effects. [...] 14984 // - when a temporary class object that has not been bound to a 14985 // reference (12.2) would be copied/moved to a class object 14986 // with the same cv-unqualified type, the copy/move operation 14987 // can be omitted by constructing the temporary object 14988 // directly into the target of the omitted copy/move 14989 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 14990 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 14991 Expr *SubExpr = ExprArgs[0]; 14992 Elidable = SubExpr->isTemporaryObject( 14993 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 14994 } 14995 14996 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 14997 FoundDecl, Constructor, 14998 Elidable, ExprArgs, HadMultipleCandidates, 14999 IsListInitialization, 15000 IsStdInitListInitialization, RequiresZeroInit, 15001 ConstructKind, ParenRange); 15002 } 15003 15004 ExprResult 15005 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15006 NamedDecl *FoundDecl, 15007 CXXConstructorDecl *Constructor, 15008 bool Elidable, 15009 MultiExprArg ExprArgs, 15010 bool HadMultipleCandidates, 15011 bool IsListInitialization, 15012 bool IsStdInitListInitialization, 15013 bool RequiresZeroInit, 15014 unsigned ConstructKind, 15015 SourceRange ParenRange) { 15016 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 15017 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 15018 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 15019 return ExprError(); 15020 } 15021 15022 return BuildCXXConstructExpr( 15023 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 15024 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 15025 RequiresZeroInit, ConstructKind, ParenRange); 15026 } 15027 15028 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 15029 /// including handling of its default argument expressions. 15030 ExprResult 15031 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15032 CXXConstructorDecl *Constructor, 15033 bool Elidable, 15034 MultiExprArg ExprArgs, 15035 bool HadMultipleCandidates, 15036 bool IsListInitialization, 15037 bool IsStdInitListInitialization, 15038 bool RequiresZeroInit, 15039 unsigned ConstructKind, 15040 SourceRange ParenRange) { 15041 assert(declaresSameEntity( 15042 Constructor->getParent(), 15043 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 15044 "given constructor for wrong type"); 15045 MarkFunctionReferenced(ConstructLoc, Constructor); 15046 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 15047 return ExprError(); 15048 if (getLangOpts().SYCLIsDevice && 15049 !checkSYCLDeviceFunction(ConstructLoc, Constructor)) 15050 return ExprError(); 15051 15052 return CheckForImmediateInvocation( 15053 CXXConstructExpr::Create( 15054 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 15055 HadMultipleCandidates, IsListInitialization, 15056 IsStdInitListInitialization, RequiresZeroInit, 15057 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 15058 ParenRange), 15059 Constructor); 15060 } 15061 15062 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 15063 assert(Field->hasInClassInitializer()); 15064 15065 // If we already have the in-class initializer nothing needs to be done. 15066 if (Field->getInClassInitializer()) 15067 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15068 15069 // If we might have already tried and failed to instantiate, don't try again. 15070 if (Field->isInvalidDecl()) 15071 return ExprError(); 15072 15073 // Maybe we haven't instantiated the in-class initializer. Go check the 15074 // pattern FieldDecl to see if it has one. 15075 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 15076 15077 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 15078 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 15079 DeclContext::lookup_result Lookup = 15080 ClassPattern->lookup(Field->getDeclName()); 15081 15082 FieldDecl *Pattern = nullptr; 15083 for (auto L : Lookup) { 15084 if (isa<FieldDecl>(L)) { 15085 Pattern = cast<FieldDecl>(L); 15086 break; 15087 } 15088 } 15089 assert(Pattern && "We must have set the Pattern!"); 15090 15091 if (!Pattern->hasInClassInitializer() || 15092 InstantiateInClassInitializer(Loc, Field, Pattern, 15093 getTemplateInstantiationArgs(Field))) { 15094 // Don't diagnose this again. 15095 Field->setInvalidDecl(); 15096 return ExprError(); 15097 } 15098 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15099 } 15100 15101 // DR1351: 15102 // If the brace-or-equal-initializer of a non-static data member 15103 // invokes a defaulted default constructor of its class or of an 15104 // enclosing class in a potentially evaluated subexpression, the 15105 // program is ill-formed. 15106 // 15107 // This resolution is unworkable: the exception specification of the 15108 // default constructor can be needed in an unevaluated context, in 15109 // particular, in the operand of a noexcept-expression, and we can be 15110 // unable to compute an exception specification for an enclosed class. 15111 // 15112 // Any attempt to resolve the exception specification of a defaulted default 15113 // constructor before the initializer is lexically complete will ultimately 15114 // come here at which point we can diagnose it. 15115 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 15116 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed) 15117 << OutermostClass << Field; 15118 Diag(Field->getEndLoc(), 15119 diag::note_default_member_initializer_not_yet_parsed); 15120 // Recover by marking the field invalid, unless we're in a SFINAE context. 15121 if (!isSFINAEContext()) 15122 Field->setInvalidDecl(); 15123 return ExprError(); 15124 } 15125 15126 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 15127 if (VD->isInvalidDecl()) return; 15128 // If initializing the variable failed, don't also diagnose problems with 15129 // the desctructor, they're likely related. 15130 if (VD->getInit() && VD->getInit()->containsErrors()) 15131 return; 15132 15133 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 15134 if (ClassDecl->isInvalidDecl()) return; 15135 if (ClassDecl->hasIrrelevantDestructor()) return; 15136 if (ClassDecl->isDependentContext()) return; 15137 15138 if (VD->isNoDestroy(getASTContext())) 15139 return; 15140 15141 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15142 15143 // If this is an array, we'll require the destructor during initialization, so 15144 // we can skip over this. We still want to emit exit-time destructor warnings 15145 // though. 15146 if (!VD->getType()->isArrayType()) { 15147 MarkFunctionReferenced(VD->getLocation(), Destructor); 15148 CheckDestructorAccess(VD->getLocation(), Destructor, 15149 PDiag(diag::err_access_dtor_var) 15150 << VD->getDeclName() << VD->getType()); 15151 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 15152 } 15153 15154 if (Destructor->isTrivial()) return; 15155 15156 // If the destructor is constexpr, check whether the variable has constant 15157 // destruction now. 15158 if (Destructor->isConstexpr()) { 15159 bool HasConstantInit = false; 15160 if (VD->getInit() && !VD->getInit()->isValueDependent()) 15161 HasConstantInit = VD->evaluateValue(); 15162 SmallVector<PartialDiagnosticAt, 8> Notes; 15163 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && 15164 HasConstantInit) { 15165 Diag(VD->getLocation(), 15166 diag::err_constexpr_var_requires_const_destruction) << VD; 15167 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 15168 Diag(Notes[I].first, Notes[I].second); 15169 } 15170 } 15171 15172 if (!VD->hasGlobalStorage()) return; 15173 15174 // Emit warning for non-trivial dtor in global scope (a real global, 15175 // class-static, function-static). 15176 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 15177 15178 // TODO: this should be re-enabled for static locals by !CXAAtExit 15179 if (!VD->isStaticLocal()) 15180 Diag(VD->getLocation(), diag::warn_global_destructor); 15181 } 15182 15183 /// Given a constructor and the set of arguments provided for the 15184 /// constructor, convert the arguments and add any required default arguments 15185 /// to form a proper call to this constructor. 15186 /// 15187 /// \returns true if an error occurred, false otherwise. 15188 bool 15189 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 15190 MultiExprArg ArgsPtr, 15191 SourceLocation Loc, 15192 SmallVectorImpl<Expr*> &ConvertedArgs, 15193 bool AllowExplicit, 15194 bool IsListInitialization) { 15195 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 15196 unsigned NumArgs = ArgsPtr.size(); 15197 Expr **Args = ArgsPtr.data(); 15198 15199 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); 15200 unsigned NumParams = Proto->getNumParams(); 15201 15202 // If too few arguments are available, we'll fill in the rest with defaults. 15203 if (NumArgs < NumParams) 15204 ConvertedArgs.reserve(NumParams); 15205 else 15206 ConvertedArgs.reserve(NumArgs); 15207 15208 VariadicCallType CallType = 15209 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 15210 SmallVector<Expr *, 8> AllArgs; 15211 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 15212 Proto, 0, 15213 llvm::makeArrayRef(Args, NumArgs), 15214 AllArgs, 15215 CallType, AllowExplicit, 15216 IsListInitialization); 15217 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 15218 15219 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 15220 15221 CheckConstructorCall(Constructor, 15222 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 15223 Proto, Loc); 15224 15225 return Invalid; 15226 } 15227 15228 static inline bool 15229 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 15230 const FunctionDecl *FnDecl) { 15231 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 15232 if (isa<NamespaceDecl>(DC)) { 15233 return SemaRef.Diag(FnDecl->getLocation(), 15234 diag::err_operator_new_delete_declared_in_namespace) 15235 << FnDecl->getDeclName(); 15236 } 15237 15238 if (isa<TranslationUnitDecl>(DC) && 15239 FnDecl->getStorageClass() == SC_Static) { 15240 return SemaRef.Diag(FnDecl->getLocation(), 15241 diag::err_operator_new_delete_declared_static) 15242 << FnDecl->getDeclName(); 15243 } 15244 15245 return false; 15246 } 15247 15248 static QualType 15249 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { 15250 QualType QTy = PtrTy->getPointeeType(); 15251 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); 15252 return SemaRef.Context.getPointerType(QTy); 15253 } 15254 15255 static inline bool 15256 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 15257 CanQualType ExpectedResultType, 15258 CanQualType ExpectedFirstParamType, 15259 unsigned DependentParamTypeDiag, 15260 unsigned InvalidParamTypeDiag) { 15261 QualType ResultType = 15262 FnDecl->getType()->castAs<FunctionType>()->getReturnType(); 15263 15264 // The operator is valid on any address space for OpenCL. 15265 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15266 if (auto *PtrTy = ResultType->getAs<PointerType>()) { 15267 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15268 } 15269 } 15270 15271 // Check that the result type is what we expect. 15272 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) { 15273 // Reject even if the type is dependent; an operator delete function is 15274 // required to have a non-dependent result type. 15275 return SemaRef.Diag( 15276 FnDecl->getLocation(), 15277 ResultType->isDependentType() 15278 ? diag::err_operator_new_delete_dependent_result_type 15279 : diag::err_operator_new_delete_invalid_result_type) 15280 << FnDecl->getDeclName() << ExpectedResultType; 15281 } 15282 15283 // A function template must have at least 2 parameters. 15284 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 15285 return SemaRef.Diag(FnDecl->getLocation(), 15286 diag::err_operator_new_delete_template_too_few_parameters) 15287 << FnDecl->getDeclName(); 15288 15289 // The function decl must have at least 1 parameter. 15290 if (FnDecl->getNumParams() == 0) 15291 return SemaRef.Diag(FnDecl->getLocation(), 15292 diag::err_operator_new_delete_too_few_parameters) 15293 << FnDecl->getDeclName(); 15294 15295 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 15296 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15297 // The operator is valid on any address space for OpenCL. 15298 if (auto *PtrTy = 15299 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { 15300 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15301 } 15302 } 15303 15304 // Check that the first parameter type is what we expect. 15305 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 15306 ExpectedFirstParamType) { 15307 // The first parameter type is not allowed to be dependent. As a tentative 15308 // DR resolution, we allow a dependent parameter type if it is the right 15309 // type anyway, to allow destroying operator delete in class templates. 15310 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType() 15311 ? DependentParamTypeDiag 15312 : InvalidParamTypeDiag) 15313 << FnDecl->getDeclName() << ExpectedFirstParamType; 15314 } 15315 15316 return false; 15317 } 15318 15319 static bool 15320 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 15321 // C++ [basic.stc.dynamic.allocation]p1: 15322 // A program is ill-formed if an allocation function is declared in a 15323 // namespace scope other than global scope or declared static in global 15324 // scope. 15325 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15326 return true; 15327 15328 CanQualType SizeTy = 15329 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 15330 15331 // C++ [basic.stc.dynamic.allocation]p1: 15332 // The return type shall be void*. The first parameter shall have type 15333 // std::size_t. 15334 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 15335 SizeTy, 15336 diag::err_operator_new_dependent_param_type, 15337 diag::err_operator_new_param_type)) 15338 return true; 15339 15340 // C++ [basic.stc.dynamic.allocation]p1: 15341 // The first parameter shall not have an associated default argument. 15342 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 15343 return SemaRef.Diag(FnDecl->getLocation(), 15344 diag::err_operator_new_default_arg) 15345 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 15346 15347 return false; 15348 } 15349 15350 static bool 15351 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 15352 // C++ [basic.stc.dynamic.deallocation]p1: 15353 // A program is ill-formed if deallocation functions are 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 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 15360 15361 // C++ P0722: 15362 // Within a class C, the first parameter of a destroying operator delete 15363 // shall be of type C *. The first parameter of any other deallocation 15364 // function shall be of type void *. 15365 CanQualType ExpectedFirstParamType = 15366 MD && MD->isDestroyingOperatorDelete() 15367 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 15368 SemaRef.Context.getRecordType(MD->getParent()))) 15369 : SemaRef.Context.VoidPtrTy; 15370 15371 // C++ [basic.stc.dynamic.deallocation]p2: 15372 // Each deallocation function shall return void 15373 if (CheckOperatorNewDeleteTypes( 15374 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 15375 diag::err_operator_delete_dependent_param_type, 15376 diag::err_operator_delete_param_type)) 15377 return true; 15378 15379 // C++ P0722: 15380 // A destroying operator delete shall be a usual deallocation function. 15381 if (MD && !MD->getParent()->isDependentContext() && 15382 MD->isDestroyingOperatorDelete() && 15383 !SemaRef.isUsualDeallocationFunction(MD)) { 15384 SemaRef.Diag(MD->getLocation(), 15385 diag::err_destroying_operator_delete_not_usual); 15386 return true; 15387 } 15388 15389 return false; 15390 } 15391 15392 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 15393 /// of this overloaded operator is well-formed. If so, returns false; 15394 /// otherwise, emits appropriate diagnostics and returns true. 15395 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 15396 assert(FnDecl && FnDecl->isOverloadedOperator() && 15397 "Expected an overloaded operator declaration"); 15398 15399 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 15400 15401 // C++ [over.oper]p5: 15402 // The allocation and deallocation functions, operator new, 15403 // operator new[], operator delete and operator delete[], are 15404 // described completely in 3.7.3. The attributes and restrictions 15405 // found in the rest of this subclause do not apply to them unless 15406 // explicitly stated in 3.7.3. 15407 if (Op == OO_Delete || Op == OO_Array_Delete) 15408 return CheckOperatorDeleteDeclaration(*this, FnDecl); 15409 15410 if (Op == OO_New || Op == OO_Array_New) 15411 return CheckOperatorNewDeclaration(*this, FnDecl); 15412 15413 // C++ [over.oper]p6: 15414 // An operator function shall either be a non-static member 15415 // function or be a non-member function and have at least one 15416 // parameter whose type is a class, a reference to a class, an 15417 // enumeration, or a reference to an enumeration. 15418 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 15419 if (MethodDecl->isStatic()) 15420 return Diag(FnDecl->getLocation(), 15421 diag::err_operator_overload_static) << FnDecl->getDeclName(); 15422 } else { 15423 bool ClassOrEnumParam = false; 15424 for (auto Param : FnDecl->parameters()) { 15425 QualType ParamType = Param->getType().getNonReferenceType(); 15426 if (ParamType->isDependentType() || ParamType->isRecordType() || 15427 ParamType->isEnumeralType()) { 15428 ClassOrEnumParam = true; 15429 break; 15430 } 15431 } 15432 15433 if (!ClassOrEnumParam) 15434 return Diag(FnDecl->getLocation(), 15435 diag::err_operator_overload_needs_class_or_enum) 15436 << FnDecl->getDeclName(); 15437 } 15438 15439 // C++ [over.oper]p8: 15440 // An operator function cannot have default arguments (8.3.6), 15441 // except where explicitly stated below. 15442 // 15443 // Only the function-call operator allows default arguments 15444 // (C++ [over.call]p1). 15445 if (Op != OO_Call) { 15446 for (auto Param : FnDecl->parameters()) { 15447 if (Param->hasDefaultArg()) 15448 return Diag(Param->getLocation(), 15449 diag::err_operator_overload_default_arg) 15450 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 15451 } 15452 } 15453 15454 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 15455 { false, false, false } 15456 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 15457 , { Unary, Binary, MemberOnly } 15458 #include "clang/Basic/OperatorKinds.def" 15459 }; 15460 15461 bool CanBeUnaryOperator = OperatorUses[Op][0]; 15462 bool CanBeBinaryOperator = OperatorUses[Op][1]; 15463 bool MustBeMemberOperator = OperatorUses[Op][2]; 15464 15465 // C++ [over.oper]p8: 15466 // [...] Operator functions cannot have more or fewer parameters 15467 // than the number required for the corresponding operator, as 15468 // described in the rest of this subclause. 15469 unsigned NumParams = FnDecl->getNumParams() 15470 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 15471 if (Op != OO_Call && 15472 ((NumParams == 1 && !CanBeUnaryOperator) || 15473 (NumParams == 2 && !CanBeBinaryOperator) || 15474 (NumParams < 1) || (NumParams > 2))) { 15475 // We have the wrong number of parameters. 15476 unsigned ErrorKind; 15477 if (CanBeUnaryOperator && CanBeBinaryOperator) { 15478 ErrorKind = 2; // 2 -> unary or binary. 15479 } else if (CanBeUnaryOperator) { 15480 ErrorKind = 0; // 0 -> unary 15481 } else { 15482 assert(CanBeBinaryOperator && 15483 "All non-call overloaded operators are unary or binary!"); 15484 ErrorKind = 1; // 1 -> binary 15485 } 15486 15487 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 15488 << FnDecl->getDeclName() << NumParams << ErrorKind; 15489 } 15490 15491 // Overloaded operators other than operator() cannot be variadic. 15492 if (Op != OO_Call && 15493 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { 15494 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 15495 << FnDecl->getDeclName(); 15496 } 15497 15498 // Some operators must be non-static member functions. 15499 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 15500 return Diag(FnDecl->getLocation(), 15501 diag::err_operator_overload_must_be_member) 15502 << FnDecl->getDeclName(); 15503 } 15504 15505 // C++ [over.inc]p1: 15506 // The user-defined function called operator++ implements the 15507 // prefix and postfix ++ operator. If this function is a member 15508 // function with no parameters, or a non-member function with one 15509 // parameter of class or enumeration type, it defines the prefix 15510 // increment operator ++ for objects of that type. If the function 15511 // is a member function with one parameter (which shall be of type 15512 // int) or a non-member function with two parameters (the second 15513 // of which shall be of type int), it defines the postfix 15514 // increment operator ++ for objects of that type. 15515 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 15516 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 15517 QualType ParamType = LastParam->getType(); 15518 15519 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 15520 !ParamType->isDependentType()) 15521 return Diag(LastParam->getLocation(), 15522 diag::err_operator_overload_post_incdec_must_be_int) 15523 << LastParam->getType() << (Op == OO_MinusMinus); 15524 } 15525 15526 return false; 15527 } 15528 15529 static bool 15530 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 15531 FunctionTemplateDecl *TpDecl) { 15532 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 15533 15534 // Must have one or two template parameters. 15535 if (TemplateParams->size() == 1) { 15536 NonTypeTemplateParmDecl *PmDecl = 15537 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 15538 15539 // The template parameter must be a char parameter pack. 15540 if (PmDecl && PmDecl->isTemplateParameterPack() && 15541 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 15542 return false; 15543 15544 // C++20 [over.literal]p5: 15545 // A string literal operator template is a literal operator template 15546 // whose template-parameter-list comprises a single non-type 15547 // template-parameter of class type. 15548 // 15549 // As a DR resolution, we also allow placeholders for deduced class 15550 // template specializations. 15551 if (SemaRef.getLangOpts().CPlusPlus20 && 15552 !PmDecl->isTemplateParameterPack() && 15553 (PmDecl->getType()->isRecordType() || 15554 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>())) 15555 return false; 15556 } else if (TemplateParams->size() == 2) { 15557 TemplateTypeParmDecl *PmType = 15558 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 15559 NonTypeTemplateParmDecl *PmArgs = 15560 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 15561 15562 // The second template parameter must be a parameter pack with the 15563 // first template parameter as its type. 15564 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 15565 PmArgs->isTemplateParameterPack()) { 15566 const TemplateTypeParmType *TArgs = 15567 PmArgs->getType()->getAs<TemplateTypeParmType>(); 15568 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 15569 TArgs->getIndex() == PmType->getIndex()) { 15570 if (!SemaRef.inTemplateInstantiation()) 15571 SemaRef.Diag(TpDecl->getLocation(), 15572 diag::ext_string_literal_operator_template); 15573 return false; 15574 } 15575 } 15576 } 15577 15578 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 15579 diag::err_literal_operator_template) 15580 << TpDecl->getTemplateParameters()->getSourceRange(); 15581 return true; 15582 } 15583 15584 /// CheckLiteralOperatorDeclaration - Check whether the declaration 15585 /// of this literal operator function is well-formed. If so, returns 15586 /// false; otherwise, emits appropriate diagnostics and returns true. 15587 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 15588 if (isa<CXXMethodDecl>(FnDecl)) { 15589 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 15590 << FnDecl->getDeclName(); 15591 return true; 15592 } 15593 15594 if (FnDecl->isExternC()) { 15595 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 15596 if (const LinkageSpecDecl *LSD = 15597 FnDecl->getDeclContext()->getExternCContext()) 15598 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 15599 return true; 15600 } 15601 15602 // This might be the definition of a literal operator template. 15603 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 15604 15605 // This might be a specialization of a literal operator template. 15606 if (!TpDecl) 15607 TpDecl = FnDecl->getPrimaryTemplate(); 15608 15609 // template <char...> type operator "" name() and 15610 // template <class T, T...> type operator "" name() are the only valid 15611 // template signatures, and the only valid signatures with no parameters. 15612 // 15613 // C++20 also allows template <SomeClass T> type operator "" name(). 15614 if (TpDecl) { 15615 if (FnDecl->param_size() != 0) { 15616 Diag(FnDecl->getLocation(), 15617 diag::err_literal_operator_template_with_params); 15618 return true; 15619 } 15620 15621 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 15622 return true; 15623 15624 } else if (FnDecl->param_size() == 1) { 15625 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 15626 15627 QualType ParamType = Param->getType().getUnqualifiedType(); 15628 15629 // Only unsigned long long int, long double, any character type, and const 15630 // char * are allowed as the only parameters. 15631 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 15632 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 15633 Context.hasSameType(ParamType, Context.CharTy) || 15634 Context.hasSameType(ParamType, Context.WideCharTy) || 15635 Context.hasSameType(ParamType, Context.Char8Ty) || 15636 Context.hasSameType(ParamType, Context.Char16Ty) || 15637 Context.hasSameType(ParamType, Context.Char32Ty)) { 15638 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 15639 QualType InnerType = Ptr->getPointeeType(); 15640 15641 // Pointer parameter must be a const char *. 15642 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 15643 Context.CharTy) && 15644 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 15645 Diag(Param->getSourceRange().getBegin(), 15646 diag::err_literal_operator_param) 15647 << ParamType << "'const char *'" << Param->getSourceRange(); 15648 return true; 15649 } 15650 15651 } else if (ParamType->isRealFloatingType()) { 15652 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15653 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 15654 return true; 15655 15656 } else if (ParamType->isIntegerType()) { 15657 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15658 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 15659 return true; 15660 15661 } else { 15662 Diag(Param->getSourceRange().getBegin(), 15663 diag::err_literal_operator_invalid_param) 15664 << ParamType << Param->getSourceRange(); 15665 return true; 15666 } 15667 15668 } else if (FnDecl->param_size() == 2) { 15669 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 15670 15671 // First, verify that the first parameter is correct. 15672 15673 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 15674 15675 // Two parameter function must have a pointer to const as a 15676 // first parameter; let's strip those qualifiers. 15677 const PointerType *PT = FirstParamType->getAs<PointerType>(); 15678 15679 if (!PT) { 15680 Diag((*Param)->getSourceRange().getBegin(), 15681 diag::err_literal_operator_param) 15682 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15683 return true; 15684 } 15685 15686 QualType PointeeType = PT->getPointeeType(); 15687 // First parameter must be const 15688 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 15689 Diag((*Param)->getSourceRange().getBegin(), 15690 diag::err_literal_operator_param) 15691 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15692 return true; 15693 } 15694 15695 QualType InnerType = PointeeType.getUnqualifiedType(); 15696 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 15697 // const char32_t* are allowed as the first parameter to a two-parameter 15698 // function 15699 if (!(Context.hasSameType(InnerType, Context.CharTy) || 15700 Context.hasSameType(InnerType, Context.WideCharTy) || 15701 Context.hasSameType(InnerType, Context.Char8Ty) || 15702 Context.hasSameType(InnerType, Context.Char16Ty) || 15703 Context.hasSameType(InnerType, Context.Char32Ty))) { 15704 Diag((*Param)->getSourceRange().getBegin(), 15705 diag::err_literal_operator_param) 15706 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15707 return true; 15708 } 15709 15710 // Move on to the second and final parameter. 15711 ++Param; 15712 15713 // The second parameter must be a std::size_t. 15714 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 15715 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 15716 Diag((*Param)->getSourceRange().getBegin(), 15717 diag::err_literal_operator_param) 15718 << SecondParamType << Context.getSizeType() 15719 << (*Param)->getSourceRange(); 15720 return true; 15721 } 15722 } else { 15723 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 15724 return true; 15725 } 15726 15727 // Parameters are good. 15728 15729 // A parameter-declaration-clause containing a default argument is not 15730 // equivalent to any of the permitted forms. 15731 for (auto Param : FnDecl->parameters()) { 15732 if (Param->hasDefaultArg()) { 15733 Diag(Param->getDefaultArgRange().getBegin(), 15734 diag::err_literal_operator_default_argument) 15735 << Param->getDefaultArgRange(); 15736 break; 15737 } 15738 } 15739 15740 StringRef LiteralName 15741 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 15742 if (LiteralName[0] != '_' && 15743 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 15744 // C++11 [usrlit.suffix]p1: 15745 // Literal suffix identifiers that do not start with an underscore 15746 // are reserved for future standardization. 15747 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 15748 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 15749 } 15750 15751 return false; 15752 } 15753 15754 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 15755 /// linkage specification, including the language and (if present) 15756 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 15757 /// language string literal. LBraceLoc, if valid, provides the location of 15758 /// the '{' brace. Otherwise, this linkage specification does not 15759 /// have any braces. 15760 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 15761 Expr *LangStr, 15762 SourceLocation LBraceLoc) { 15763 StringLiteral *Lit = cast<StringLiteral>(LangStr); 15764 if (!Lit->isAscii()) { 15765 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 15766 << LangStr->getSourceRange(); 15767 return nullptr; 15768 } 15769 15770 StringRef Lang = Lit->getString(); 15771 LinkageSpecDecl::LanguageIDs Language; 15772 if (Lang == "C") 15773 Language = LinkageSpecDecl::lang_c; 15774 else if (Lang == "C++") 15775 Language = LinkageSpecDecl::lang_cxx; 15776 else { 15777 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 15778 << LangStr->getSourceRange(); 15779 return nullptr; 15780 } 15781 15782 // FIXME: Add all the various semantics of linkage specifications 15783 15784 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 15785 LangStr->getExprLoc(), Language, 15786 LBraceLoc.isValid()); 15787 CurContext->addDecl(D); 15788 PushDeclContext(S, D); 15789 return D; 15790 } 15791 15792 /// ActOnFinishLinkageSpecification - Complete the definition of 15793 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 15794 /// valid, it's the position of the closing '}' brace in a linkage 15795 /// specification that uses braces. 15796 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 15797 Decl *LinkageSpec, 15798 SourceLocation RBraceLoc) { 15799 if (RBraceLoc.isValid()) { 15800 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 15801 LSDecl->setRBraceLoc(RBraceLoc); 15802 } 15803 PopDeclContext(); 15804 return LinkageSpec; 15805 } 15806 15807 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 15808 const ParsedAttributesView &AttrList, 15809 SourceLocation SemiLoc) { 15810 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 15811 // Attribute declarations appertain to empty declaration so we handle 15812 // them here. 15813 ProcessDeclAttributeList(S, ED, AttrList); 15814 15815 CurContext->addDecl(ED); 15816 return ED; 15817 } 15818 15819 /// Perform semantic analysis for the variable declaration that 15820 /// occurs within a C++ catch clause, returning the newly-created 15821 /// variable. 15822 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 15823 TypeSourceInfo *TInfo, 15824 SourceLocation StartLoc, 15825 SourceLocation Loc, 15826 IdentifierInfo *Name) { 15827 bool Invalid = false; 15828 QualType ExDeclType = TInfo->getType(); 15829 15830 // Arrays and functions decay. 15831 if (ExDeclType->isArrayType()) 15832 ExDeclType = Context.getArrayDecayedType(ExDeclType); 15833 else if (ExDeclType->isFunctionType()) 15834 ExDeclType = Context.getPointerType(ExDeclType); 15835 15836 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 15837 // The exception-declaration shall not denote a pointer or reference to an 15838 // incomplete type, other than [cv] void*. 15839 // N2844 forbids rvalue references. 15840 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 15841 Diag(Loc, diag::err_catch_rvalue_ref); 15842 Invalid = true; 15843 } 15844 15845 if (ExDeclType->isVariablyModifiedType()) { 15846 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 15847 Invalid = true; 15848 } 15849 15850 QualType BaseType = ExDeclType; 15851 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 15852 unsigned DK = diag::err_catch_incomplete; 15853 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 15854 BaseType = Ptr->getPointeeType(); 15855 Mode = 1; 15856 DK = diag::err_catch_incomplete_ptr; 15857 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 15858 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 15859 BaseType = Ref->getPointeeType(); 15860 Mode = 2; 15861 DK = diag::err_catch_incomplete_ref; 15862 } 15863 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 15864 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 15865 Invalid = true; 15866 15867 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) { 15868 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType; 15869 Invalid = true; 15870 } 15871 15872 if (!Invalid && !ExDeclType->isDependentType() && 15873 RequireNonAbstractType(Loc, ExDeclType, 15874 diag::err_abstract_type_in_decl, 15875 AbstractVariableType)) 15876 Invalid = true; 15877 15878 // Only the non-fragile NeXT runtime currently supports C++ catches 15879 // of ObjC types, and no runtime supports catching ObjC types by value. 15880 if (!Invalid && getLangOpts().ObjC) { 15881 QualType T = ExDeclType; 15882 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 15883 T = RT->getPointeeType(); 15884 15885 if (T->isObjCObjectType()) { 15886 Diag(Loc, diag::err_objc_object_catch); 15887 Invalid = true; 15888 } else if (T->isObjCObjectPointerType()) { 15889 // FIXME: should this be a test for macosx-fragile specifically? 15890 if (getLangOpts().ObjCRuntime.isFragile()) 15891 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 15892 } 15893 } 15894 15895 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 15896 ExDeclType, TInfo, SC_None); 15897 ExDecl->setExceptionVariable(true); 15898 15899 // In ARC, infer 'retaining' for variables of retainable type. 15900 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 15901 Invalid = true; 15902 15903 if (!Invalid && !ExDeclType->isDependentType()) { 15904 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 15905 // Insulate this from anything else we might currently be parsing. 15906 EnterExpressionEvaluationContext scope( 15907 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15908 15909 // C++ [except.handle]p16: 15910 // The object declared in an exception-declaration or, if the 15911 // exception-declaration does not specify a name, a temporary (12.2) is 15912 // copy-initialized (8.5) from the exception object. [...] 15913 // The object is destroyed when the handler exits, after the destruction 15914 // of any automatic objects initialized within the handler. 15915 // 15916 // We just pretend to initialize the object with itself, then make sure 15917 // it can be destroyed later. 15918 QualType initType = Context.getExceptionObjectType(ExDeclType); 15919 15920 InitializedEntity entity = 15921 InitializedEntity::InitializeVariable(ExDecl); 15922 InitializationKind initKind = 15923 InitializationKind::CreateCopy(Loc, SourceLocation()); 15924 15925 Expr *opaqueValue = 15926 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 15927 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 15928 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 15929 if (result.isInvalid()) 15930 Invalid = true; 15931 else { 15932 // If the constructor used was non-trivial, set this as the 15933 // "initializer". 15934 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 15935 if (!construct->getConstructor()->isTrivial()) { 15936 Expr *init = MaybeCreateExprWithCleanups(construct); 15937 ExDecl->setInit(init); 15938 } 15939 15940 // And make sure it's destructable. 15941 FinalizeVarWithDestructor(ExDecl, recordType); 15942 } 15943 } 15944 } 15945 15946 if (Invalid) 15947 ExDecl->setInvalidDecl(); 15948 15949 return ExDecl; 15950 } 15951 15952 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 15953 /// handler. 15954 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 15955 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15956 bool Invalid = D.isInvalidType(); 15957 15958 // Check for unexpanded parameter packs. 15959 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15960 UPPC_ExceptionType)) { 15961 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 15962 D.getIdentifierLoc()); 15963 Invalid = true; 15964 } 15965 15966 IdentifierInfo *II = D.getIdentifier(); 15967 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 15968 LookupOrdinaryName, 15969 ForVisibleRedeclaration)) { 15970 // The scope should be freshly made just for us. There is just no way 15971 // it contains any previous declaration, except for function parameters in 15972 // a function-try-block's catch statement. 15973 assert(!S->isDeclScope(PrevDecl)); 15974 if (isDeclInScope(PrevDecl, CurContext, S)) { 15975 Diag(D.getIdentifierLoc(), diag::err_redefinition) 15976 << D.getIdentifier(); 15977 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 15978 Invalid = true; 15979 } else if (PrevDecl->isTemplateParameter()) 15980 // Maybe we will complain about the shadowed template parameter. 15981 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15982 } 15983 15984 if (D.getCXXScopeSpec().isSet() && !Invalid) { 15985 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 15986 << D.getCXXScopeSpec().getRange(); 15987 Invalid = true; 15988 } 15989 15990 VarDecl *ExDecl = BuildExceptionDeclaration( 15991 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 15992 if (Invalid) 15993 ExDecl->setInvalidDecl(); 15994 15995 // Add the exception declaration into this scope. 15996 if (II) 15997 PushOnScopeChains(ExDecl, S); 15998 else 15999 CurContext->addDecl(ExDecl); 16000 16001 ProcessDeclAttributes(S, ExDecl, D); 16002 return ExDecl; 16003 } 16004 16005 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16006 Expr *AssertExpr, 16007 Expr *AssertMessageExpr, 16008 SourceLocation RParenLoc) { 16009 StringLiteral *AssertMessage = 16010 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 16011 16012 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 16013 return nullptr; 16014 16015 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 16016 AssertMessage, RParenLoc, false); 16017 } 16018 16019 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16020 Expr *AssertExpr, 16021 StringLiteral *AssertMessage, 16022 SourceLocation RParenLoc, 16023 bool Failed) { 16024 assert(AssertExpr != nullptr && "Expected non-null condition"); 16025 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 16026 !Failed) { 16027 // In a static_assert-declaration, the constant-expression shall be a 16028 // constant expression that can be contextually converted to bool. 16029 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 16030 if (Converted.isInvalid()) 16031 Failed = true; 16032 16033 ExprResult FullAssertExpr = 16034 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 16035 /*DiscardedValue*/ false, 16036 /*IsConstexpr*/ true); 16037 if (FullAssertExpr.isInvalid()) 16038 Failed = true; 16039 else 16040 AssertExpr = FullAssertExpr.get(); 16041 16042 llvm::APSInt Cond; 16043 if (!Failed && VerifyIntegerConstantExpression( 16044 AssertExpr, &Cond, 16045 diag::err_static_assert_expression_is_not_constant) 16046 .isInvalid()) 16047 Failed = true; 16048 16049 if (!Failed && !Cond) { 16050 SmallString<256> MsgBuffer; 16051 llvm::raw_svector_ostream Msg(MsgBuffer); 16052 if (AssertMessage) 16053 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 16054 16055 Expr *InnerCond = nullptr; 16056 std::string InnerCondDescription; 16057 std::tie(InnerCond, InnerCondDescription) = 16058 findFailedBooleanCondition(Converted.get()); 16059 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 16060 // Drill down into concept specialization expressions to see why they 16061 // weren't satisfied. 16062 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16063 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16064 ConstraintSatisfaction Satisfaction; 16065 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 16066 DiagnoseUnsatisfiedConstraint(Satisfaction); 16067 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 16068 && !isa<IntegerLiteral>(InnerCond)) { 16069 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 16070 << InnerCondDescription << !AssertMessage 16071 << Msg.str() << InnerCond->getSourceRange(); 16072 } else { 16073 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16074 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16075 } 16076 Failed = true; 16077 } 16078 } else { 16079 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 16080 /*DiscardedValue*/false, 16081 /*IsConstexpr*/true); 16082 if (FullAssertExpr.isInvalid()) 16083 Failed = true; 16084 else 16085 AssertExpr = FullAssertExpr.get(); 16086 } 16087 16088 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 16089 AssertExpr, AssertMessage, RParenLoc, 16090 Failed); 16091 16092 CurContext->addDecl(Decl); 16093 return Decl; 16094 } 16095 16096 /// Perform semantic analysis of the given friend type declaration. 16097 /// 16098 /// \returns A friend declaration that. 16099 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 16100 SourceLocation FriendLoc, 16101 TypeSourceInfo *TSInfo) { 16102 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 16103 16104 QualType T = TSInfo->getType(); 16105 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 16106 16107 // C++03 [class.friend]p2: 16108 // An elaborated-type-specifier shall be used in a friend declaration 16109 // for a class.* 16110 // 16111 // * The class-key of the elaborated-type-specifier is required. 16112 if (!CodeSynthesisContexts.empty()) { 16113 // Do not complain about the form of friend template types during any kind 16114 // of code synthesis. For template instantiation, we will have complained 16115 // when the template was defined. 16116 } else { 16117 if (!T->isElaboratedTypeSpecifier()) { 16118 // If we evaluated the type to a record type, suggest putting 16119 // a tag in front. 16120 if (const RecordType *RT = T->getAs<RecordType>()) { 16121 RecordDecl *RD = RT->getDecl(); 16122 16123 SmallString<16> InsertionText(" "); 16124 InsertionText += RD->getKindName(); 16125 16126 Diag(TypeRange.getBegin(), 16127 getLangOpts().CPlusPlus11 ? 16128 diag::warn_cxx98_compat_unelaborated_friend_type : 16129 diag::ext_unelaborated_friend_type) 16130 << (unsigned) RD->getTagKind() 16131 << T 16132 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 16133 InsertionText); 16134 } else { 16135 Diag(FriendLoc, 16136 getLangOpts().CPlusPlus11 ? 16137 diag::warn_cxx98_compat_nonclass_type_friend : 16138 diag::ext_nonclass_type_friend) 16139 << T 16140 << TypeRange; 16141 } 16142 } else if (T->getAs<EnumType>()) { 16143 Diag(FriendLoc, 16144 getLangOpts().CPlusPlus11 ? 16145 diag::warn_cxx98_compat_enum_friend : 16146 diag::ext_enum_friend) 16147 << T 16148 << TypeRange; 16149 } 16150 16151 // C++11 [class.friend]p3: 16152 // A friend declaration that does not declare a function shall have one 16153 // of the following forms: 16154 // friend elaborated-type-specifier ; 16155 // friend simple-type-specifier ; 16156 // friend typename-specifier ; 16157 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 16158 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 16159 } 16160 16161 // If the type specifier in a friend declaration designates a (possibly 16162 // cv-qualified) class type, that class is declared as a friend; otherwise, 16163 // the friend declaration is ignored. 16164 return FriendDecl::Create(Context, CurContext, 16165 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 16166 FriendLoc); 16167 } 16168 16169 /// Handle a friend tag declaration where the scope specifier was 16170 /// templated. 16171 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 16172 unsigned TagSpec, SourceLocation TagLoc, 16173 CXXScopeSpec &SS, IdentifierInfo *Name, 16174 SourceLocation NameLoc, 16175 const ParsedAttributesView &Attr, 16176 MultiTemplateParamsArg TempParamLists) { 16177 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16178 16179 bool IsMemberSpecialization = false; 16180 bool Invalid = false; 16181 16182 if (TemplateParameterList *TemplateParams = 16183 MatchTemplateParametersToScopeSpecifier( 16184 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 16185 IsMemberSpecialization, Invalid)) { 16186 if (TemplateParams->size() > 0) { 16187 // This is a declaration of a class template. 16188 if (Invalid) 16189 return nullptr; 16190 16191 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 16192 NameLoc, Attr, TemplateParams, AS_public, 16193 /*ModulePrivateLoc=*/SourceLocation(), 16194 FriendLoc, TempParamLists.size() - 1, 16195 TempParamLists.data()).get(); 16196 } else { 16197 // The "template<>" header is extraneous. 16198 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16199 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16200 IsMemberSpecialization = true; 16201 } 16202 } 16203 16204 if (Invalid) return nullptr; 16205 16206 bool isAllExplicitSpecializations = true; 16207 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 16208 if (TempParamLists[I]->size()) { 16209 isAllExplicitSpecializations = false; 16210 break; 16211 } 16212 } 16213 16214 // FIXME: don't ignore attributes. 16215 16216 // If it's explicit specializations all the way down, just forget 16217 // about the template header and build an appropriate non-templated 16218 // friend. TODO: for source fidelity, remember the headers. 16219 if (isAllExplicitSpecializations) { 16220 if (SS.isEmpty()) { 16221 bool Owned = false; 16222 bool IsDependent = false; 16223 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 16224 Attr, AS_public, 16225 /*ModulePrivateLoc=*/SourceLocation(), 16226 MultiTemplateParamsArg(), Owned, IsDependent, 16227 /*ScopedEnumKWLoc=*/SourceLocation(), 16228 /*ScopedEnumUsesClassTag=*/false, 16229 /*UnderlyingType=*/TypeResult(), 16230 /*IsTypeSpecifier=*/false, 16231 /*IsTemplateParamOrArg=*/false); 16232 } 16233 16234 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 16235 ElaboratedTypeKeyword Keyword 16236 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16237 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 16238 *Name, NameLoc); 16239 if (T.isNull()) 16240 return nullptr; 16241 16242 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16243 if (isa<DependentNameType>(T)) { 16244 DependentNameTypeLoc TL = 16245 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16246 TL.setElaboratedKeywordLoc(TagLoc); 16247 TL.setQualifierLoc(QualifierLoc); 16248 TL.setNameLoc(NameLoc); 16249 } else { 16250 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 16251 TL.setElaboratedKeywordLoc(TagLoc); 16252 TL.setQualifierLoc(QualifierLoc); 16253 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 16254 } 16255 16256 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16257 TSI, FriendLoc, TempParamLists); 16258 Friend->setAccess(AS_public); 16259 CurContext->addDecl(Friend); 16260 return Friend; 16261 } 16262 16263 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 16264 16265 16266 16267 // Handle the case of a templated-scope friend class. e.g. 16268 // template <class T> class A<T>::B; 16269 // FIXME: we don't support these right now. 16270 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 16271 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 16272 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16273 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 16274 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16275 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16276 TL.setElaboratedKeywordLoc(TagLoc); 16277 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 16278 TL.setNameLoc(NameLoc); 16279 16280 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16281 TSI, FriendLoc, TempParamLists); 16282 Friend->setAccess(AS_public); 16283 Friend->setUnsupportedFriend(true); 16284 CurContext->addDecl(Friend); 16285 return Friend; 16286 } 16287 16288 /// Handle a friend type declaration. This works in tandem with 16289 /// ActOnTag. 16290 /// 16291 /// Notes on friend class templates: 16292 /// 16293 /// We generally treat friend class declarations as if they were 16294 /// declaring a class. So, for example, the elaborated type specifier 16295 /// in a friend declaration is required to obey the restrictions of a 16296 /// class-head (i.e. no typedefs in the scope chain), template 16297 /// parameters are required to match up with simple template-ids, &c. 16298 /// However, unlike when declaring a template specialization, it's 16299 /// okay to refer to a template specialization without an empty 16300 /// template parameter declaration, e.g. 16301 /// friend class A<T>::B<unsigned>; 16302 /// We permit this as a special case; if there are any template 16303 /// parameters present at all, require proper matching, i.e. 16304 /// template <> template \<class T> friend class A<int>::B; 16305 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 16306 MultiTemplateParamsArg TempParams) { 16307 SourceLocation Loc = DS.getBeginLoc(); 16308 16309 assert(DS.isFriendSpecified()); 16310 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16311 16312 // C++ [class.friend]p3: 16313 // A friend declaration that does not declare a function shall have one of 16314 // the following forms: 16315 // friend elaborated-type-specifier ; 16316 // friend simple-type-specifier ; 16317 // friend typename-specifier ; 16318 // 16319 // Any declaration with a type qualifier does not have that form. (It's 16320 // legal to specify a qualified type as a friend, you just can't write the 16321 // keywords.) 16322 if (DS.getTypeQualifiers()) { 16323 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 16324 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 16325 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 16326 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 16327 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 16328 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 16329 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 16330 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 16331 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 16332 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 16333 } 16334 16335 // Try to convert the decl specifier to a type. This works for 16336 // friend templates because ActOnTag never produces a ClassTemplateDecl 16337 // for a TUK_Friend. 16338 Declarator TheDeclarator(DS, DeclaratorContext::Member); 16339 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 16340 QualType T = TSI->getType(); 16341 if (TheDeclarator.isInvalidType()) 16342 return nullptr; 16343 16344 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 16345 return nullptr; 16346 16347 // This is definitely an error in C++98. It's probably meant to 16348 // be forbidden in C++0x, too, but the specification is just 16349 // poorly written. 16350 // 16351 // The problem is with declarations like the following: 16352 // template <T> friend A<T>::foo; 16353 // where deciding whether a class C is a friend or not now hinges 16354 // on whether there exists an instantiation of A that causes 16355 // 'foo' to equal C. There are restrictions on class-heads 16356 // (which we declare (by fiat) elaborated friend declarations to 16357 // be) that makes this tractable. 16358 // 16359 // FIXME: handle "template <> friend class A<T>;", which 16360 // is possibly well-formed? Who even knows? 16361 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 16362 Diag(Loc, diag::err_tagless_friend_type_template) 16363 << DS.getSourceRange(); 16364 return nullptr; 16365 } 16366 16367 // C++98 [class.friend]p1: A friend of a class is a function 16368 // or class that is not a member of the class . . . 16369 // This is fixed in DR77, which just barely didn't make the C++03 16370 // deadline. It's also a very silly restriction that seriously 16371 // affects inner classes and which nobody else seems to implement; 16372 // thus we never diagnose it, not even in -pedantic. 16373 // 16374 // But note that we could warn about it: it's always useless to 16375 // friend one of your own members (it's not, however, worthless to 16376 // friend a member of an arbitrary specialization of your template). 16377 16378 Decl *D; 16379 if (!TempParams.empty()) 16380 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 16381 TempParams, 16382 TSI, 16383 DS.getFriendSpecLoc()); 16384 else 16385 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 16386 16387 if (!D) 16388 return nullptr; 16389 16390 D->setAccess(AS_public); 16391 CurContext->addDecl(D); 16392 16393 return D; 16394 } 16395 16396 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 16397 MultiTemplateParamsArg TemplateParams) { 16398 const DeclSpec &DS = D.getDeclSpec(); 16399 16400 assert(DS.isFriendSpecified()); 16401 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16402 16403 SourceLocation Loc = D.getIdentifierLoc(); 16404 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16405 16406 // C++ [class.friend]p1 16407 // A friend of a class is a function or class.... 16408 // Note that this sees through typedefs, which is intended. 16409 // It *doesn't* see through dependent types, which is correct 16410 // according to [temp.arg.type]p3: 16411 // If a declaration acquires a function type through a 16412 // type dependent on a template-parameter and this causes 16413 // a declaration that does not use the syntactic form of a 16414 // function declarator to have a function type, the program 16415 // is ill-formed. 16416 if (!TInfo->getType()->isFunctionType()) { 16417 Diag(Loc, diag::err_unexpected_friend); 16418 16419 // It might be worthwhile to try to recover by creating an 16420 // appropriate declaration. 16421 return nullptr; 16422 } 16423 16424 // C++ [namespace.memdef]p3 16425 // - If a friend declaration in a non-local class first declares a 16426 // class or function, the friend class or function is a member 16427 // of the innermost enclosing namespace. 16428 // - The name of the friend is not found by simple name lookup 16429 // until a matching declaration is provided in that namespace 16430 // scope (either before or after the class declaration granting 16431 // friendship). 16432 // - If a friend function is called, its name may be found by the 16433 // name lookup that considers functions from namespaces and 16434 // classes associated with the types of the function arguments. 16435 // - When looking for a prior declaration of a class or a function 16436 // declared as a friend, scopes outside the innermost enclosing 16437 // namespace scope are not considered. 16438 16439 CXXScopeSpec &SS = D.getCXXScopeSpec(); 16440 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 16441 assert(NameInfo.getName()); 16442 16443 // Check for unexpanded parameter packs. 16444 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 16445 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 16446 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 16447 return nullptr; 16448 16449 // The context we found the declaration in, or in which we should 16450 // create the declaration. 16451 DeclContext *DC; 16452 Scope *DCScope = S; 16453 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 16454 ForExternalRedeclaration); 16455 16456 // There are five cases here. 16457 // - There's no scope specifier and we're in a local class. Only look 16458 // for functions declared in the immediately-enclosing block scope. 16459 // We recover from invalid scope qualifiers as if they just weren't there. 16460 FunctionDecl *FunctionContainingLocalClass = nullptr; 16461 if ((SS.isInvalid() || !SS.isSet()) && 16462 (FunctionContainingLocalClass = 16463 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 16464 // C++11 [class.friend]p11: 16465 // If a friend declaration appears in a local class and the name 16466 // specified is an unqualified name, a prior declaration is 16467 // looked up without considering scopes that are outside the 16468 // innermost enclosing non-class scope. For a friend function 16469 // declaration, if there is no prior declaration, the program is 16470 // ill-formed. 16471 16472 // Find the innermost enclosing non-class scope. This is the block 16473 // scope containing the local class definition (or for a nested class, 16474 // the outer local class). 16475 DCScope = S->getFnParent(); 16476 16477 // Look up the function name in the scope. 16478 Previous.clear(LookupLocalFriendName); 16479 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 16480 16481 if (!Previous.empty()) { 16482 // All possible previous declarations must have the same context: 16483 // either they were declared at block scope or they are members of 16484 // one of the enclosing local classes. 16485 DC = Previous.getRepresentativeDecl()->getDeclContext(); 16486 } else { 16487 // This is ill-formed, but provide the context that we would have 16488 // declared the function in, if we were permitted to, for error recovery. 16489 DC = FunctionContainingLocalClass; 16490 } 16491 adjustContextForLocalExternDecl(DC); 16492 16493 // C++ [class.friend]p6: 16494 // A function can be defined in a friend declaration of a class if and 16495 // only if the class is a non-local class (9.8), the function name is 16496 // unqualified, and the function has namespace scope. 16497 if (D.isFunctionDefinition()) { 16498 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 16499 } 16500 16501 // - There's no scope specifier, in which case we just go to the 16502 // appropriate scope and look for a function or function template 16503 // there as appropriate. 16504 } else if (SS.isInvalid() || !SS.isSet()) { 16505 // C++11 [namespace.memdef]p3: 16506 // If the name in a friend declaration is neither qualified nor 16507 // a template-id and the declaration is a function or an 16508 // elaborated-type-specifier, the lookup to determine whether 16509 // the entity has been previously declared shall not consider 16510 // any scopes outside the innermost enclosing namespace. 16511 bool isTemplateId = 16512 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 16513 16514 // Find the appropriate context according to the above. 16515 DC = CurContext; 16516 16517 // Skip class contexts. If someone can cite chapter and verse 16518 // for this behavior, that would be nice --- it's what GCC and 16519 // EDG do, and it seems like a reasonable intent, but the spec 16520 // really only says that checks for unqualified existing 16521 // declarations should stop at the nearest enclosing namespace, 16522 // not that they should only consider the nearest enclosing 16523 // namespace. 16524 while (DC->isRecord()) 16525 DC = DC->getParent(); 16526 16527 DeclContext *LookupDC = DC; 16528 while (LookupDC->isTransparentContext()) 16529 LookupDC = LookupDC->getParent(); 16530 16531 while (true) { 16532 LookupQualifiedName(Previous, LookupDC); 16533 16534 if (!Previous.empty()) { 16535 DC = LookupDC; 16536 break; 16537 } 16538 16539 if (isTemplateId) { 16540 if (isa<TranslationUnitDecl>(LookupDC)) break; 16541 } else { 16542 if (LookupDC->isFileContext()) break; 16543 } 16544 LookupDC = LookupDC->getParent(); 16545 } 16546 16547 DCScope = getScopeForDeclContext(S, DC); 16548 16549 // - There's a non-dependent scope specifier, in which case we 16550 // compute it and do a previous lookup there for a function 16551 // or function template. 16552 } else if (!SS.getScopeRep()->isDependent()) { 16553 DC = computeDeclContext(SS); 16554 if (!DC) return nullptr; 16555 16556 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 16557 16558 LookupQualifiedName(Previous, DC); 16559 16560 // C++ [class.friend]p1: A friend of a class is a function or 16561 // class that is not a member of the class . . . 16562 if (DC->Equals(CurContext)) 16563 Diag(DS.getFriendSpecLoc(), 16564 getLangOpts().CPlusPlus11 ? 16565 diag::warn_cxx98_compat_friend_is_member : 16566 diag::err_friend_is_member); 16567 16568 if (D.isFunctionDefinition()) { 16569 // C++ [class.friend]p6: 16570 // A function can be defined in a friend declaration of a class if and 16571 // only if the class is a non-local class (9.8), the function name is 16572 // unqualified, and the function has namespace scope. 16573 // 16574 // FIXME: We should only do this if the scope specifier names the 16575 // innermost enclosing namespace; otherwise the fixit changes the 16576 // meaning of the code. 16577 SemaDiagnosticBuilder DB 16578 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 16579 16580 DB << SS.getScopeRep(); 16581 if (DC->isFileContext()) 16582 DB << FixItHint::CreateRemoval(SS.getRange()); 16583 SS.clear(); 16584 } 16585 16586 // - There's a scope specifier that does not match any template 16587 // parameter lists, in which case we use some arbitrary context, 16588 // create a method or method template, and wait for instantiation. 16589 // - There's a scope specifier that does match some template 16590 // parameter lists, which we don't handle right now. 16591 } else { 16592 if (D.isFunctionDefinition()) { 16593 // C++ [class.friend]p6: 16594 // A function can be defined in a friend declaration of a class if and 16595 // only if the class is a non-local class (9.8), the function name is 16596 // unqualified, and the function has namespace scope. 16597 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 16598 << SS.getScopeRep(); 16599 } 16600 16601 DC = CurContext; 16602 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 16603 } 16604 16605 if (!DC->isRecord()) { 16606 int DiagArg = -1; 16607 switch (D.getName().getKind()) { 16608 case UnqualifiedIdKind::IK_ConstructorTemplateId: 16609 case UnqualifiedIdKind::IK_ConstructorName: 16610 DiagArg = 0; 16611 break; 16612 case UnqualifiedIdKind::IK_DestructorName: 16613 DiagArg = 1; 16614 break; 16615 case UnqualifiedIdKind::IK_ConversionFunctionId: 16616 DiagArg = 2; 16617 break; 16618 case UnqualifiedIdKind::IK_DeductionGuideName: 16619 DiagArg = 3; 16620 break; 16621 case UnqualifiedIdKind::IK_Identifier: 16622 case UnqualifiedIdKind::IK_ImplicitSelfParam: 16623 case UnqualifiedIdKind::IK_LiteralOperatorId: 16624 case UnqualifiedIdKind::IK_OperatorFunctionId: 16625 case UnqualifiedIdKind::IK_TemplateId: 16626 break; 16627 } 16628 // This implies that it has to be an operator or function. 16629 if (DiagArg >= 0) { 16630 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 16631 return nullptr; 16632 } 16633 } 16634 16635 // FIXME: This is an egregious hack to cope with cases where the scope stack 16636 // does not contain the declaration context, i.e., in an out-of-line 16637 // definition of a class. 16638 Scope FakeDCScope(S, Scope::DeclScope, Diags); 16639 if (!DCScope) { 16640 FakeDCScope.setEntity(DC); 16641 DCScope = &FakeDCScope; 16642 } 16643 16644 bool AddToScope = true; 16645 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 16646 TemplateParams, AddToScope); 16647 if (!ND) return nullptr; 16648 16649 assert(ND->getLexicalDeclContext() == CurContext); 16650 16651 // If we performed typo correction, we might have added a scope specifier 16652 // and changed the decl context. 16653 DC = ND->getDeclContext(); 16654 16655 // Add the function declaration to the appropriate lookup tables, 16656 // adjusting the redeclarations list as necessary. We don't 16657 // want to do this yet if the friending class is dependent. 16658 // 16659 // Also update the scope-based lookup if the target context's 16660 // lookup context is in lexical scope. 16661 if (!CurContext->isDependentContext()) { 16662 DC = DC->getRedeclContext(); 16663 DC->makeDeclVisibleInContext(ND); 16664 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16665 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 16666 } 16667 16668 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 16669 D.getIdentifierLoc(), ND, 16670 DS.getFriendSpecLoc()); 16671 FrD->setAccess(AS_public); 16672 CurContext->addDecl(FrD); 16673 16674 if (ND->isInvalidDecl()) { 16675 FrD->setInvalidDecl(); 16676 } else { 16677 if (DC->isRecord()) CheckFriendAccess(ND); 16678 16679 FunctionDecl *FD; 16680 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 16681 FD = FTD->getTemplatedDecl(); 16682 else 16683 FD = cast<FunctionDecl>(ND); 16684 16685 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 16686 // default argument expression, that declaration shall be a definition 16687 // and shall be the only declaration of the function or function 16688 // template in the translation unit. 16689 if (functionDeclHasDefaultArgument(FD)) { 16690 // We can't look at FD->getPreviousDecl() because it may not have been set 16691 // if we're in a dependent context. If the function is known to be a 16692 // redeclaration, we will have narrowed Previous down to the right decl. 16693 if (D.isRedeclaration()) { 16694 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 16695 Diag(Previous.getRepresentativeDecl()->getLocation(), 16696 diag::note_previous_declaration); 16697 } else if (!D.isFunctionDefinition()) 16698 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 16699 } 16700 16701 // Mark templated-scope function declarations as unsupported. 16702 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 16703 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 16704 << SS.getScopeRep() << SS.getRange() 16705 << cast<CXXRecordDecl>(CurContext); 16706 FrD->setUnsupportedFriend(true); 16707 } 16708 } 16709 16710 return ND; 16711 } 16712 16713 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 16714 AdjustDeclIfTemplate(Dcl); 16715 16716 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 16717 if (!Fn) { 16718 Diag(DelLoc, diag::err_deleted_non_function); 16719 return; 16720 } 16721 16722 // Deleted function does not have a body. 16723 Fn->setWillHaveBody(false); 16724 16725 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 16726 // Don't consider the implicit declaration we generate for explicit 16727 // specializations. FIXME: Do not generate these implicit declarations. 16728 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 16729 Prev->getPreviousDecl()) && 16730 !Prev->isDefined()) { 16731 Diag(DelLoc, diag::err_deleted_decl_not_first); 16732 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 16733 Prev->isImplicit() ? diag::note_previous_implicit_declaration 16734 : diag::note_previous_declaration); 16735 // We can't recover from this; the declaration might have already 16736 // been used. 16737 Fn->setInvalidDecl(); 16738 return; 16739 } 16740 16741 // To maintain the invariant that functions are only deleted on their first 16742 // declaration, mark the implicitly-instantiated declaration of the 16743 // explicitly-specialized function as deleted instead of marking the 16744 // instantiated redeclaration. 16745 Fn = Fn->getCanonicalDecl(); 16746 } 16747 16748 // dllimport/dllexport cannot be deleted. 16749 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 16750 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 16751 Fn->setInvalidDecl(); 16752 } 16753 16754 // C++11 [basic.start.main]p3: 16755 // A program that defines main as deleted [...] is ill-formed. 16756 if (Fn->isMain()) 16757 Diag(DelLoc, diag::err_deleted_main); 16758 16759 // C++11 [dcl.fct.def.delete]p4: 16760 // A deleted function is implicitly inline. 16761 Fn->setImplicitlyInline(); 16762 Fn->setDeletedAsWritten(); 16763 } 16764 16765 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 16766 if (!Dcl || Dcl->isInvalidDecl()) 16767 return; 16768 16769 auto *FD = dyn_cast<FunctionDecl>(Dcl); 16770 if (!FD) { 16771 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 16772 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 16773 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 16774 return; 16775 } 16776 } 16777 16778 Diag(DefaultLoc, diag::err_default_special_members) 16779 << getLangOpts().CPlusPlus20; 16780 return; 16781 } 16782 16783 // Reject if this can't possibly be a defaultable function. 16784 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 16785 if (!DefKind && 16786 // A dependent function that doesn't locally look defaultable can 16787 // still instantiate to a defaultable function if it's a constructor 16788 // or assignment operator. 16789 (!FD->isDependentContext() || 16790 (!isa<CXXConstructorDecl>(FD) && 16791 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 16792 Diag(DefaultLoc, diag::err_default_special_members) 16793 << getLangOpts().CPlusPlus20; 16794 return; 16795 } 16796 16797 if (DefKind.isComparison() && 16798 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 16799 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class) 16800 << (int)DefKind.asComparison(); 16801 return; 16802 } 16803 16804 // Issue compatibility warning. We already warned if the operator is 16805 // 'operator<=>' when parsing the '<=>' token. 16806 if (DefKind.isComparison() && 16807 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 16808 Diag(DefaultLoc, getLangOpts().CPlusPlus20 16809 ? diag::warn_cxx17_compat_defaulted_comparison 16810 : diag::ext_defaulted_comparison); 16811 } 16812 16813 FD->setDefaulted(); 16814 FD->setExplicitlyDefaulted(); 16815 16816 // Defer checking functions that are defaulted in a dependent context. 16817 if (FD->isDependentContext()) 16818 return; 16819 16820 // Unset that we will have a body for this function. We might not, 16821 // if it turns out to be trivial, and we don't need this marking now 16822 // that we've marked it as defaulted. 16823 FD->setWillHaveBody(false); 16824 16825 // If this definition appears within the record, do the checking when 16826 // the record is complete. This is always the case for a defaulted 16827 // comparison. 16828 if (DefKind.isComparison()) 16829 return; 16830 auto *MD = cast<CXXMethodDecl>(FD); 16831 16832 const FunctionDecl *Primary = FD; 16833 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 16834 // Ask the template instantiation pattern that actually had the 16835 // '= default' on it. 16836 Primary = Pattern; 16837 16838 // If the method was defaulted on its first declaration, we will have 16839 // already performed the checking in CheckCompletedCXXClass. Such a 16840 // declaration doesn't trigger an implicit definition. 16841 if (Primary->getCanonicalDecl()->isDefaulted()) 16842 return; 16843 16844 // FIXME: Once we support defining comparisons out of class, check for a 16845 // defaulted comparison here. 16846 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 16847 MD->setInvalidDecl(); 16848 else 16849 DefineDefaultedFunction(*this, MD, DefaultLoc); 16850 } 16851 16852 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 16853 for (Stmt *SubStmt : S->children()) { 16854 if (!SubStmt) 16855 continue; 16856 if (isa<ReturnStmt>(SubStmt)) 16857 Self.Diag(SubStmt->getBeginLoc(), 16858 diag::err_return_in_constructor_handler); 16859 if (!isa<Expr>(SubStmt)) 16860 SearchForReturnInStmt(Self, SubStmt); 16861 } 16862 } 16863 16864 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 16865 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 16866 CXXCatchStmt *Handler = TryBlock->getHandler(I); 16867 SearchForReturnInStmt(*this, Handler); 16868 } 16869 } 16870 16871 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 16872 const CXXMethodDecl *Old) { 16873 const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); 16874 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); 16875 16876 if (OldFT->hasExtParameterInfos()) { 16877 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 16878 // A parameter of the overriding method should be annotated with noescape 16879 // if the corresponding parameter of the overridden method is annotated. 16880 if (OldFT->getExtParameterInfo(I).isNoEscape() && 16881 !NewFT->getExtParameterInfo(I).isNoEscape()) { 16882 Diag(New->getParamDecl(I)->getLocation(), 16883 diag::warn_overriding_method_missing_noescape); 16884 Diag(Old->getParamDecl(I)->getLocation(), 16885 diag::note_overridden_marked_noescape); 16886 } 16887 } 16888 16889 // Virtual overrides must have the same code_seg. 16890 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 16891 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 16892 if ((NewCSA || OldCSA) && 16893 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 16894 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 16895 Diag(Old->getLocation(), diag::note_previous_declaration); 16896 return true; 16897 } 16898 16899 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 16900 16901 // If the calling conventions match, everything is fine 16902 if (NewCC == OldCC) 16903 return false; 16904 16905 // If the calling conventions mismatch because the new function is static, 16906 // suppress the calling convention mismatch error; the error about static 16907 // function override (err_static_overrides_virtual from 16908 // Sema::CheckFunctionDeclaration) is more clear. 16909 if (New->getStorageClass() == SC_Static) 16910 return false; 16911 16912 Diag(New->getLocation(), 16913 diag::err_conflicting_overriding_cc_attributes) 16914 << New->getDeclName() << New->getType() << Old->getType(); 16915 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 16916 return true; 16917 } 16918 16919 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 16920 const CXXMethodDecl *Old) { 16921 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); 16922 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); 16923 16924 if (Context.hasSameType(NewTy, OldTy) || 16925 NewTy->isDependentType() || OldTy->isDependentType()) 16926 return false; 16927 16928 // Check if the return types are covariant 16929 QualType NewClassTy, OldClassTy; 16930 16931 /// Both types must be pointers or references to classes. 16932 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 16933 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 16934 NewClassTy = NewPT->getPointeeType(); 16935 OldClassTy = OldPT->getPointeeType(); 16936 } 16937 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 16938 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 16939 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 16940 NewClassTy = NewRT->getPointeeType(); 16941 OldClassTy = OldRT->getPointeeType(); 16942 } 16943 } 16944 } 16945 16946 // The return types aren't either both pointers or references to a class type. 16947 if (NewClassTy.isNull()) { 16948 Diag(New->getLocation(), 16949 diag::err_different_return_type_for_overriding_virtual_function) 16950 << New->getDeclName() << NewTy << OldTy 16951 << New->getReturnTypeSourceRange(); 16952 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16953 << Old->getReturnTypeSourceRange(); 16954 16955 return true; 16956 } 16957 16958 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 16959 // C++14 [class.virtual]p8: 16960 // If the class type in the covariant return type of D::f differs from 16961 // that of B::f, the class type in the return type of D::f shall be 16962 // complete at the point of declaration of D::f or shall be the class 16963 // type D. 16964 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 16965 if (!RT->isBeingDefined() && 16966 RequireCompleteType(New->getLocation(), NewClassTy, 16967 diag::err_covariant_return_incomplete, 16968 New->getDeclName())) 16969 return true; 16970 } 16971 16972 // Check if the new class derives from the old class. 16973 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 16974 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 16975 << New->getDeclName() << NewTy << OldTy 16976 << New->getReturnTypeSourceRange(); 16977 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16978 << Old->getReturnTypeSourceRange(); 16979 return true; 16980 } 16981 16982 // Check if we the conversion from derived to base is valid. 16983 if (CheckDerivedToBaseConversion( 16984 NewClassTy, OldClassTy, 16985 diag::err_covariant_return_inaccessible_base, 16986 diag::err_covariant_return_ambiguous_derived_to_base_conv, 16987 New->getLocation(), New->getReturnTypeSourceRange(), 16988 New->getDeclName(), nullptr)) { 16989 // FIXME: this note won't trigger for delayed access control 16990 // diagnostics, and it's impossible to get an undelayed error 16991 // here from access control during the original parse because 16992 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 16993 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16994 << Old->getReturnTypeSourceRange(); 16995 return true; 16996 } 16997 } 16998 16999 // The qualifiers of the return types must be the same. 17000 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 17001 Diag(New->getLocation(), 17002 diag::err_covariant_return_type_different_qualifications) 17003 << New->getDeclName() << NewTy << OldTy 17004 << New->getReturnTypeSourceRange(); 17005 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17006 << Old->getReturnTypeSourceRange(); 17007 return true; 17008 } 17009 17010 17011 // The new class type must have the same or less qualifiers as the old type. 17012 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 17013 Diag(New->getLocation(), 17014 diag::err_covariant_return_type_class_type_more_qualified) 17015 << New->getDeclName() << NewTy << OldTy 17016 << New->getReturnTypeSourceRange(); 17017 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17018 << Old->getReturnTypeSourceRange(); 17019 return true; 17020 } 17021 17022 return false; 17023 } 17024 17025 /// Mark the given method pure. 17026 /// 17027 /// \param Method the method to be marked pure. 17028 /// 17029 /// \param InitRange the source range that covers the "0" initializer. 17030 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 17031 SourceLocation EndLoc = InitRange.getEnd(); 17032 if (EndLoc.isValid()) 17033 Method->setRangeEnd(EndLoc); 17034 17035 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 17036 Method->setPure(); 17037 return false; 17038 } 17039 17040 if (!Method->isInvalidDecl()) 17041 Diag(Method->getLocation(), diag::err_non_virtual_pure) 17042 << Method->getDeclName() << InitRange; 17043 return true; 17044 } 17045 17046 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 17047 if (D->getFriendObjectKind()) 17048 Diag(D->getLocation(), diag::err_pure_friend); 17049 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 17050 CheckPureMethod(M, ZeroLoc); 17051 else 17052 Diag(D->getLocation(), diag::err_illegal_initializer); 17053 } 17054 17055 /// Determine whether the given declaration is a global variable or 17056 /// static data member. 17057 static bool isNonlocalVariable(const Decl *D) { 17058 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 17059 return Var->hasGlobalStorage(); 17060 17061 return false; 17062 } 17063 17064 /// Invoked when we are about to parse an initializer for the declaration 17065 /// 'Dcl'. 17066 /// 17067 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 17068 /// static data member of class X, names should be looked up in the scope of 17069 /// class X. If the declaration had a scope specifier, a scope will have 17070 /// been created and passed in for this purpose. Otherwise, S will be null. 17071 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 17072 // If there is no declaration, there was an error parsing it. 17073 if (!D || D->isInvalidDecl()) 17074 return; 17075 17076 // We will always have a nested name specifier here, but this declaration 17077 // might not be out of line if the specifier names the current namespace: 17078 // extern int n; 17079 // int ::n = 0; 17080 if (S && D->isOutOfLine()) 17081 EnterDeclaratorContext(S, D->getDeclContext()); 17082 17083 // If we are parsing the initializer for a static data member, push a 17084 // new expression evaluation context that is associated with this static 17085 // data member. 17086 if (isNonlocalVariable(D)) 17087 PushExpressionEvaluationContext( 17088 ExpressionEvaluationContext::PotentiallyEvaluated, D); 17089 } 17090 17091 /// Invoked after we are finished parsing an initializer for the declaration D. 17092 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 17093 // If there is no declaration, there was an error parsing it. 17094 if (!D || D->isInvalidDecl()) 17095 return; 17096 17097 if (isNonlocalVariable(D)) 17098 PopExpressionEvaluationContext(); 17099 17100 if (S && D->isOutOfLine()) 17101 ExitDeclaratorContext(S); 17102 } 17103 17104 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 17105 /// C++ if/switch/while/for statement. 17106 /// e.g: "if (int x = f()) {...}" 17107 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 17108 // C++ 6.4p2: 17109 // The declarator shall not specify a function or an array. 17110 // The type-specifier-seq shall not contain typedef and shall not declare a 17111 // new class or enumeration. 17112 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 17113 "Parser allowed 'typedef' as storage class of condition decl."); 17114 17115 Decl *Dcl = ActOnDeclarator(S, D); 17116 if (!Dcl) 17117 return true; 17118 17119 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 17120 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 17121 << D.getSourceRange(); 17122 return true; 17123 } 17124 17125 return Dcl; 17126 } 17127 17128 void Sema::LoadExternalVTableUses() { 17129 if (!ExternalSource) 17130 return; 17131 17132 SmallVector<ExternalVTableUse, 4> VTables; 17133 ExternalSource->ReadUsedVTables(VTables); 17134 SmallVector<VTableUse, 4> NewUses; 17135 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 17136 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 17137 = VTablesUsed.find(VTables[I].Record); 17138 // Even if a definition wasn't required before, it may be required now. 17139 if (Pos != VTablesUsed.end()) { 17140 if (!Pos->second && VTables[I].DefinitionRequired) 17141 Pos->second = true; 17142 continue; 17143 } 17144 17145 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 17146 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 17147 } 17148 17149 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 17150 } 17151 17152 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 17153 bool DefinitionRequired) { 17154 // Ignore any vtable uses in unevaluated operands or for classes that do 17155 // not have a vtable. 17156 if (!Class->isDynamicClass() || Class->isDependentContext() || 17157 CurContext->isDependentContext() || isUnevaluatedContext()) 17158 return; 17159 // Do not mark as used if compiling for the device outside of the target 17160 // region. 17161 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 17162 !isInOpenMPDeclareTargetContext() && 17163 !isInOpenMPTargetExecutionDirective()) { 17164 if (!DefinitionRequired) 17165 MarkVirtualMembersReferenced(Loc, Class); 17166 return; 17167 } 17168 17169 // Try to insert this class into the map. 17170 LoadExternalVTableUses(); 17171 Class = Class->getCanonicalDecl(); 17172 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 17173 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 17174 if (!Pos.second) { 17175 // If we already had an entry, check to see if we are promoting this vtable 17176 // to require a definition. If so, we need to reappend to the VTableUses 17177 // list, since we may have already processed the first entry. 17178 if (DefinitionRequired && !Pos.first->second) { 17179 Pos.first->second = true; 17180 } else { 17181 // Otherwise, we can early exit. 17182 return; 17183 } 17184 } else { 17185 // The Microsoft ABI requires that we perform the destructor body 17186 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 17187 // the deleting destructor is emitted with the vtable, not with the 17188 // destructor definition as in the Itanium ABI. 17189 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17190 CXXDestructorDecl *DD = Class->getDestructor(); 17191 if (DD && DD->isVirtual() && !DD->isDeleted()) { 17192 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 17193 // If this is an out-of-line declaration, marking it referenced will 17194 // not do anything. Manually call CheckDestructor to look up operator 17195 // delete(). 17196 ContextRAII SavedContext(*this, DD); 17197 CheckDestructor(DD); 17198 } else { 17199 MarkFunctionReferenced(Loc, Class->getDestructor()); 17200 } 17201 } 17202 } 17203 } 17204 17205 // Local classes need to have their virtual members marked 17206 // immediately. For all other classes, we mark their virtual members 17207 // at the end of the translation unit. 17208 if (Class->isLocalClass()) 17209 MarkVirtualMembersReferenced(Loc, Class); 17210 else 17211 VTableUses.push_back(std::make_pair(Class, Loc)); 17212 } 17213 17214 bool Sema::DefineUsedVTables() { 17215 LoadExternalVTableUses(); 17216 if (VTableUses.empty()) 17217 return false; 17218 17219 // Note: The VTableUses vector could grow as a result of marking 17220 // the members of a class as "used", so we check the size each 17221 // time through the loop and prefer indices (which are stable) to 17222 // iterators (which are not). 17223 bool DefinedAnything = false; 17224 for (unsigned I = 0; I != VTableUses.size(); ++I) { 17225 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 17226 if (!Class) 17227 continue; 17228 TemplateSpecializationKind ClassTSK = 17229 Class->getTemplateSpecializationKind(); 17230 17231 SourceLocation Loc = VTableUses[I].second; 17232 17233 bool DefineVTable = true; 17234 17235 // If this class has a key function, but that key function is 17236 // defined in another translation unit, we don't need to emit the 17237 // vtable even though we're using it. 17238 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 17239 if (KeyFunction && !KeyFunction->hasBody()) { 17240 // The key function is in another translation unit. 17241 DefineVTable = false; 17242 TemplateSpecializationKind TSK = 17243 KeyFunction->getTemplateSpecializationKind(); 17244 assert(TSK != TSK_ExplicitInstantiationDefinition && 17245 TSK != TSK_ImplicitInstantiation && 17246 "Instantiations don't have key functions"); 17247 (void)TSK; 17248 } else if (!KeyFunction) { 17249 // If we have a class with no key function that is the subject 17250 // of an explicit instantiation declaration, suppress the 17251 // vtable; it will live with the explicit instantiation 17252 // definition. 17253 bool IsExplicitInstantiationDeclaration = 17254 ClassTSK == TSK_ExplicitInstantiationDeclaration; 17255 for (auto R : Class->redecls()) { 17256 TemplateSpecializationKind TSK 17257 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 17258 if (TSK == TSK_ExplicitInstantiationDeclaration) 17259 IsExplicitInstantiationDeclaration = true; 17260 else if (TSK == TSK_ExplicitInstantiationDefinition) { 17261 IsExplicitInstantiationDeclaration = false; 17262 break; 17263 } 17264 } 17265 17266 if (IsExplicitInstantiationDeclaration) 17267 DefineVTable = false; 17268 } 17269 17270 // The exception specifications for all virtual members may be needed even 17271 // if we are not providing an authoritative form of the vtable in this TU. 17272 // We may choose to emit it available_externally anyway. 17273 if (!DefineVTable) { 17274 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 17275 continue; 17276 } 17277 17278 // Mark all of the virtual members of this class as referenced, so 17279 // that we can build a vtable. Then, tell the AST consumer that a 17280 // vtable for this class is required. 17281 DefinedAnything = true; 17282 MarkVirtualMembersReferenced(Loc, Class); 17283 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 17284 if (VTablesUsed[Canonical]) 17285 Consumer.HandleVTable(Class); 17286 17287 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 17288 // no key function or the key function is inlined. Don't warn in C++ ABIs 17289 // that lack key functions, since the user won't be able to make one. 17290 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 17291 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 17292 const FunctionDecl *KeyFunctionDef = nullptr; 17293 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 17294 KeyFunctionDef->isInlined())) { 17295 Diag(Class->getLocation(), 17296 ClassTSK == TSK_ExplicitInstantiationDefinition 17297 ? diag::warn_weak_template_vtable 17298 : diag::warn_weak_vtable) 17299 << Class; 17300 } 17301 } 17302 } 17303 VTableUses.clear(); 17304 17305 return DefinedAnything; 17306 } 17307 17308 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 17309 const CXXRecordDecl *RD) { 17310 for (const auto *I : RD->methods()) 17311 if (I->isVirtual() && !I->isPure()) 17312 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 17313 } 17314 17315 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 17316 const CXXRecordDecl *RD, 17317 bool ConstexprOnly) { 17318 // Mark all functions which will appear in RD's vtable as used. 17319 CXXFinalOverriderMap FinalOverriders; 17320 RD->getFinalOverriders(FinalOverriders); 17321 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 17322 E = FinalOverriders.end(); 17323 I != E; ++I) { 17324 for (OverridingMethods::const_iterator OI = I->second.begin(), 17325 OE = I->second.end(); 17326 OI != OE; ++OI) { 17327 assert(OI->second.size() > 0 && "no final overrider"); 17328 CXXMethodDecl *Overrider = OI->second.front().Method; 17329 17330 // C++ [basic.def.odr]p2: 17331 // [...] A virtual member function is used if it is not pure. [...] 17332 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 17333 MarkFunctionReferenced(Loc, Overrider); 17334 } 17335 } 17336 17337 // Only classes that have virtual bases need a VTT. 17338 if (RD->getNumVBases() == 0) 17339 return; 17340 17341 for (const auto &I : RD->bases()) { 17342 const auto *Base = 17343 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 17344 if (Base->getNumVBases() == 0) 17345 continue; 17346 MarkVirtualMembersReferenced(Loc, Base); 17347 } 17348 } 17349 17350 /// SetIvarInitializers - This routine builds initialization ASTs for the 17351 /// Objective-C implementation whose ivars need be initialized. 17352 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 17353 if (!getLangOpts().CPlusPlus) 17354 return; 17355 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 17356 SmallVector<ObjCIvarDecl*, 8> ivars; 17357 CollectIvarsToConstructOrDestruct(OID, ivars); 17358 if (ivars.empty()) 17359 return; 17360 SmallVector<CXXCtorInitializer*, 32> AllToInit; 17361 for (unsigned i = 0; i < ivars.size(); i++) { 17362 FieldDecl *Field = ivars[i]; 17363 if (Field->isInvalidDecl()) 17364 continue; 17365 17366 CXXCtorInitializer *Member; 17367 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 17368 InitializationKind InitKind = 17369 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 17370 17371 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 17372 ExprResult MemberInit = 17373 InitSeq.Perform(*this, InitEntity, InitKind, None); 17374 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 17375 // Note, MemberInit could actually come back empty if no initialization 17376 // is required (e.g., because it would call a trivial default constructor) 17377 if (!MemberInit.get() || MemberInit.isInvalid()) 17378 continue; 17379 17380 Member = 17381 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 17382 SourceLocation(), 17383 MemberInit.getAs<Expr>(), 17384 SourceLocation()); 17385 AllToInit.push_back(Member); 17386 17387 // Be sure that the destructor is accessible and is marked as referenced. 17388 if (const RecordType *RecordTy = 17389 Context.getBaseElementType(Field->getType()) 17390 ->getAs<RecordType>()) { 17391 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 17392 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 17393 MarkFunctionReferenced(Field->getLocation(), Destructor); 17394 CheckDestructorAccess(Field->getLocation(), Destructor, 17395 PDiag(diag::err_access_dtor_ivar) 17396 << Context.getBaseElementType(Field->getType())); 17397 } 17398 } 17399 } 17400 ObjCImplementation->setIvarInitializers(Context, 17401 AllToInit.data(), AllToInit.size()); 17402 } 17403 } 17404 17405 static 17406 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 17407 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 17408 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 17409 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 17410 Sema &S) { 17411 if (Ctor->isInvalidDecl()) 17412 return; 17413 17414 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 17415 17416 // Target may not be determinable yet, for instance if this is a dependent 17417 // call in an uninstantiated template. 17418 if (Target) { 17419 const FunctionDecl *FNTarget = nullptr; 17420 (void)Target->hasBody(FNTarget); 17421 Target = const_cast<CXXConstructorDecl*>( 17422 cast_or_null<CXXConstructorDecl>(FNTarget)); 17423 } 17424 17425 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 17426 // Avoid dereferencing a null pointer here. 17427 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 17428 17429 if (!Current.insert(Canonical).second) 17430 return; 17431 17432 // We know that beyond here, we aren't chaining into a cycle. 17433 if (!Target || !Target->isDelegatingConstructor() || 17434 Target->isInvalidDecl() || Valid.count(TCanonical)) { 17435 Valid.insert(Current.begin(), Current.end()); 17436 Current.clear(); 17437 // We've hit a cycle. 17438 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 17439 Current.count(TCanonical)) { 17440 // If we haven't diagnosed this cycle yet, do so now. 17441 if (!Invalid.count(TCanonical)) { 17442 S.Diag((*Ctor->init_begin())->getSourceLocation(), 17443 diag::warn_delegating_ctor_cycle) 17444 << Ctor; 17445 17446 // Don't add a note for a function delegating directly to itself. 17447 if (TCanonical != Canonical) 17448 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 17449 17450 CXXConstructorDecl *C = Target; 17451 while (C->getCanonicalDecl() != Canonical) { 17452 const FunctionDecl *FNTarget = nullptr; 17453 (void)C->getTargetConstructor()->hasBody(FNTarget); 17454 assert(FNTarget && "Ctor cycle through bodiless function"); 17455 17456 C = const_cast<CXXConstructorDecl*>( 17457 cast<CXXConstructorDecl>(FNTarget)); 17458 S.Diag(C->getLocation(), diag::note_which_delegates_to); 17459 } 17460 } 17461 17462 Invalid.insert(Current.begin(), Current.end()); 17463 Current.clear(); 17464 } else { 17465 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 17466 } 17467 } 17468 17469 17470 void Sema::CheckDelegatingCtorCycles() { 17471 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 17472 17473 for (DelegatingCtorDeclsType::iterator 17474 I = DelegatingCtorDecls.begin(ExternalSource), 17475 E = DelegatingCtorDecls.end(); 17476 I != E; ++I) 17477 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 17478 17479 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 17480 (*CI)->setInvalidDecl(); 17481 } 17482 17483 namespace { 17484 /// AST visitor that finds references to the 'this' expression. 17485 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 17486 Sema &S; 17487 17488 public: 17489 explicit FindCXXThisExpr(Sema &S) : S(S) { } 17490 17491 bool VisitCXXThisExpr(CXXThisExpr *E) { 17492 S.Diag(E->getLocation(), diag::err_this_static_member_func) 17493 << E->isImplicit(); 17494 return false; 17495 } 17496 }; 17497 } 17498 17499 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 17500 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17501 if (!TSInfo) 17502 return false; 17503 17504 TypeLoc TL = TSInfo->getTypeLoc(); 17505 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17506 if (!ProtoTL) 17507 return false; 17508 17509 // C++11 [expr.prim.general]p3: 17510 // [The expression this] shall not appear before the optional 17511 // cv-qualifier-seq and it shall not appear within the declaration of a 17512 // static member function (although its type and value category are defined 17513 // within a static member function as they are within a non-static member 17514 // function). [ Note: this is because declaration matching does not occur 17515 // until the complete declarator is known. - end note ] 17516 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17517 FindCXXThisExpr Finder(*this); 17518 17519 // If the return type came after the cv-qualifier-seq, check it now. 17520 if (Proto->hasTrailingReturn() && 17521 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 17522 return true; 17523 17524 // Check the exception specification. 17525 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 17526 return true; 17527 17528 // Check the trailing requires clause 17529 if (Expr *E = Method->getTrailingRequiresClause()) 17530 if (!Finder.TraverseStmt(E)) 17531 return true; 17532 17533 return checkThisInStaticMemberFunctionAttributes(Method); 17534 } 17535 17536 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 17537 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17538 if (!TSInfo) 17539 return false; 17540 17541 TypeLoc TL = TSInfo->getTypeLoc(); 17542 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17543 if (!ProtoTL) 17544 return false; 17545 17546 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17547 FindCXXThisExpr Finder(*this); 17548 17549 switch (Proto->getExceptionSpecType()) { 17550 case EST_Unparsed: 17551 case EST_Uninstantiated: 17552 case EST_Unevaluated: 17553 case EST_BasicNoexcept: 17554 case EST_NoThrow: 17555 case EST_DynamicNone: 17556 case EST_MSAny: 17557 case EST_None: 17558 break; 17559 17560 case EST_DependentNoexcept: 17561 case EST_NoexceptFalse: 17562 case EST_NoexceptTrue: 17563 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 17564 return true; 17565 LLVM_FALLTHROUGH; 17566 17567 case EST_Dynamic: 17568 for (const auto &E : Proto->exceptions()) { 17569 if (!Finder.TraverseType(E)) 17570 return true; 17571 } 17572 break; 17573 } 17574 17575 return false; 17576 } 17577 17578 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 17579 FindCXXThisExpr Finder(*this); 17580 17581 // Check attributes. 17582 for (const auto *A : Method->attrs()) { 17583 // FIXME: This should be emitted by tblgen. 17584 Expr *Arg = nullptr; 17585 ArrayRef<Expr *> Args; 17586 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 17587 Arg = G->getArg(); 17588 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 17589 Arg = G->getArg(); 17590 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 17591 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 17592 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 17593 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 17594 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 17595 Arg = ETLF->getSuccessValue(); 17596 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 17597 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 17598 Arg = STLF->getSuccessValue(); 17599 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 17600 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 17601 Arg = LR->getArg(); 17602 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 17603 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 17604 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 17605 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17606 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 17607 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17608 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 17609 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17610 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 17611 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17612 17613 if (Arg && !Finder.TraverseStmt(Arg)) 17614 return true; 17615 17616 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 17617 if (!Finder.TraverseStmt(Args[I])) 17618 return true; 17619 } 17620 } 17621 17622 return false; 17623 } 17624 17625 void Sema::checkExceptionSpecification( 17626 bool IsTopLevel, ExceptionSpecificationType EST, 17627 ArrayRef<ParsedType> DynamicExceptions, 17628 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 17629 SmallVectorImpl<QualType> &Exceptions, 17630 FunctionProtoType::ExceptionSpecInfo &ESI) { 17631 Exceptions.clear(); 17632 ESI.Type = EST; 17633 if (EST == EST_Dynamic) { 17634 Exceptions.reserve(DynamicExceptions.size()); 17635 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 17636 // FIXME: Preserve type source info. 17637 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 17638 17639 if (IsTopLevel) { 17640 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 17641 collectUnexpandedParameterPacks(ET, Unexpanded); 17642 if (!Unexpanded.empty()) { 17643 DiagnoseUnexpandedParameterPacks( 17644 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 17645 Unexpanded); 17646 continue; 17647 } 17648 } 17649 17650 // Check that the type is valid for an exception spec, and 17651 // drop it if not. 17652 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 17653 Exceptions.push_back(ET); 17654 } 17655 ESI.Exceptions = Exceptions; 17656 return; 17657 } 17658 17659 if (isComputedNoexcept(EST)) { 17660 assert((NoexceptExpr->isTypeDependent() || 17661 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 17662 Context.BoolTy) && 17663 "Parser should have made sure that the expression is boolean"); 17664 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 17665 ESI.Type = EST_BasicNoexcept; 17666 return; 17667 } 17668 17669 ESI.NoexceptExpr = NoexceptExpr; 17670 return; 17671 } 17672 } 17673 17674 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 17675 ExceptionSpecificationType EST, 17676 SourceRange SpecificationRange, 17677 ArrayRef<ParsedType> DynamicExceptions, 17678 ArrayRef<SourceRange> DynamicExceptionRanges, 17679 Expr *NoexceptExpr) { 17680 if (!MethodD) 17681 return; 17682 17683 // Dig out the method we're referring to. 17684 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 17685 MethodD = FunTmpl->getTemplatedDecl(); 17686 17687 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 17688 if (!Method) 17689 return; 17690 17691 // Check the exception specification. 17692 llvm::SmallVector<QualType, 4> Exceptions; 17693 FunctionProtoType::ExceptionSpecInfo ESI; 17694 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 17695 DynamicExceptionRanges, NoexceptExpr, Exceptions, 17696 ESI); 17697 17698 // Update the exception specification on the function type. 17699 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 17700 17701 if (Method->isStatic()) 17702 checkThisInStaticMemberFunctionExceptionSpec(Method); 17703 17704 if (Method->isVirtual()) { 17705 // Check overrides, which we previously had to delay. 17706 for (const CXXMethodDecl *O : Method->overridden_methods()) 17707 CheckOverridingFunctionExceptionSpec(Method, O); 17708 } 17709 } 17710 17711 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 17712 /// 17713 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 17714 SourceLocation DeclStart, Declarator &D, 17715 Expr *BitWidth, 17716 InClassInitStyle InitStyle, 17717 AccessSpecifier AS, 17718 const ParsedAttr &MSPropertyAttr) { 17719 IdentifierInfo *II = D.getIdentifier(); 17720 if (!II) { 17721 Diag(DeclStart, diag::err_anonymous_property); 17722 return nullptr; 17723 } 17724 SourceLocation Loc = D.getIdentifierLoc(); 17725 17726 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17727 QualType T = TInfo->getType(); 17728 if (getLangOpts().CPlusPlus) { 17729 CheckExtraCXXDefaultArguments(D); 17730 17731 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 17732 UPPC_DataMemberType)) { 17733 D.setInvalidType(); 17734 T = Context.IntTy; 17735 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 17736 } 17737 } 17738 17739 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 17740 17741 if (D.getDeclSpec().isInlineSpecified()) 17742 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 17743 << getLangOpts().CPlusPlus17; 17744 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 17745 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 17746 diag::err_invalid_thread) 17747 << DeclSpec::getSpecifierName(TSCS); 17748 17749 // Check to see if this name was declared as a member previously 17750 NamedDecl *PrevDecl = nullptr; 17751 LookupResult Previous(*this, II, Loc, LookupMemberName, 17752 ForVisibleRedeclaration); 17753 LookupName(Previous, S); 17754 switch (Previous.getResultKind()) { 17755 case LookupResult::Found: 17756 case LookupResult::FoundUnresolvedValue: 17757 PrevDecl = Previous.getAsSingle<NamedDecl>(); 17758 break; 17759 17760 case LookupResult::FoundOverloaded: 17761 PrevDecl = Previous.getRepresentativeDecl(); 17762 break; 17763 17764 case LookupResult::NotFound: 17765 case LookupResult::NotFoundInCurrentInstantiation: 17766 case LookupResult::Ambiguous: 17767 break; 17768 } 17769 17770 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17771 // Maybe we will complain about the shadowed template parameter. 17772 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 17773 // Just pretend that we didn't see the previous declaration. 17774 PrevDecl = nullptr; 17775 } 17776 17777 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 17778 PrevDecl = nullptr; 17779 17780 SourceLocation TSSL = D.getBeginLoc(); 17781 MSPropertyDecl *NewPD = 17782 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 17783 MSPropertyAttr.getPropertyDataGetter(), 17784 MSPropertyAttr.getPropertyDataSetter()); 17785 ProcessDeclAttributes(TUScope, NewPD, D); 17786 NewPD->setAccess(AS); 17787 17788 if (NewPD->isInvalidDecl()) 17789 Record->setInvalidDecl(); 17790 17791 if (D.getDeclSpec().isModulePrivateSpecified()) 17792 NewPD->setModulePrivate(); 17793 17794 if (NewPD->isInvalidDecl() && PrevDecl) { 17795 // Don't introduce NewFD into scope; there's already something 17796 // with the same name in the same scope. 17797 } else if (II) { 17798 PushOnScopeChains(NewPD, S); 17799 } else 17800 Record->addDecl(NewPD); 17801 17802 return NewPD; 17803 } 17804 17805 void Sema::ActOnStartFunctionDeclarationDeclarator( 17806 Declarator &Declarator, unsigned TemplateParameterDepth) { 17807 auto &Info = InventedParameterInfos.emplace_back(); 17808 TemplateParameterList *ExplicitParams = nullptr; 17809 ArrayRef<TemplateParameterList *> ExplicitLists = 17810 Declarator.getTemplateParameterLists(); 17811 if (!ExplicitLists.empty()) { 17812 bool IsMemberSpecialization, IsInvalid; 17813 ExplicitParams = MatchTemplateParametersToScopeSpecifier( 17814 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), 17815 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, 17816 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, 17817 /*SuppressDiagnostic=*/true); 17818 } 17819 if (ExplicitParams) { 17820 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); 17821 for (NamedDecl *Param : *ExplicitParams) 17822 Info.TemplateParams.push_back(Param); 17823 Info.NumExplicitTemplateParams = ExplicitParams->size(); 17824 } else { 17825 Info.AutoTemplateParameterDepth = TemplateParameterDepth; 17826 Info.NumExplicitTemplateParams = 0; 17827 } 17828 } 17829 17830 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { 17831 auto &FSI = InventedParameterInfos.back(); 17832 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { 17833 if (FSI.NumExplicitTemplateParams != 0) { 17834 TemplateParameterList *ExplicitParams = 17835 Declarator.getTemplateParameterLists().back(); 17836 Declarator.setInventedTemplateParameterList( 17837 TemplateParameterList::Create( 17838 Context, ExplicitParams->getTemplateLoc(), 17839 ExplicitParams->getLAngleLoc(), FSI.TemplateParams, 17840 ExplicitParams->getRAngleLoc(), 17841 ExplicitParams->getRequiresClause())); 17842 } else { 17843 Declarator.setInventedTemplateParameterList( 17844 TemplateParameterList::Create( 17845 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, 17846 SourceLocation(), /*RequiresClause=*/nullptr)); 17847 } 17848 } 17849 InventedParameterInfos.pop_back(); 17850 } 17851